// tools/start-hooks/configure.ts — handleConfigureHooks + plan-mode integration + template apply.
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { generateHookTemplate, mergeHookConfig } from '../../engine/hooks/hook-templates.js';
import { buildPlanModeHookScripts } from '../../engine/hooks/plan-mode-scripts.js';
import { ConfigLoader } from '../../engine/hooks/config-loader.js';
import { getConfigLoaderInstance, getEngineInstance } from './engine.js';
import { compactResult, formatKeyValue } from '../output-formatter.js';
export async function handleConfigureHooks(args) {
    if (args.action === 'enable-plan-mode-integration') {
        return enablePlanModeIntegration(args.projectPath);
    }
    if (args.template) {
        return applyHookTemplate(args);
    }
    const configLoader = getConfigLoaderInstance();
    if (!configLoader) {
        const loader = new ConfigLoader(args.projectPath);
        const config = await loader.load();
        loader.close();
        return compactResult(formatKeyValue({
            message: 'Hook engine not running. Current config:',
            debounceMs: config.debounceMs,
            rateLimitPerFileMs: config.rateLimitPerFileMs,
        }, 'Hook Config'));
    }
    const config = await configLoader.load();
    return compactResult(formatKeyValue({
        message: 'Configuration reloaded',
        engineRunning: getEngineInstance()?.status().running ?? false,
        debounceMs: config.debounceMs,
        rateLimitPerFileMs: config.rateLimitPerFileMs,
    }, 'Hook Config'));
}
async function enablePlanModeIntegration(projectPath) {
    const hooksDir = join(projectPath, '.claude', 'hooks');
    await mkdir(hooksDir, { recursive: true });
    const scripts = buildPlanModeHookScripts();
    const preHookPath = join(hooksDir, 'planu-pre-plan.sh');
    const postHookPath = join(hooksDir, 'planu-post-plan.sh');
    await writeFile(preHookPath, scripts.preScript, { mode: 0o755 });
    await writeFile(postHookPath, scripts.postScript, { mode: 0o755 });
    const settingsPath = join(projectPath, '.claude', 'settings.json');
    let existing = {};
    try {
        const raw = await readFile(settingsPath, 'utf-8');
        existing = JSON.parse(raw);
    }
    catch {
        // File doesn't exist yet — start from empty
    }
    const preEntry = {
        matcher: 'Task',
        hooks: [{ type: 'command', command: `bash "${preHookPath}"` }],
    };
    const postEntry = {
        matcher: 'exit_plan_mode',
        hooks: [{ type: 'command', command: `bash "${postHookPath}"` }],
    };
    const existingHooks = (existing.hooks ?? {});
    const merged = {
        ...existing,
        hooks: {
            ...existingHooks,
            PreToolUse: [...(existingHooks.PreToolUse ?? []), preEntry],
            PostToolUse: [...(existingHooks.PostToolUse ?? []), postEntry],
        },
    };
    await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
    const result = {
        action: 'enable-plan-mode-integration',
        preHookPath,
        postHookPath,
        settingsPath,
        message: 'Plan Mode integration enabled. Planu context will be injected automatically when Claude enters Plan Mode.',
    };
    return compactResult(formatKeyValue({
        action: result.action,
        preHookPath: result.preHookPath,
        postHookPath: result.postHookPath,
        settingsPath: result.settingsPath,
        message: result.message,
    }, 'Plan Mode Integration'));
}
async function applyHookTemplate(args) {
    /* c8 ignore next 3 */
    if (!args.template) {
        return { content: [{ type: 'text', text: 'template is required' }], isError: true };
    }
    const generated = generateHookTemplate({
        template: args.template,
        notificationMatcher: args.notificationMatcher,
    });
    const settingsPath = join(args.projectPath, '.claude', 'settings.json');
    let existing = {};
    try {
        const raw = await readFile(settingsPath, 'utf-8');
        existing = JSON.parse(raw);
    }
    catch {
        // File doesn't exist yet or is not valid JSON — start from empty object
    }
    const merged = mergeHookConfig(existing, generated);
    await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
    return compactResult(formatKeyValue({
        message: `Hook template '${args.template}' applied`,
        settingsPath,
        description: generated.description,
        mergeInstructions: generated.mergeInstructions,
    }, 'Hook Template'));
}
//# sourceMappingURL=configure.js.map