/**
 * `olam memory install-hooks` — install agentmemory Claude Code hooks.
 *
 * Writes the 3 agentmemory hook scripts from olam's canonical location at
 * `packages/memory-service/hooks/` to the operator's `~/.claude/scripts/hooks/`,
 * then prints the settings.json edit operators need to apply. The 3 hooks:
 *
 *   - agentmemory-session-recall.js   — SessionStart hook (injects recall
 *                                       context at session start).
 *   - agentmemory-recall-trigger.mjs  — PreToolUse hook (pre-tool recall).
 *   - agentmemory-classify-queue.mjs  — PostToolUse hook (capture-to-queue).
 *
 * Idempotent: re-running with same canonical content + same target path is
 * a no-op (UNCHANGED). Existing operator files are PRESERVED unless --force
 * (which backs them up to .agentmemory-hook-backup-<ts>).
 *
 * Plan reference: docs/plans/olam-flywheel-cli-namespace/phase-a-tasks.md § A16
 * Closes K1-adjacent operator-pass-2 directive (agentmemory hook consolidation).
 */
import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const HOOK_BASENAMES = [
    'agentmemory-session-recall.js',
    'agentmemory-recall-trigger.mjs',
    'agentmemory-classify-queue.mjs',
];
function defaultSourceDir() {
    // Resolve to packages/memory-service/hooks/ relative to this file's own
    // dist location. At build time, dist/commands/memory/install-hooks.js
    // → ../../../memory-service/hooks (climb out of dist/commands/memory
    // back to packages/cli, then sibling packages/memory-service/hooks).
    // Falls back to the workspace root if the relative path doesn't resolve.
    const here = dirname(fileURLToPath(import.meta.url));
    const candidate = resolve(here, '..', '..', '..', 'memory-service', 'hooks');
    if (existsSync(candidate))
        return candidate;
    // Source-tree fallback (npm run dev / tsx).
    const srcCandidate = resolve(here, '..', '..', '..', '..', 'memory-service', 'hooks');
    if (existsSync(srcCandidate))
        return srcCandidate;
    return candidate;
}
function installOne(basename, sourceDir, targetDir, opts) {
    const sourcePath = join(sourceDir, basename);
    const targetPath = join(targetDir, basename);
    if (!existsSync(sourcePath)) {
        throw new Error(`canonical hook source missing at ${sourcePath} — olam install corrupt or sourceDir is wrong`);
    }
    const newContent = readFileSync(sourcePath, 'utf8');
    if (!existsSync(targetPath)) {
        if (opts.dryRun !== true) {
            mkdirSync(dirname(targetPath), { recursive: true });
            writeFileSync(targetPath, newContent, { mode: 0o755 });
        }
        return { basename, action: 'written', targetPath };
    }
    const existing = readFileSync(targetPath, 'utf8');
    if (existing === newContent) {
        return { basename, action: 'unchanged', targetPath };
    }
    if (opts.force === true) {
        const backupPath = `${targetPath}.agentmemory-hook-backup-${Math.floor(Date.now() / 1000)}`;
        if (opts.dryRun !== true) {
            copyFileSync(targetPath, backupPath);
            writeFileSync(targetPath, newContent, { mode: 0o755 });
        }
        return { basename, action: 'force-overwritten', targetPath, backupPath };
    }
    return { basename, action: 'preserved-existing', targetPath };
}
function emitSettingsHint(targetDir) {
    return `
Settings.json wiring (apply manually; auto-injection deferred to a follow-up):

Add these hook entries to ~/.claude/settings.json:

{
  "hooks": {
    "SessionStart": [
      { "command": "node ${join(targetDir, 'agentmemory-session-recall.js')}" }
    ],
    "PreToolUse": [
      { "command": "node ${join(targetDir, 'agentmemory-recall-trigger.mjs')}" }
    ],
    "PostToolUse": [
      { "command": "node ${join(targetDir, 'agentmemory-classify-queue.mjs')}" }
    ]
  }
}

If existing entries already point at the same paths, no edit needed.
`;
}
export function registerMemoryInstallHooks(parent) {
    parent
        .command('install-hooks')
        .description('Install agentmemory hooks (PreToolUse + PostToolUse + SessionStart) to ~/.claude/scripts/hooks/')
        .option('--force', 'overwrite existing non-canonical files (backs them up to .agentmemory-hook-backup-<ts>)')
        .option('--dry-run', 'preview which hooks would be written without modifying disk')
        .option('--target-dir <path>', 'override target directory (default: ~/.claude/scripts/hooks/); for tests')
        .option('--source-dir <path>', 'override source directory (default: packages/memory-service/hooks/); for tests')
        .action((opts) => {
        const targetDir = opts.targetDir ?? join(homedir(), '.claude', 'scripts', 'hooks');
        const sourceDir = opts.sourceDir ?? defaultSourceDir();
        let written = 0;
        let unchanged = 0;
        let preserved = 0;
        let forceOverwritten = 0;
        const lines = [];
        const backups = [];
        try {
            for (const basename of HOOK_BASENAMES) {
                const result = installOne(basename, sourceDir, targetDir, opts);
                const dryRunSuffix = opts.dryRun === true ? ' (dry-run)' : '';
                switch (result.action) {
                    case 'written':
                        lines.push(`  WRITTEN     ${result.targetPath}${dryRunSuffix}`);
                        written += 1;
                        break;
                    case 'unchanged':
                        lines.push(`  UNCHANGED   ${result.targetPath}`);
                        unchanged += 1;
                        break;
                    case 'preserved-existing':
                        lines.push(`  PRESERVED   ${result.targetPath} (existing file; use --force to overwrite + backup)`);
                        preserved += 1;
                        break;
                    case 'force-overwritten':
                        lines.push(`  OVERWRITTEN ${result.targetPath}${dryRunSuffix} (backup: ${result.backupPath})`);
                        forceOverwritten += 1;
                        if (result.backupPath !== undefined)
                            backups.push(result.backupPath);
                        break;
                }
            }
        }
        catch (err) {
            process.stderr.write(`[memory-install-hooks-error] ${err instanceof Error ? err.message : 'unknown error'}\n`);
            process.exit(2);
        }
        process.stdout.write(`olam memory install-hooks → ${targetDir}\n`);
        process.stdout.write(`  source: ${sourceDir}\n\n`);
        for (const line of lines)
            process.stdout.write(line + '\n');
        process.stdout.write(`\nwritten: ${written}, unchanged: ${unchanged}, preserved: ${preserved}, force-overwritten: ${forceOverwritten}\n`);
        if (preserved === 0) {
            process.stdout.write(emitSettingsHint(targetDir));
        }
        else {
            process.exit(1);
        }
    });
}
//# sourceMappingURL=install-hooks.js.map