/**
 * Nexus Prime — `nexus-prime watch`
 * Tail live SSE events from the running daemon in a colored terminal feed.
 */
import * as http from 'http';
const ANSI = {
    cyan: '\x1b[36m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    magenta: '\x1b[35m',
    red: '\x1b[31m',
    dim: '\x1b[2m',
    bold: '\x1b[1m',
    reset: '\x1b[0m',
};
const isTTY = process.stdout.isTTY === true && !process.env.NO_COLOR;
const c = (s, k) => isTTY ? `${ANSI[k]}${s}${ANSI.reset}` : s;
const DEFAULT_FILTER = /^(mcp\.|tokens\.|planner\.|phantom\.|license\.|install\.|orchestrator\.run)/;
function colorForType(type) {
    if (type.startsWith('mcp.'))
        return 'cyan';
    if (type.startsWith('tokens.'))
        return 'yellow';
    if (type.startsWith('license.'))
        return 'magenta';
    if (type.startsWith('phantom.'))
        return 'green';
    if (type.startsWith('install.'))
        return 'green';
    if (type.includes('error') || type.includes('fail') || type.includes('bad'))
        return 'red';
    return 'dim';
}
export async function runWatch(opts = {}) {
    const port = opts.port ?? Number(process.env.NEXUS_DASHBOARD_PORT ?? 3377);
    const filterRe = opts.all
        ? null
        : opts.filter
            ? new RegExp(opts.filter)
            : DEFAULT_FILTER;
    console.log(c('◆ Nexus Prime · Live Event Tail', 'cyan'));
    console.log(c(`  Stream: http://localhost:${port}/dashboard/events`, 'dim'));
    console.log(c(`  Filter: ${filterRe ? filterRe.source : 'all events'}`, 'dim'));
    console.log(c('  Press Ctrl-C to exit\n', 'dim'));
    let buf = '';
    const req = http.get({ hostname: 'localhost', port, path: '/dashboard/events', headers: { Accept: 'text/event-stream' } }, (res) => {
        if (res.statusCode !== 200) {
            console.error(c(`  ✗ Daemon not reachable (HTTP ${res.statusCode}). Start: nexus-prime daemon`, 'red'));
            process.exit(1);
        }
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
            buf += chunk;
            const lines = buf.split('\n');
            buf = lines.pop() ?? '';
            for (const line of lines) {
                if (!line.startsWith('data: '))
                    continue;
                try {
                    const evt = JSON.parse(line.slice(6));
                    const type = evt.type ?? evt.t ?? '';
                    if (filterRe && !filterRe.test(type))
                        continue;
                    const payload = evt.payload ?? evt.data ?? evt.p ?? {};
                    const summary = summarize(type, payload);
                    const ts = new Date().toTimeString().slice(0, 8);
                    process.stdout.write(`${c(ts, 'dim')} ${c(type.padEnd(36), colorForType(type))} ${summary}\n`);
                }
                catch { /* malformed JSON — skip */ }
            }
        });
        res.on('error', (err) => {
            console.error(c(`  Stream error: ${err.message}`, 'red'));
            process.exit(1);
        });
        res.on('close', () => {
            console.log(c('\n  Stream closed.', 'dim'));
            process.exit(0);
        });
    });
    req.on('error', (err) => {
        console.error(c(`  ✗ Cannot connect to daemon on port ${port}: ${err.message}`, 'red'));
        console.error(c('    Start daemon: nexus-prime daemon', 'dim'));
        process.exit(1);
    });
    process.on('SIGINT', () => {
        req.destroy();
        console.log(c('\n  Bye.', 'dim'));
        process.exit(0);
    });
}
function summarize(type, payload) {
    switch (type) {
        case 'mcp.call.start':
            return `→ ${payload.toolName ?? 'tool'}`;
        case 'mcp.call.complete':
            return payload.error
                ? c(`✗ ${payload.toolName ?? 'tool'} · ${String(payload.error).slice(0, 60)}`, 'red')
                : c(`✓ ${payload.toolName ?? 'tool'} · ${payload.durationMs ?? 0}ms`, 'green');
        case 'tokens.optimized':
            return `saved ${payload.savings ?? 0} · ${payload.pct ?? 0}% · src:${payload.source ?? 'unknown'}`;
        case 'planner.stage':
            return `${payload.stage ?? ''} · ${payload.status ?? ''}`;
        case 'orchestrator.run.start':
            return String(payload.goal ?? '').slice(0, 80);
        case 'orchestrator.run.complete':
            return `done · ${payload.durationMs ?? ''}ms`;
        case 'license.tierChanged':
            return `${payload.from ?? '?'} → ${String(payload.to ?? '?').toUpperCase()}`;
        case 'license.upgradeNudge':
            return String(payload.message ?? '').slice(0, 80);
        case 'install.step':
            return `[${payload.status ?? ''}] ${payload.label ?? ''} (${payload.step ?? '?'}/${payload.total ?? '?'})`;
        default:
            return String(payload.message ?? payload.summary ?? payload.goal ?? '').slice(0, 80);
    }
}
