import { spawn } from 'child_process';
import path from 'path';
import fs from 'fs';
import { resolveServerPaths } from '../utils/server-paths.js';
import { findPackageRoot } from '../utils/config.js';
function getEngineFromFile(cwd) {
    const engineFile = path.join(cwd, '.engine');
    if (fs.existsSync(engineFile)) {
        const content = fs.readFileSync(engineFile, 'utf-8').trim();
        if (['claude-code', 'opencode', 'auto'].includes(content)) {
            return content;
        }
    }
    return undefined;
}
export async function serverCommand(options = {}) {
    const userProjectDir = process.cwd();
    const port = process.env.PORT ?? '3001';
    let stopping = false;
    function startServer() {
        const { serverEntry, dashboardDist } = resolveServerPaths();
        // Re-read version on each start (picks up updates)
        let pkgVersion = '0.0.0';
        try {
            const pkg = JSON.parse(fs.readFileSync(path.join(findPackageRoot(), 'package.json'), 'utf-8'));
            pkgVersion = pkg.version ?? '0.0.0';
        }
        catch { /* ignore */ }
        // Read engine from .engine file (for engine switching)
        const engineFromFile = getEngineFromFile(userProjectDir);
        console.log(`Starting ExpxAgents server v${pkgVersion}...`);
        const child = spawn('node', [serverEntry], {
            cwd: userProjectDir,
            stdio: 'inherit',
            env: {
                ...process.env,
                NODE_ENV: 'production',
                DASHBOARD_DIST: dashboardDist,
                SQUADS_DIR: path.join(userProjectDir, 'squads'),
                DATA_DIR: path.join(userProjectDir, '.expxagents', 'data'),
                DOTENV_PATH: path.join(userProjectDir, '.env'),
                PORT: port,
                EXPXAGENTS_VERSION: pkgVersion,
                ...(engineFromFile ? { AGENT_ENGINE: engineFromFile } : {}),
            },
        });
        child.on('error', (err) => {
            console.error(`Failed to start server: ${err.message}`);
            console.error('Make sure you have the latest expxagents package installed.');
            process.exit(1);
        });
        if (options.tunnel) {
            // Give server 2s to start before opening tunnel
            setTimeout(async () => {
                try {
                    const { default: localtunnel } = await import('localtunnel');
                    const tunnel = await localtunnel({ port: Number(port) });
                    console.log(`\n  Public URL: ${tunnel.url}`);
                    console.log('  Share this to access your dashboard remotely.\n');
                    tunnel.on('close', () => console.log('[tunnel] Connection closed.'));
                    tunnel.on('error', (err) => console.error('[tunnel] Error:', err.message));
                    process.on('SIGINT', () => tunnel.close());
                    process.on('SIGTERM', () => tunnel.close());
                }
                catch (err) {
                    console.error('[tunnel] Failed to create tunnel:', err.message);
                }
            }, 2000);
        }
        child.on('exit', (code) => {
            if (stopping) {
                process.exit(code ?? 0);
                return;
            }
            // Exit code 0 = intentional restart (e.g. after auto-update)
            if (code === 0) {
                console.log('Server exited with code 0, restarting...');
                setTimeout(() => startServer(), 1000);
                return;
            }
            process.exit(code ?? 1);
        });
        process.on('SIGINT', () => { stopping = true; child.kill('SIGINT'); });
        process.on('SIGTERM', () => { stopping = true; child.kill('SIGTERM'); });
    }
    startServer();
}
