/**
 * NERF Inspect — SQLite DB diagnostics.
 *
 * Contains: InspectData type, formatInspectOutput, handleInspect
 */
import { existsSync } from "node:fs";
import { join } from "node:path";
import { nerfRoot } from "./paths.js";
import { getErrorMessage } from "./error-utils.js";
export function formatInspectOutput(data) {
    const lines = [];
    lines.push("=== NERF Database Inspect ===");
    lines.push(`Schema version: ${data.schemaVersion ?? "unknown"}`);
    lines.push("");
    lines.push(`Decisions:    ${data.counts.decisions}`);
    lines.push(`Requirements: ${data.counts.requirements}`);
    lines.push(`Artifacts:    ${data.counts.artifacts}`);
    if (data.recentDecisions.length > 0) {
        lines.push("");
        lines.push("Recent decisions:");
        for (const d of data.recentDecisions) {
            lines.push(`  ${d.id}: ${d.decision} → ${d.choice}`);
        }
    }
    if (data.recentRequirements.length > 0) {
        lines.push("");
        lines.push("Recent requirements:");
        for (const r of data.recentRequirements) {
            lines.push(`  ${r.id} [${r.status}]: ${r.description}`);
        }
    }
    return lines.join("\n");
}
export async function handleInspect(ctx) {
    try {
        const { isDbAvailable, _getAdapter, openDatabase } = await import("./nerf-db.js");
        if (!isDbAvailable()) {
            const nerfDir = nerfRoot(process.cwd());
            const dbPath = join(nerfDir, "nerf.db");
            if (!existsSync(nerfDir) || !existsSync(dbPath) || !openDatabase(dbPath)) {
                ctx.ui.notify("No NERF database available. Run /nerf auto to create one.", "info");
                return;
            }
        }
        const adapter = _getAdapter();
        if (!adapter) {
            ctx.ui.notify("No NERF database available. Run /nerf auto to create one.", "info");
            return;
        }
        const versionRow = adapter.prepare("SELECT MAX(version) as v FROM schema_version").get();
        const schemaVersion = versionRow ? versionRow["v"] : null;
        const dCount = adapter.prepare("SELECT count(*) as cnt FROM decisions").get();
        const rCount = adapter.prepare("SELECT count(*) as cnt FROM requirements").get();
        const aCount = adapter.prepare("SELECT count(*) as cnt FROM artifacts").get();
        const recentDecisions = adapter
            .prepare("SELECT id, decision, choice FROM decisions ORDER BY seq DESC LIMIT 5")
            .all();
        const recentRequirements = adapter
            .prepare("SELECT id, status, description FROM requirements ORDER BY id DESC LIMIT 5")
            .all();
        const data = {
            schemaVersion,
            counts: {
                decisions: dCount?.["cnt"] ?? 0,
                requirements: rCount?.["cnt"] ?? 0,
                artifacts: aCount?.["cnt"] ?? 0,
            },
            recentDecisions,
            recentRequirements,
        };
        ctx.ui.notify(formatInspectOutput(data), "info");
    }
    catch (err) {
        process.stderr.write(`nerf-db: /nerf inspect failed: ${getErrorMessage(err)}\n`);
        ctx.ui.notify("Failed to inspect NERF database. Check stderr for details.", "error");
    }
}
