/**
 * NERF Commands — /nerf namespace for admin and info.
 *
 * Subcommands: status, doctor, skills, domains, analyze
 */
import { existsSync } from "node:fs";
import { resolve, join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { homedir } from "node:os";
const __dirname = fileURLToPath(new URL(".", import.meta.url));
// ---------------------------------------------------------------------------
// Path resolver — finds cli/lib/ across dev, global install, and agent copy
// ---------------------------------------------------------------------------
function resolveCliLib() {
    const candidates = [];
    // From __dirname (works in repo dev and global install dist/)
    candidates.push(resolve(__dirname, "..", "..", "..", "..", "cli", "lib"));
    // From the running binary (dist/loader.js -> ../cli/lib)
    if (process.argv[1]) {
        const binDir = dirname(resolve(process.argv[1]));
        candidates.push(resolve(binDir, "..", "cli", "lib"));
        candidates.push(resolve(binDir, "cli", "lib"));
    }
    // Common global install paths
    const npmGlobal = process.env.npm_config_prefix || "/usr/lib";
    candidates.push(join(npmGlobal, "node_modules", "@defconxt", "nerf", "cli", "lib"));
    candidates.push("/usr/lib/node_modules/@defconxt/nerf/cli/lib");
    candidates.push("/usr/local/lib/node_modules/@defconxt/nerf/cli/lib");
    candidates.push(join(homedir(), ".npm-global", "lib", "node_modules", "@defconxt", "nerf", "cli", "lib"));
    for (const candidate of candidates) {
        if (existsSync(join(candidate, "gateway", "commands.js"))) {
            return candidate;
        }
    }
    return resolve(__dirname, "..", "..", "..", "..", "cli", "lib");
}
// Lazy gateway import (same bridge as tools.ts)
let _gateway = null;
async function gateway() {
    if (_gateway)
        return _gateway;
    const gatewayPath = join(resolveCliLib(), "gateway", "commands.js");
    if (existsSync(gatewayPath)) {
        try {
            _gateway = await import(gatewayPath);
            return _gateway;
        }
        catch {
            // Import failed — fall through to empty gateway
        }
    }
    _gateway = {};
    return _gateway;
}
export function registerNerfCommands(pi) {
    // Register individual NERF commands as top-level slash commands
    // These provide quick access without needing /nerf:<subcommand> syntax
    pi.registerCommand("nerf-status", {
        description: "NERF status — version, memory, techniques",
        handler: async (_args, ctx) => {
            try {
                const gw = await gateway();
                const version = gw.handleVersion
                    ? await gw.handleVersion()
                    : { version: process.env.NERF_VERSION || "?" };
                const stats = gw.handleStats ? await gw.handleStats() : null;
                ctx.ui.notify(`NERF v${version?.version || "?"} — ` +
                    `${stats?.memory?.total || 0} memories, ` +
                    `${stats?.skills?.total || 0} techniques`, "info");
            }
            catch (e) {
                const msg = e instanceof Error ? e.message : String(e);
                ctx.ui.notify(`NERF error: ${msg}`, "error");
            }
        },
    });
    pi.registerCommand("nerf-doctor", {
        description: "NERF diagnostics — check all components",
        handler: async (_args, ctx) => {
            try {
                const gw = await gateway();
                if (!gw.handleDoctor) {
                    ctx.ui.notify("NERF doctor not available", "warning");
                    return;
                }
                const doctor = await gw.handleDoctor();
                const ok = doctor?.checks?.filter((c) => c.status === "ok").length || 0;
                const total = doctor?.checks?.length || 0;
                ctx.ui.notify(`NERF doctor: ${ok}/${total} checks passed`, ok === total ? "info" : "warning");
            }
            catch (e) {
                const msg = e instanceof Error ? e.message : String(e);
                ctx.ui.notify(`NERF error: ${msg}`, "error");
            }
        },
    });
    pi.registerCommand("nerf-keys", {
        description: "NERF keys — show API key status for all providers",
        handler: async (_args, ctx) => {
            try {
                const gw = await gateway();
                if (!gw.handleKeys) {
                    ctx.ui.notify("NERF keys not available", "warning");
                    return;
                }
                const result = await gw.handleKeys();
                const providers = result?.providers || [];
                const configured = providers.filter((p) => p.keyStatus !== "missing").length;
                ctx.ui.notify(`NERF keys: ${configured}/${providers.length} providers configured` +
                    (result?.activeBackend
                        ? ` — active: ${result.activeBackend}`
                        : ""), "info");
            }
            catch (e) {
                const msg = e instanceof Error ? e.message : String(e);
                ctx.ui.notify(`NERF error: ${msg}`, "error");
            }
        },
    });
    pi.registerCommand("nerf-skills", {
        description: "NERF skills — list loaded security skill count",
        handler: async (_args, ctx) => {
            try {
                const gw = await gateway();
                if (!gw.handleSkills) {
                    ctx.ui.notify("NERF skills not available", "warning");
                    return;
                }
                const skills = await gw.handleSkills();
                ctx.ui.notify(`${skills?.count || 0} security skills loaded`, "info");
            }
            catch (e) {
                const msg = e instanceof Error ? e.message : String(e);
                ctx.ui.notify(`NERF error: ${msg}`, "error");
            }
        },
    });
}
