import { computeProgressScore, formatProgressLine } from "../../progress-score.js";
import { getGlobalNerfPreferencesPath, getProjectNerfPreferencesPath } from "../../preferences.js";
import { ensurePreferencesFile, handlePrefs, handlePrefsMode, handlePrefsWizard } from "../../commands-prefs-wizard.js";
import { runEnvironmentChecks } from "../../doctor-environment.js";
import { deriveState } from "../../state.js";
import { handleCmux } from "../../commands-cmux.js";
import { projectRoot } from "../context.js";
export function showHelp(ctx) {
    const lines = [
        "NERF — Get Shit Done\n",
        "WORKFLOW",
        "  /nerf start <tpl>   Start a workflow template (bugfix, spike, feature, hotfix, etc.)",
        "  /nerf templates     List available workflow templates  [info <name>]",
        "  /nerf               Run next unit in step mode (same as /nerf next)",
        "  /nerf next           Execute next task, then pause  [--dry-run] [--verbose]",
        "  /nerf auto           Run all queued units continuously  [--verbose]",
        "  /nerf stop           Stop auto-mode gracefully",
        "  /nerf pause          Pause auto-mode (preserves state, /nerf auto to resume)",
        "  /nerf discuss        Start guided milestone/slice discussion",
        "  /nerf new-milestone  Create milestone from headless context (used by nerf headless)",
        "",
        "VISIBILITY",
        "  /nerf status         Show progress dashboard  (Ctrl+Alt+G)",
        "  /nerf visualize      Interactive 10-tab TUI (progress, timeline, deps, metrics, health, agent, changes, knowledge, captures, export)",
        "  /nerf queue          Show queued/dispatched units and execution order",
        "  /nerf history        View execution history  [--cost] [--phase] [--model] [N]",
        "  /nerf changelog      Show categorized release notes  [version]",
        "",
        "COURSE CORRECTION",
        "  /nerf steer <desc>   Apply user override to active work",
        "  /nerf capture <text> Quick-capture a thought to CAPTURES.md",
        "  /nerf triage         Classify and route pending captures",
        "  /nerf skip <unit>    Prevent a unit from auto-mode dispatch",
        "  /nerf undo           Revert last completed unit  [--force]",
        "  /nerf rethink        Conversational project reorganization — reorder, park, discard, add milestones",
        "  /nerf park [id]      Park a milestone — skip without deleting  [reason]",
        "  /nerf unpark [id]    Reactivate a parked milestone",
        "",
        "PROJECT KNOWLEDGE",
        "  /nerf knowledge <type> <text>   Add rule, pattern, or lesson to KNOWLEDGE.md",
        "",
        "SETUP & CONFIGURATION",
        "  /nerf init           Project init wizard — detect, configure, bootstrap .nerf/",
        "  /nerf setup          Global setup status  [llm|search|remote|keys|prefs]",
        "  /nerf mode           Set workflow mode (solo/team)  [global|project]",
        "  /nerf prefs          Manage preferences  [global|project|status|wizard|setup|import-claude]",
        "  /nerf cmux           Manage cmux integration  [status|on|off|notifications|sidebar|splits|browser]",
        "  /nerf config         Set API keys for external tools",
        "  /nerf keys           API key manager  [list|add|remove|test|rotate|doctor]",
        "  /nerf hooks          Show post-unit hook configuration",
        "  /nerf extensions     Manage extensions  [list|enable|disable|info]",
        "  /nerf fast           Toggle OpenAI service tier  [on|off|flex|status]",
        "  /nerf mcp            MCP server status and connectivity  [status|check <server>]",
        "",
        "MAINTENANCE",
        "  /nerf doctor         Diagnose and repair .nerf/ state  [audit|fix|heal] [scope]",
        "  /nerf export         Export milestone/slice results  [--json|--markdown|--html] [--all]",
        "  /nerf cleanup        Remove merged branches or snapshots  [branches|snapshots]",
        "  /nerf migrate        Migrate .planning/ (v1) to .nerf/ (v2) format",
        "  /nerf remote         Control remote auto-mode  [slack|discord|status|disconnect]",
        "  /nerf inspect        Show SQLite DB diagnostics (schema, row counts, recent entries)",
        "  /nerf update         Update NERF to the latest version via npm",
    ];
    ctx.ui.notify(lines.join("\n"), "info");
}
export async function handleStatus(ctx) {
    const basePath = projectRoot();
    const state = await deriveState(basePath);
    if (state.registry.length === 0) {
        ctx.ui.notify("No NERF milestones found. Run /nerf to start.", "info");
        return;
    }
    const { NerfDashboardOverlay } = await import("../../dashboard-overlay.js");
    const result = await ctx.ui.custom((tui, theme, _kb, done) => new NerfDashboardOverlay(tui, theme, () => done()), {
        overlay: true,
        overlayOptions: {
            width: "70%",
            minWidth: 60,
            maxHeight: "90%",
            anchor: "center",
        },
    });
    if (result === undefined) {
        ctx.ui.notify(formatTextStatus(state), "info");
    }
}
export async function fireStatusViaCommand(ctx) {
    await handleStatus(ctx);
}
export async function handleVisualize(ctx) {
    if (!ctx.hasUI) {
        ctx.ui.notify("Visualizer requires an interactive terminal.", "warning");
        return;
    }
    const { NerfVisualizerOverlay } = await import("../../visualizer-overlay.js");
    const result = await ctx.ui.custom((tui, theme, _kb, done) => new NerfVisualizerOverlay(tui, theme, () => done()), {
        overlay: true,
        overlayOptions: {
            width: "80%",
            minWidth: 80,
            maxHeight: "90%",
            anchor: "center",
        },
    });
    if (result === undefined) {
        ctx.ui.notify("Visualizer requires an interactive terminal. Use /nerf status for a text-based overview.", "warning");
    }
}
export async function handleSetup(args, ctx) {
    const { detectProjectState, hasGlobalSetup } = await import("../../detection.js");
    const globalConfigured = hasGlobalSetup();
    const detection = detectProjectState(projectRoot());
    const statusLines = ["NERF Setup Status\n"];
    statusLines.push(`  Global preferences: ${globalConfigured ? "configured" : "not set"}`);
    statusLines.push(`  Project state: ${detection.state}`);
    if (detection.projectSignals.primaryLanguage) {
        statusLines.push(`  Detected: ${detection.projectSignals.primaryLanguage}`);
    }
    if (args === "llm" || args === "auth") {
        ctx.ui.notify("Use /login to configure LLM authentication.", "info");
        return;
    }
    if (args === "search") {
        ctx.ui.notify("Use /search-provider to configure web search.", "info");
        return;
    }
    if (args === "remote") {
        ctx.ui.notify("Use /nerf remote to configure remote questions.", "info");
        return;
    }
    if (args === "keys") {
        const { handleKeys } = await import("../../key-manager.js");
        await handleKeys("", ctx);
        return;
    }
    if (args === "prefs") {
        await ensurePreferencesFile(getGlobalNerfPreferencesPath(), ctx, "global");
        await handlePrefsWizard(ctx, "global");
        return;
    }
    ctx.ui.notify(statusLines.join("\n"), "info");
    ctx.ui.notify("Available setup commands:\n" +
        "  /nerf setup llm     — LLM authentication\n" +
        "  /nerf setup search  — Web search provider\n" +
        "  /nerf setup remote  — Remote questions (Discord/Slack/Telegram)\n" +
        "  /nerf setup keys    — Tool API keys\n" +
        "  /nerf setup prefs   — Global preferences wizard", "info");
}
export async function handleCoreCommand(trimmed, ctx) {
    if (trimmed === "help" || trimmed === "h" || trimmed === "?") {
        showHelp(ctx);
        return true;
    }
    if (trimmed === "status") {
        await handleStatus(ctx);
        return true;
    }
    if (trimmed === "visualize") {
        await handleVisualize(ctx);
        return true;
    }
    if (trimmed === "widget" || trimmed.startsWith("widget ")) {
        const { cycleWidgetMode, setWidgetMode, getWidgetMode } = await import("../../auto-dashboard.js");
        const arg = trimmed.replace(/^widget\s*/, "").trim();
        if (arg === "full" || arg === "small" || arg === "min" || arg === "off") {
            setWidgetMode(arg);
        }
        else {
            cycleWidgetMode();
        }
        ctx.ui.notify(`Widget: ${getWidgetMode()}`, "info");
        return true;
    }
    if (trimmed === "mode" || trimmed.startsWith("mode ")) {
        const modeArgs = trimmed.replace(/^mode\s*/, "").trim();
        const scope = modeArgs === "project" ? "project" : "global";
        const path = scope === "project" ? getProjectNerfPreferencesPath() : getGlobalNerfPreferencesPath();
        await ensurePreferencesFile(path, ctx, scope);
        await handlePrefsMode(ctx, scope);
        return true;
    }
    if (trimmed === "prefs" || trimmed.startsWith("prefs ")) {
        await handlePrefs(trimmed.replace(/^prefs\s*/, "").trim(), ctx);
        return true;
    }
    if (trimmed === "cmux" || trimmed.startsWith("cmux ")) {
        await handleCmux(trimmed.replace(/^cmux\s*/, "").trim(), ctx);
        return true;
    }
    if (trimmed === "setup" || trimmed.startsWith("setup ")) {
        await handleSetup(trimmed.replace(/^setup\s*/, "").trim(), ctx);
        return true;
    }
    return false;
}
export function formatTextStatus(state) {
    const lines = ["NERF Status\n"];
    lines.push(formatProgressLine(computeProgressScore()));
    lines.push("");
    lines.push(`Phase: ${state.phase}`);
    if (state.activeMilestone) {
        lines.push(`Active milestone: ${state.activeMilestone.id} — ${state.activeMilestone.title}`);
    }
    if (state.activeSlice) {
        lines.push(`Active slice: ${state.activeSlice.id} — ${state.activeSlice.title}`);
    }
    if (state.activeTask) {
        lines.push(`Active task: ${state.activeTask.id} — ${state.activeTask.title}`);
    }
    if (state.progress) {
        const { milestones, slices, tasks } = state.progress;
        const parts = [`milestones ${milestones.done}/${milestones.total}`];
        if (slices)
            parts.push(`slices ${slices.done}/${slices.total}`);
        if (tasks)
            parts.push(`tasks ${tasks.done}/${tasks.total}`);
        lines.push(`Progress: ${parts.join(", ")}`);
    }
    if (state.nextAction) {
        lines.push(`Next: ${state.nextAction}`);
    }
    if (state.blockers.length > 0) {
        lines.push(`Blockers: ${state.blockers.join("; ")}`);
    }
    if (state.registry.length > 0) {
        lines.push("");
        lines.push("Milestones:");
        for (const milestone of state.registry) {
            const icon = milestone.status === "complete"
                ? "✓"
                : milestone.status === "active"
                    ? "▶"
                    : milestone.status === "parked"
                        ? "⏸"
                        : "○";
            lines.push(`  ${icon} ${milestone.id}: ${milestone.title} (${milestone.status})`);
        }
    }
    const envResults = runEnvironmentChecks(projectRoot());
    const envIssues = envResults.filter((result) => result.status !== "ok");
    if (envIssues.length > 0) {
        lines.push("");
        lines.push("Environment:");
        for (const issue of envIssues) {
            lines.push(`  ${issue.status === "error" ? "✗" : "⚠"} ${issue.message}`);
        }
    }
    return lines.join("\n");
}
