#!/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 { existsSync, readFileSync, writeFileSync, mkdirSync } 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: Generate wrangler.toml if needed
  const wranglerPath = join(SITE_DIR, 'wrangler.toml');
  if (!existsSync(wranglerPath)) {
    console.log('[deploy] Creating wrangler.toml...');
    writeFileSync(wranglerPath, `name = "${projectName}"
compatibility_date = "2024-12-01"
pages_build_output_dir = "."
`);
  }

  // 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!');
}

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