/**
 * olam skills doctor — diagnostic + auto-repair for the skills surface.
 *
 *   olam skills doctor                  # print report; interactive prompts
 *                                       # per issue when TTY
 *   olam skills doctor --auto-fix       # apply every repair without prompt
 *   olam skills doctor --check-only     # exit 1 on any issue; never modify
 *                                       # state (read-only health probe)
 *
 * Mirrors `olam kg doctor`'s shape; per OQ12 [assumed].
 */
import * as readline from 'node:readline';
import pc from 'picocolors';
import { runAllDoctorChecks, } from '@olam/core/src/skill-sources/index.js';
import { printError, printHeader, printSuccess, printWarning } from '../output.js';
function asMessage(err) {
    return err instanceof Error ? err.message : String(err);
}
function defaultDoctorPrompt(question) {
    return new Promise((resolve) => {
        const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
        rl.question(question, (a) => {
            rl.close();
            resolve(a);
        });
    });
}
async function confirmRepair(check) {
    const testFn = globalThis.__olamTestDoctorPrompt;
    const prompt = testFn ?? (() => defaultDoctorPrompt(`Apply repair for "${check.name}"? [y/N] `));
    const answer = (await prompt()).trim().toLowerCase();
    return answer === 'y' || answer === 'yes';
}
function printCheck(check) {
    if (check.healthy) {
        console.log(`  ${pc.green('✓')} ${pc.bold(check.name.padEnd(22))} ${pc.dim(check.description)}`);
        if (check.details && check.details.length > 0) {
            for (const d of check.details)
                console.log(`      ${pc.dim(d)}`);
        }
    }
    else {
        console.log(`  ${pc.red('✗')} ${pc.bold(check.name.padEnd(22))} ${pc.yellow(check.issue ?? 'unhealthy')}`);
        console.log(`      ${pc.dim(check.description)}`);
        if (check.details) {
            for (const d of check.details.slice(0, 10))
                console.log(`      ${pc.dim('· ' + d)}`);
            if (check.details.length > 10)
                console.log(`      ${pc.dim(`… and ${check.details.length - 10} more`)}`);
        }
    }
}
export function registerSkillsDoctor(program) {
    const skills = program.commands.find((c) => c.name() === 'skills') ??
        program.command('skills').description('Manage skill sources and synchronization');
    skills
        .command('doctor')
        .description('Diagnose corruption classes + member-overlay drift; auto-repair available with --auto-fix')
        .option('--auto-fix', 'Apply each repair without prompting')
        .option('--check-only', 'Report issues + exit non-zero without modifying state')
        .action(async (opts) => {
        if (opts.autoFix && opts.checkOnly) {
            printError('--auto-fix and --check-only are mutually exclusive');
            process.exitCode = 1;
            return;
        }
        printHeader('skills doctor');
        let checks;
        try {
            checks = runAllDoctorChecks();
        }
        catch (err) {
            printError(`doctor checks crashed: ${asMessage(err)}`);
            process.exitCode = 1;
            return;
        }
        for (const c of checks)
            printCheck(c);
        const unhealthy = checks.filter((c) => !c.healthy);
        if (unhealthy.length === 0) {
            console.log();
            printSuccess(`all ${checks.length} check(s) PASS`);
            return;
        }
        console.log();
        printWarning(`${unhealthy.length} of ${checks.length} check(s) report issues`);
        if (opts.checkOnly) {
            console.log(pc.dim('(--check-only — exiting without repair)'));
            process.exitCode = 1;
            return;
        }
        let repaired = 0;
        let skipped = 0;
        for (const check of unhealthy) {
            if (!check.repair) {
                console.log(pc.dim(`  (no auto-repair for ${check.name} — operator-attention required)`));
                skipped += 1;
                continue;
            }
            const shouldRepair = opts.autoFix ? true : await confirmRepair(check);
            if (!shouldRepair) {
                console.log(pc.dim(`  skipped: ${check.name}`));
                skipped += 1;
                continue;
            }
            try {
                await check.repair();
                console.log(pc.green(`  repaired: ${check.name}`));
                repaired += 1;
            }
            catch (err) {
                printError(`  repair failed for ${check.name}: ${asMessage(err)}`);
                skipped += 1;
            }
        }
        console.log();
        if (skipped > 0) {
            printWarning(`repaired ${repaired}; skipped ${skipped}. Re-run doctor to verify.`);
            process.exitCode = skipped > 0 ? 1 : 0;
        }
        else {
            printSuccess(`repaired ${repaired} issue(s). Re-run doctor to verify.`);
        }
    });
}
//# sourceMappingURL=skills-doctor.js.map