import { spawn } from 'node:child_process';
function runHook(command, payload, cwd) {
    return new Promise((resolve) => {
        const child = spawn(command, { shell: '/bin/bash', cwd, env: process.env });
        let stderr = '';
        child.stderr.on('data', (d) => (stderr += d.toString()));
        child.on('error', () => resolve({ code: null, stderr }));
        const timer = setTimeout(() => {
            child.kill('SIGKILL');
            resolve({ code: null, stderr });
        }, 30_000);
        child.on('close', (code) => {
            clearTimeout(timer);
            resolve({ code, stderr });
        });
        child.stdin.write(JSON.stringify(payload));
        child.stdin.end();
    });
}
export function createHookRunner(config, cwd) {
    return {
        pre: async (toolName, input) => {
            if (!config.preToolUse)
                return null;
            const { code, stderr } = await runHook(config.preToolUse, { tool: toolName, input }, cwd);
            if (code === 2) {
                return `blocked by preToolUse hook${stderr.trim() ? `: ${stderr.trim().slice(0, 500)}` : ''}`;
            }
            return null; // exit 0 allows; other exits / hook failures fail open
        },
        post: (toolName, input, output) => {
            if (!config.postToolUse)
                return;
            void runHook(config.postToolUse, { tool: toolName, input, output: output.slice(0, 10_000) }, cwd);
        },
    };
}
