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

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

export const name = 'publish-site';
export const description = 'Rebuild and deploy the agent personal website to Cloudflare (includes all outputs, journal, memories, download zip)';

export async function execute(ctx) {
  try {
    // Build the site
    const buildResult = execSync('node scripts/build-site.mjs', {
      cwd: ROOT,
      encoding: 'utf-8',
      timeout: 30_000
    });
    console.log(buildResult);

    // Build the distributable zip (for download page)
    try {
      const zipResult = execSync('bash scripts/build-zip.sh', {
        cwd: ROOT,
        encoding: 'utf-8',
        timeout: 15_000
      });
      console.log(zipResult);
    } catch (zipErr) {
      console.log(`[publish-site] Zip build failed (not critical): ${zipErr.message}`);
    }

    // Try to deploy (will gracefully fail if wrangler isn't configured)
    try {
      const deployResult = execSync('node scripts/deploy.mjs', {
        cwd: ROOT,
        encoding: 'utf-8',
        timeout: 120_000
      });
      ctx.addEvent('system', 'agent', 'Website rebuilt and deployed to Cloudflare.');
      return 'Site rebuilt and deployed.';
    } catch (deployErr) {
      // Deploy failed but build succeeded — that's fine
      ctx.addEvent('system', 'agent', 'Website rebuilt locally. Deploy skipped (wrangler not configured).');
      return 'Site rebuilt locally (deploy requires wrangler setup).';
    }
  } catch (err) {
    console.error(`[publish-site] Build failed: ${err.message}`);
    return null;
  }
}

export default { name, description, execute };
