/**
 * `olam kg doctor` — diagnostic table for the kg-service container.
 *
 * 4 probes:
 *   1. Container state (running / stopped / missing)
 *   2. /health responds with ready=true
 *   3. /status lists at least one workspace (advisory; warn if empty)
 *   4. /classify round-trip works end-to-end (synthetic probe)
 *
 * Exit 0 on all-green; non-zero on first failure with remedy hint.
 * --json emits a machine-readable structure for monitoring pipelines.
 */
import pc from 'picocolors';
import { KgServiceContainerController } from './kg-service-container.js';
import { classify, health, KgServiceUnreachableError, status, } from '@olam/core/src/kg/kg-service-client.js';
import { printError, printHeader, printInfo, printSuccess, printWarning } from '../output.js';
async function runProbes() {
    const results = [];
    const controller = new KgServiceContainerController();
    // Probe 1: container state
    const state = controller.status();
    if (state.state === 'running') {
        results.push({ name: 'container', status: 'ok', detail: `running on :${state.port}` });
    }
    else if (state.state === 'stopped') {
        results.push({
            name: 'container',
            status: 'fail',
            detail: 'stopped',
            remedy: '`olam services up`',
        });
        return results; // Subsequent probes will all fail; short-circuit.
    }
    else {
        if (controller.imageMissingEverywhere()) {
            results.push({
                name: 'container',
                status: 'warn',
                detail: 'image not pulled (opt-out)',
                remedy: '`olam bootstrap` (without --skip-kg-service) to pull olam-kg-service',
            });
        }
        else {
            results.push({
                name: 'container',
                status: 'fail',
                detail: 'missing',
                remedy: '`olam services up`',
            });
        }
        return results;
    }
    // Probe 2: /health
    try {
        const h = await health({ timeoutMs: 2_000 });
        if (h.ready) {
            results.push({ name: 'health', status: 'ok', detail: `ready · v${h.version}` });
        }
        else {
            results.push({
                name: 'health',
                status: 'warn',
                detail: `service up but not ready (still warming up?)`,
                remedy: 'Wait a few seconds and re-run',
            });
        }
    }
    catch (err) {
        results.push({
            name: 'health',
            status: 'fail',
            detail: err instanceof Error ? err.message : String(err),
            remedy: 'Check `docker logs olam-kg-service`',
        });
        return results;
    }
    // Probe 3: /status (workspace enumeration)
    try {
        const s = await status({ timeoutMs: 2_000 });
        if (s.workspaces.length === 0) {
            results.push({
                name: 'workspaces',
                status: 'warn',
                detail: 'no workspaces built yet',
                remedy: '`olam kg build` to index a workspace',
            });
        }
        else {
            results.push({
                name: 'workspaces',
                status: 'ok',
                detail: `${s.workspaces.length} indexed: ${s.workspaces.map((w) => w.name).join(', ')}`,
            });
        }
    }
    catch (err) {
        results.push({
            name: 'workspaces',
            status: 'fail',
            detail: err instanceof Error ? err.message : String(err),
        });
    }
    // Probe 4: /classify round-trip
    try {
        const r = await classify({ q: 'doctor probe' }, { timeoutMs: 3_000 });
        if (r.route && r.took_ms != null) {
            results.push({
                name: 'classify',
                status: 'ok',
                detail: `round-trip ok · ${r.took_ms}ms · layer ${r.layer}`,
            });
        }
        else {
            results.push({
                name: 'classify',
                status: 'warn',
                detail: 'unexpected response shape',
            });
        }
    }
    catch (err) {
        if (err instanceof KgServiceUnreachableError) {
            results.push({
                name: 'classify',
                status: 'fail',
                detail: 'kg-service unreachable',
                remedy: '`olam services up`',
            });
        }
        else {
            results.push({
                name: 'classify',
                status: 'fail',
                detail: err instanceof Error ? err.message : String(err),
            });
        }
    }
    return results;
}
export function registerKgDoctorCommand(kg) {
    kg.command('doctor')
        .description('Diagnostic table for kg-service (container + /health + workspaces + classify round-trip)')
        .option('--json', 'Emit machine-readable JSON instead of the formatted table')
        .action(async (opts) => {
        const probes = await runProbes();
        if (opts.json) {
            process.stdout.write(JSON.stringify({ probes }, null, 2) + '\n');
        }
        else {
            printHeader('kg-service doctor');
            for (const p of probes) {
                const badge = p.status === 'ok'
                    ? pc.green('✓')
                    : p.status === 'warn'
                        ? pc.yellow('⊘')
                        : pc.red('✗');
                const label = `${badge}  ${p.name}`;
                const detail = p.detail ?? '';
                printInfo(label, detail);
                if (p.remedy) {
                    process.stderr.write(`      ${pc.dim('remedy:')} ${p.remedy}\n`);
                }
            }
        }
        // Exit code: non-zero if any fail; warn alone is acceptable.
        const hasFail = probes.some((p) => p.status === 'fail');
        if (hasFail) {
            if (!opts.json)
                printError('one or more probes failed');
            process.exitCode = 1;
        }
        else if (probes.every((p) => p.status === 'ok')) {
            if (!opts.json)
                printSuccess('all probes green');
        }
        else {
            if (!opts.json)
                printWarning('mostly green, with advisory warnings');
        }
    });
}
//# sourceMappingURL=kg-doctor.js.map