import { registerNerfCommand } from "../commands.js";
import { registerExitCommand } from "../exit-command.js";
import { registerWorktreeCommand } from "../worktree-command.js";
import { registerDbTools } from "./db-tools.js";
import { registerDynamicTools } from "./dynamic-tools.js";
import { registerJournalTools } from "./journal-tools.js";
import { registerHooks } from "./register-hooks.js";
import { registerShortcuts } from "./register-shortcuts.js";
export function handleRecoverableExtensionProcessError(err) {
    if (err.code === "EPIPE") {
        process.exit(0);
    }
    if (err.code === "ENOENT") {
        const syscall = err.syscall;
        if (syscall?.startsWith("spawn")) {
            process.stderr.write(`[nerf] spawn ENOENT: ${err.path ?? "unknown"} — command not found\n`);
            return true;
        }
        if (syscall === "uv_cwd") {
            process.stderr.write(`[nerf] ENOENT (${syscall}): ${err.message}\n`);
            return true;
        }
    }
    return false;
}
function installEpipeGuard() {
    if (!process.listeners("uncaughtException").some((listener) => listener.name === "_nerfEpipeGuard")) {
        const _nerfEpipeGuard = (err) => {
            if (handleRecoverableExtensionProcessError(err)) {
                return;
            }
            throw err;
        };
        process.on("uncaughtException", _nerfEpipeGuard);
    }
}
export function registerNerfExtension(pi) {
    registerNerfCommand(pi);
    registerWorktreeCommand(pi);
    registerExitCommand(pi);
    installEpipeGuard();
    pi.registerCommand("kill", {
        description: "Exit NERF immediately (no cleanup)",
        handler: async (_args, _ctx) => {
            process.exit(0);
        },
    });
    registerDynamicTools(pi);
    registerDbTools(pi);
    registerJournalTools(pi);
    registerShortcuts(pi);
    registerHooks(pi);
}
