import { randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, writeFileSync, copyFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { homedir } from 'node:os';

const dataDir = join(homedir(), '.agenticmail');
const configPath = join(dataDir, 'config.json');
const envPath = join(dirname(new URL(import.meta.url).pathname), '..', '.env');
const envExamplePath = join(dirname(new URL(import.meta.url).pathname), '..', '.env.example');

console.log('🔧 AgenticMail — First-time setup\n');

// Create data directory
if (!existsSync(dataDir)) {
  mkdirSync(dataDir, { recursive: true });
  console.log(`✅ Created data directory: ${dataDir}`);
}

// Generate master key
const masterKey = `mk_${randomBytes(24).toString('hex')}`;

// Generate Stalwart admin password
const stalwartPassword = randomBytes(16).toString('hex');

// Save config
const config = {
  masterKey,
  stalwart: {
    url: 'http://localhost:8080',
    adminUser: 'admin',
    adminPassword: stalwartPassword,
  },
  smtp: { host: 'localhost', port: 587 },
  imap: { host: 'localhost', port: 143 },
  api: { port: 3100, host: '127.0.0.1' },
  dataDir,
};

writeFileSync(configPath, JSON.stringify(config, null, 2));
console.log(`✅ Saved config: ${configPath}`);

// Create .env file
const envContent = `# Auto-generated by agenticmail init
STALWART_ADMIN_USER=admin
STALWART_ADMIN_PASSWORD=${stalwartPassword}
STALWART_URL=http://localhost:8080

AGENTICMAIL_MASTER_KEY=${masterKey}
AGENTICMAIL_API_PORT=3100
AGENTICMAIL_DATA_DIR=${dataDir}

SMTP_HOST=localhost
SMTP_PORT=587
IMAP_HOST=localhost
IMAP_PORT=143
`;

writeFileSync(envPath, envContent);
console.log(`✅ Created .env file`);

// We deliberately print the master key ONCE so the operator can copy
// it for the next step. Stalwart's admin password stays inside the
// .env file we just wrote — no need to also print it here (the user
// can `cat .env | grep STALWART_ADMIN_PASSWORD` if they need it).
// Avoid logging both — that's what CodeQL `js/clear-text-logging`
// was flagging on the prior version of this block.
console.log(`\n📋 Master API key (save this — won't be shown again):`);
console.log(`   ${masterKey}`);
console.log(`\n   Stalwart admin password is saved in ${envPath}`);
console.log(`\n🚀 Next steps:`);
console.log(`   1. docker compose up -d`);
console.log(`   2. npm run dev:api`);
console.log(`   3. Use the Master API Key to create agent accounts`);
