/**
 * `olam kg uninstall-hook [--scope project|user]` — surgical removal of the
 * kg-service PreToolUse hook from .claude/settings.json.
 *
 * Matches by sentinel — only removes hook entries whose command contains
 * KG_HOOK_SENTINEL. Other PreToolUse entries (e.g. operator-installed
 * custom hooks) are left intact. Idempotent: running on a non-installed
 * file is a no-op.
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { KG_HOOK_SENTINEL } from '@olam/core/src/kg/hook-template.js';
import { printError, printInfo, printSuccess } from '../output.js';
function settingsPathFor(scope) {
    if (scope === 'user') {
        return path.join(os.homedir(), '.claude', 'settings.json');
    }
    return path.join(process.cwd(), '.claude', 'settings.json');
}
/**
 * Walk a PreToolUse matcher array and drop:
 *   - inner hook entries whose `command` contains the sentinel
 *   - outer matcher entries left empty after the inner-drop
 * Returns the filtered array + a boolean "did anything change".
 */
function dropSentinel(matchers) {
    let changed = false;
    const out = [];
    for (const matcher of matchers) {
        const innerHooks = matcher.hooks ?? [];
        const keptInner = innerHooks.filter((h) => {
            if (typeof h.command === 'string' && h.command.includes(KG_HOOK_SENTINEL)) {
                changed = true;
                return false;
            }
            return true;
        });
        if (keptInner.length === 0 && innerHooks.length > 0) {
            // The matcher had hooks but they were all kg-service; drop the matcher entirely.
            changed = true;
            continue;
        }
        if (keptInner.length === innerHooks.length) {
            out.push(matcher);
        }
        else {
            out.push({ ...matcher, hooks: keptInner });
        }
    }
    return { matchers: out, changed };
}
export function registerKgUninstallHookCommand(kg) {
    kg.command('uninstall-hook')
        .description('Remove kg-service PreToolUse hook from .claude/settings.json (sentinel-matched; surgical)')
        .option('--scope <scope>', 'project (default) or user', 'project')
        .action((opts) => {
        const scope = opts.scope === 'user' ? 'user' : 'project';
        const filePath = settingsPathFor(scope);
        if (!fs.existsSync(filePath)) {
            printInfo('kg-service hook', `no settings.json at ${filePath} — nothing to remove`);
            return;
        }
        let settings;
        try {
            const raw = fs.readFileSync(filePath, 'utf-8');
            settings = raw.trim() ? JSON.parse(raw) : {};
        }
        catch (err) {
            printError(`could not parse ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
            process.exitCode = 1;
            return;
        }
        const preToolUse = settings.hooks?.PreToolUse;
        if (!Array.isArray(preToolUse) || preToolUse.length === 0) {
            printInfo('kg-service hook', `no PreToolUse hooks at ${filePath} — nothing to remove`);
            return;
        }
        const { matchers, changed } = dropSentinel(preToolUse);
        if (!changed) {
            printInfo('kg-service hook', `not found in ${filePath} — already uninstalled`);
            return;
        }
        // Back up before writing the filtered result.
        const ts = new Date().toISOString().replace(/[:.]/g, '-');
        const backupPath = `${filePath}.olam-bak.${ts}`;
        try {
            fs.copyFileSync(filePath, backupPath);
        }
        catch {
            // best-effort backup
        }
        const next = {
            ...settings,
            hooks: {
                ...settings.hooks,
                PreToolUse: matchers,
            },
        };
        // If PreToolUse is now empty AND there are no other hook stages, drop the key entirely.
        if (matchers.length === 0) {
            const otherStages = Object.keys(next.hooks ?? {}).filter((k) => k !== 'PreToolUse');
            if (otherStages.length === 0) {
                delete next.hooks;
            }
            else {
                delete next.hooks.PreToolUse;
            }
        }
        try {
            fs.writeFileSync(filePath, JSON.stringify(next, null, 2) + '\n');
            printSuccess(`kg-service hook removed from ${filePath}`);
            printInfo('backup', backupPath);
        }
        catch (err) {
            printError(`could not write ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
            process.exitCode = 1;
        }
    });
}
//# sourceMappingURL=kg-uninstall-hook.js.map