/**
 * Flywheel doctor probes — callable functions for `olam doctor` to consume.
 *
 * Deliberately separated from `packages/cli/src/commands/doctor.ts` so the
 * probe logic can land + be tested without touching the 945-line doctor's
 * D11 positional-contract churn. doctor.ts wiring is a focused follow-up;
 * the probe functions here are the deliverable.
 *
 * Probes:
 *   - `probeFlywheelShimHealth()` — verifies every registered shim target
 *     (per @olam/cli/lib/shim-generator SHIM_SPECS) exists at
 *     `~/.claude/scripts/<basename>` AND is the olam-generated form
 *     (contains the AUTO-GENERATED marker). Returns the probe result + a
 *     per-target breakdown.
 *
 *   - `probeSettingsHooksAudit()` — closes K1 OQ9. Scans
 *     `~/.claude/settings.json` for hook entries (PreToolUse / PostToolUse /
 *     Stop / SessionStart) that reference hardcoded `~/.claude/scripts/<n>`
 *     paths AND warns if the basename matches a shim-target that has a
 *     `replacedBy` migration path.
 *
 * Plan reference: docs/plans/olam-flywheel-cli-namespace/phase-b-tasks.md § B4 + B6
 */
import { existsSync, readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { SHIM_SPECS } from './shim-generator.js';
import { lookupShimTarget } from '@olam/core/src/lib/shim-targets.js';
const SHIM_AUTO_GENERATED_MARKER = '# AUTO-GENERATED by `olam flywheel install-shims`';
const DEFAULT_SCRIPTS_DIR = join(homedir(), '.claude', 'scripts');
const DEFAULT_SETTINGS_PATH = join(homedir(), '.claude', 'settings.json');
export function probeFlywheelShimHealth(opts = {}) {
    const scriptsDir = opts.scriptsDir ?? DEFAULT_SCRIPTS_DIR;
    const details = [];
    let okCount = 0;
    let missingCount = 0;
    let staleCount = 0;
    let operatorFileCount = 0;
    for (const spec of SHIM_SPECS) {
        const path = join(scriptsDir, spec.basename);
        let status;
        if (!existsSync(path)) {
            status = 'MISSING';
            missingCount += 1;
        }
        else {
            try {
                const content = readFileSync(path, 'utf8');
                if (content.includes(SHIM_AUTO_GENERATED_MARKER)) {
                    status = 'OK';
                    okCount += 1;
                }
                else {
                    status = 'OPERATOR-FILE';
                    operatorFileCount += 1;
                }
            }
            catch {
                status = 'STALE';
                staleCount += 1;
            }
        }
        details.push({ basename: spec.basename, path, status });
    }
    const totalSpecs = SHIM_SPECS.length;
    if (missingCount === 0 && operatorFileCount === 0 && staleCount === 0) {
        return {
            ok: true,
            warn: false,
            message: `flywheel-shim-health: ${okCount}/${totalSpecs} shim targets present + auto-generated`,
            details,
            okCount,
            missingCount,
            staleCount,
            operatorFileCount,
        };
    }
    const issues = [];
    if (missingCount > 0)
        issues.push(`${missingCount} missing`);
    if (operatorFileCount > 0)
        issues.push(`${operatorFileCount} operator-file (would be backed up by --force install)`);
    if (staleCount > 0)
        issues.push(`${staleCount} stale`);
    return {
        ok: false,
        warn: missingCount === 0 && staleCount === 0, // operator-file alone is WARN, not FAIL
        message: `flywheel-shim-health: ${okCount}/${totalSpecs} OK, ${issues.join(', ')} — run \`olam flywheel install-shims\` to refresh (--force to backup + overwrite operator files)`,
        details,
        okCount,
        missingCount,
        staleCount,
        operatorFileCount,
    };
}
const HOOK_BLOCKS = [
    'PreToolUse',
    'PostToolUse',
    'Stop',
    'SessionStart',
    'UserPromptSubmit',
];
const SCRIPT_PATH_RE = /~\/.claude\/scripts\/([\w.-]+)|\$HOME\/\.claude\/scripts\/([\w.-]+)|\/Users\/[\w.-]+\/\.claude\/scripts\/([\w.-]+)/;
export function probeSettingsHooksAudit(opts = {}) {
    const settingsPath = opts.settingsPath ?? DEFAULT_SETTINGS_PATH;
    if (!existsSync(settingsPath)) {
        return {
            ok: true,
            warn: false,
            message: `settings-hooks-audit: ${settingsPath} not present; nothing to audit`,
            findings: [],
        };
    }
    let parsed;
    try {
        parsed = JSON.parse(readFileSync(settingsPath, 'utf8'));
    }
    catch (err) {
        return {
            ok: false,
            warn: false,
            message: `settings-hooks-audit: cannot parse ${settingsPath} as JSON: ${err instanceof Error ? err.message : 'unknown'}`,
            findings: [],
        };
    }
    const findings = [];
    const hooks = parsed.hooks ?? {};
    for (const block of HOOK_BLOCKS) {
        const entries = hooks[block] ?? [];
        for (const entry of entries) {
            const command = entry.command ?? '';
            const match = SCRIPT_PATH_RE.exec(command);
            if (match === null)
                continue;
            const basename = match[1] ?? match[2] ?? match[3];
            if (basename === undefined)
                continue;
            const shimTarget = lookupShimTarget(basename);
            findings.push({
                block,
                command,
                ...(basename ? { matchedShimBasename: basename } : {}),
                ...(shimTarget?.replacedBy !== undefined ? { suggestedReplacement: shimTarget.replacedBy } : {}),
            });
        }
    }
    if (findings.length === 0) {
        return {
            ok: true,
            warn: false,
            message: 'settings-hooks-audit: no hardcoded ~/.claude/scripts/ paths in hook entries',
            findings: [],
        };
    }
    const shimMatches = findings.filter((f) => f.suggestedReplacement !== undefined).length;
    return {
        ok: false,
        warn: true,
        message: `settings-hooks-audit: ${findings.length} hook entries reference hardcoded ~/.claude/scripts/<n>${shimMatches > 0 ? `, ${shimMatches} have an olam-flywheel replacement available` : ''}`,
        findings,
    };
}
//# sourceMappingURL=flywheel-probes.js.map