import { Command } from 'commander';
function getBaseUrl() {
    const port = process.env.PORT ?? '3001';
    return `http://localhost:${port}`;
}
async function fetchWithAuth(path, options = {}) {
    const url = `${getBaseUrl()}${path}`;
    const res = await fetch(url, {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            ...options.headers,
        },
    });
    return res;
}
export function schedulerCommand() {
    const cmd = new Command('scheduler')
        .description('Manage scheduled squad executions');
    cmd.command('status')
        .description('Show status of all scheduled jobs')
        .action(async () => {
        try {
            const res = await fetchWithAuth('/api/scheduler');
            if (!res.ok) {
                console.error(`Error: ${res.status} ${res.statusText}`);
                process.exit(1);
            }
            const body = await res.json();
            const jobs = body.data;
            if (jobs.length === 0) {
                console.log('No scheduled jobs found.');
                return;
            }
            console.log('Scheduled Jobs:\n');
            for (const job of jobs) {
                const status = job.status === 'active' ? '● active' :
                    job.status === 'paused' ? '○ paused' : '✕ error';
                console.log(`  ${job.squad_name}  ${status}  ${job.cron_expression}  last: ${job.last_result ?? 'never'}`);
            }
        }
        catch {
            console.error('Could not connect to server. Is it running? (npx expxagents server)');
            process.exit(1);
        }
    });
    cmd.command('pause <squad>')
        .description('Pause a scheduled squad')
        .action(async (squad) => {
        const res = await fetchWithAuth(`/api/scheduler/${squad}/pause`, { method: 'POST' });
        if (res.ok)
            console.log(`Paused: ${squad}`);
        else
            console.error(`Failed to pause: ${res.statusText}`);
    });
    cmd.command('resume <squad>')
        .description('Resume a paused squad')
        .action(async (squad) => {
        const res = await fetchWithAuth(`/api/scheduler/${squad}/resume`, { method: 'POST' });
        if (res.ok)
            console.log(`Resumed: ${squad}`);
        else
            console.error(`Failed to resume: ${res.statusText}`);
    });
    cmd.command('trigger <squad>')
        .description('Trigger immediate execution of a squad')
        .action(async (squad) => {
        const res = await fetchWithAuth(`/api/scheduler/${squad}/trigger`, { method: 'POST' });
        if (res.ok)
            console.log(`Triggered: ${squad}`);
        else
            console.error(`Failed to trigger: ${res.statusText}`);
    });
    cmd.command('history [squad]')
        .description('Show execution history')
        .option('--limit <n>', 'Number of results', '20')
        .action(async (squad, opts) => {
        const path = squad
            ? `/api/scheduler/${squad}/history?limit=${opts.limit}`
            : `/api/activities/recent?limit=${opts.limit}`;
        const res = await fetchWithAuth(path);
        if (!res.ok) {
            console.error(`Error: ${res.statusText}`);
            process.exit(1);
        }
        const body = await res.json();
        const items = body.data;
        if (items.length === 0) {
            console.log('No history found.');
            return;
        }
        console.log('Execution History:\n');
        for (const item of items) {
            const status = item.status === 'completed' ? '✓' : item.status === 'failed' ? '✕' : '…';
            const dur = item.duration_ms ? `${Math.round(item.duration_ms / 1000)}s` : '-';
            console.log(`  ${status} ${item.squad_code}  ${item.started_at}  ${dur}  attempt:${item.attempt ?? 1}`);
        }
    });
    return cmd;
}
