#!/usr/bin/env node

/**
 * Deploy the agent's static site to Cloudflare Workers.
 *
 * Prerequisites:
 *   npm install -g wrangler
 *   wrangler login
 *
 * Usage:
 *   node scripts/deploy.mjs                  # build + deploy
 *   node scripts/deploy.mjs --build-only     # just build, no deploy
 *   node scripts/deploy.mjs --name my-agent  # deploy with custom worker name
 */

import { execSync } from 'child_process';
import { readFileSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..');
const SITE_DIR = join(ROOT, 'site');

// Parse CLI args
const args = process.argv.slice(2);
const buildOnly = args.includes('--build-only');
const nameFlag = args.indexOf('--name');
const workerName = nameFlag !== -1 ? args[nameFlag + 1] : null;

// Load agent config for defaults
let agentName = 'agent';
try {
  const config = JSON.parse(readFileSync(join(ROOT, 'config.json'), 'utf-8'));
  agentName = config.agentName || agentName;
} catch {}

const projectName = (workerName || 'ai-do-site').toLowerCase().replace(/[^a-z0-9-]/g, '-');

async function main() {
  // Step 1: Build the site
  console.log('[deploy] Building site...');
  execSync('node scripts/build-site.mjs', { cwd: ROOT, stdio: 'inherit' });

  if (buildOnly) {
    console.log('[deploy] Build complete (--build-only). Skipping deploy.');
    return;
  }

  // Step 2: Ensure wrangler is available
  try {
    execSync(process.platform === 'win32' ? 'where wrangler' : 'which wrangler', { stdio: 'ignore' });
  } catch {
    console.error('[deploy] wrangler CLI not found. Install with: npm install -g wrangler');
    console.error('[deploy] Then run: wrangler login');
    process.exit(1);
  }

  // Step 3: Write wrangler.toml with bindings
  const wranglerPath = join(SITE_DIR, 'wrangler.toml');
  console.log('[deploy] Writing wrangler.toml with KV + R2 bindings...');
  writeFileSync(wranglerPath, `name = "${projectName}"
compatibility_date = "2024-12-01"
pages_build_output_dir = "."

# KV namespace for rate limiting (IP-based daily quotas)
[[kv_namespaces]]
binding = "RATE_LIMITS"
id = "8f519f42430c45df88950912f7ceb69a"

# R2 bucket for large release files (DMG, EXE, ZIP > 25 MiB)
[[r2_buckets]]
binding = "RELEASES"
bucket_name = "ai-do-releases"
`);

  // Step 4: Deploy to Cloudflare Pages
  console.log(`[deploy] Deploying to Cloudflare Pages as "${projectName}"...`);
  try {
    const result = execSync(`wrangler pages deploy . --project-name ${projectName} --commit-dirty=true`, {
      cwd: SITE_DIR,
      stdio: 'pipe',
      encoding: 'utf-8'
    });
    console.log(result);

    // Try to extract the URL
    const urlMatch = result.match(/(https:\/\/[^\s]+\.(?:pages|workers)\.dev)/);
    if (urlMatch) {
      console.log(`\n[deploy] ✓ Live at: ${urlMatch[1]}`);
    }
  } catch (err) {
    const stderr = err.stderr || '';
    // Auto-create project if it doesn't exist yet
    if (stderr.includes('Project not found') || stderr.includes('8000007')) {
      console.log(`[deploy] Project "${projectName}" not found — creating it...`);
      try {
        execSync(`wrangler pages project create ${projectName} --production-branch main`, {
          stdio: 'pipe', encoding: 'utf-8'
        });
        const result = execSync(`wrangler pages deploy . --project-name ${projectName} --commit-dirty=true`, {
          cwd: SITE_DIR, stdio: 'pipe', encoding: 'utf-8'
        });
        console.log(result);
        const urlMatch = result.match(/(https:\/\/[^\s]+\.(?:pages|workers)\.dev)/);
        if (urlMatch) console.log(`\n[deploy] ✓ Live at: ${urlMatch[1]}`);
      } catch (createErr) {
        console.error('[deploy] Failed to create project:', createErr.stderr || createErr.message);
        process.exit(1);
      }
    } else {
      console.error('[deploy] Deploy failed:', stderr || err.stdout || err.message);
      console.error('[deploy] Make sure you have run: wrangler login');
      process.exit(1);
    }
  }

  console.log('[deploy] Done!');
  console.log('');
  console.log('[deploy] Post-deployment setup (run once for worker proxy):');
  console.log('  Or use: node scripts/release.mjs --secrets');
  console.log('');
  console.log(`  1. Create KV namespace:`);
  console.log(`     wrangler kv namespace create RATE_LIMITS`);
  console.log(`  2. Create R2 bucket (for desktop app downloads):`);
  console.log(`     wrangler r2 bucket create ai-do-releases`);
  console.log(`  3. Bind KV + R2 in Cloudflare dashboard:`);
  console.log(`     Pages > ${projectName} > Settings > Bindings`);
  console.log(`     - KV Namespace: RATE_LIMITS`);
  console.log(`     - R2 Bucket: RELEASES → ai-do-releases`);
  console.log(`  4. Set API key secrets:`);
  console.log(`     wrangler pages secret put APP_TOKEN --project-name ${projectName}`);
  console.log(`     wrangler pages secret put ANTHROPIC_API_KEY --project-name ${projectName}`);
  console.log(`     wrangler pages secret put XAI_API_KEY --project-name ${projectName}`);
  console.log(`     wrangler pages secret put OPENAI_API_KEY --project-name ${projectName}`);
  console.log('');
  console.log('  APP_TOKEN must match the token in config.mjs DEFAULTS.worker.token');
}

main().catch(err => {
  console.error('[deploy] Fatal error:', err);
  process.exit(1);
});
