import { spawn } from 'child_process';
import fs from 'fs';
import path from 'path';
import { resolveServerPaths } from './server-paths.js';
/**
 * Ensure the production server is running on the given port.
 * If a dev server is detected (health OK but no dashboard), it is killed and replaced.
 */
export async function ensureProductionServer(port) {
    let serverRunning = false;
    let servingDashboard = false;
    try {
        const healthRes = await fetch(`http://localhost:${port}/api/health`);
        serverRunning = healthRes.ok;
    }
    catch {
        serverRunning = false;
    }
    if (serverRunning) {
        // Check if the server serves the dashboard (production mode)
        try {
            const dashRes = await fetch(`http://localhost:${port}/`, { redirect: 'manual' });
            const contentType = dashRes.headers.get('content-type') ?? '';
            servingDashboard = dashRes.ok && contentType.includes('text/html');
        }
        catch {
            servingDashboard = false;
        }
        if (servingDashboard) {
            return; // Production server already running, nothing to do
        }
        // Server is running but not serving dashboard (dev mode) — kill it
        console.log('Detected dev server on port ' + port + ', restarting in production mode...');
        try {
            const { execSync } = await import('child_process');
            execSync(`lsof -ti:${port} | xargs kill -9`, { stdio: 'ignore' });
            // Wait for port to free up
            await new Promise((resolve) => setTimeout(resolve, 1000));
        }
        catch {
            console.error(`Could not stop existing server on port ${port}. Stop it manually and retry.`);
            process.exit(1);
        }
    }
    // Start production server
    const { serverEntry, dashboardDist } = resolveServerPaths();
    if (!fs.existsSync(serverEntry)) {
        console.error(`Server not found at ${serverEntry}`);
        console.error('Run "npm run build" first, or install the latest expxagents package.');
        process.exit(1);
    }
    const userProjectDir = process.cwd();
    const dotenvPath = path.join(userProjectDir, '.env');
    const jwtSecret = process.env.JWT_SECRET ?? (await import('crypto')).randomBytes(32).toString('hex');
    console.log('Starting ExpxAgents server...');
    const child = spawn('node', [serverEntry], {
        cwd: userProjectDir,
        stdio: 'inherit',
        env: {
            ...process.env,
            NODE_ENV: 'production',
            DASHBOARD_DIST: dashboardDist,
            SQUADS_DIR: path.join(userProjectDir, 'squads'),
            DOTENV_PATH: dotenvPath,
            JWT_SECRET: jwtSecret,
            PORT: port,
        },
        detached: true,
    });
    child.on('error', (err) => {
        console.error(`Failed to start server: ${err.message}`);
        process.exit(1);
    });
    // Wait for server to start
    await new Promise((resolve) => setTimeout(resolve, 2000));
}
