"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerNextCommands = registerNextCommands;
const chalk_1 = __importDefault(require("chalk"));
const core_1 = require("@myycontext/core");
const FeatureGraphCompiler_1 = require("../services/FeatureGraphCompiler");
const QuestionGraphEngine_1 = require("../services/QuestionGraphEngine");
const BlockerGate_1 = require("../services/BlockerGate");
const LivingDictionary_1 = require("../services/LivingDictionary");
const ImplGraphCompiler_1 = require("../services/ImplGraphCompiler");
const ExecutionHistory_1 = require("../services/ExecutionHistory");
const registry_1 = require("../agents/registry");
const ChatFirstController_1 = require("./ChatFirstController");
function registerNextCommands(shell, controller = new ChatFirstController_1.ChatFirstController()) {
    const tui = shell.getTUI();
    // ── /features ──────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "features",
        description: "Feature Graph: list, graph, plan, validate, compile",
        handler: async (args) => {
            const [sub] = args.split(/\s+/);
            const compiler = new FeatureGraphCompiler_1.FeatureGraphCompiler();
            switch (sub) {
                case "list": {
                    const graph = await compiler.compileFromContext();
                    const features = graph.getDependencyOrder();
                    tui.header(`FEATURES (${features.length})`);
                    for (const f of features) {
                        const score = f.completeness?.overall ?? 0;
                        const color = score >= 80 ? chalk_1.default.green : score >= 50 ? chalk_1.default.yellow : chalk_1.default.red;
                        console.log(`  ${chalk_1.default.cyan("▸")} ${chalk_1.default.bold(f.name || f.id)}`);
                        console.log(`     ${chalk_1.default.dim("Status:")} ${f.status} · ${chalk_1.default.dim("Score:")} ${color(`${score}%`)}`);
                    }
                    break;
                }
                case "graph": {
                    const graph = await compiler.compileFromContext();
                    const ordered = graph.getDependencyOrder();
                    tui.header("FEATURE DEPENDENCY GRAPH");
                    const indent = "  ";
                    ordered.forEach((f, i) => {
                        const prefix = i === 0 ? chalk_1.default.green("◉") : chalk_1.default.cyan("◉");
                        console.log(`${indent}${prefix} ${f.name}`);
                        const deps = graph.nodes.get(f.id)?.metadata?.dependencies;
                        if (deps && deps.length > 0) {
                            deps.forEach((d) => {
                                const dep = graph.nodes.get(d);
                                console.log(`${indent}  ${chalk_1.default.dim("←")} ${dep ? dep.name : d}`);
                            });
                        }
                    });
                    break;
                }
                case "plan": {
                    const next = await compiler.getNextRecommended();
                    tui.header("FEATURE PLAN");
                    if (next) {
                        console.log(`  ${chalk_1.default.green("→")} Next: ${chalk_1.default.bold(next.name)}`);
                        console.log(`     ${chalk_1.default.dim(next.description)}`);
                    }
                    else {
                        console.log(`  ${chalk_1.default.dim("All features completed or planned")}`);
                    }
                    break;
                }
                case "validate": {
                    const graph = await compiler.compileFromContext();
                    tui.header("FEATURE GAPS");
                    let gapCount = 0;
                    for (const f of graph.getDependencyOrder()) {
                        const gaps = await compiler.detectGaps(f);
                        if (gaps.length > 0) {
                            gapCount += gaps.length;
                            gaps.forEach((g) => console.log(`  ${chalk_1.default.red("✗")} ${f.name}: ${g}`));
                        }
                    }
                    if (gapCount === 0) {
                        console.log(`  ${chalk_1.default.green("✓ No gaps detected")}`);
                    }
                    break;
                }
                case "compile": {
                    const graph = await compiler.compileFromContext();
                    tui.header("FEATURE COMPILE");
                    console.log(`  ${chalk_1.default.green("✓")} Compiled ${graph.nodes.size} features`);
                    break;
                }
                default:
                    console.log(chalk_1.default.yellow("  Subcommands: list, graph, plan, validate, compile"));
            }
        },
    });
    // ── /questions ─────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "questions",
        description: "Question Graph: list, blockers, answer, validate",
        handler: async (args) => {
            const [sub, ...rest] = args.split(/\s+/);
            const engine = new QuestionGraphEngine_1.QuestionGraphEngine();
            await engine.load();
            switch (sub) {
                case "list": {
                    const graph = engine.getGraph();
                    const questions = Array.from(graph.nodes.values());
                    tui.header(`QUESTIONS (${questions.length})`);
                    questions.forEach((q) => {
                        const status = q.status === "answered" ? chalk_1.default.green("✓") : q.isBlocking ? chalk_1.default.red("✗") : chalk_1.default.dim("—");
                        console.log(`  ${status} ${chalk_1.default.cyan(q.id)}: ${q.text}`);
                        if (q.answer)
                            console.log(`     ${chalk_1.default.dim("Answer:")} ${q.answer}`);
                    });
                    break;
                }
                case "blockers": {
                    const blockers = engine.getBlockers();
                    tui.header("BLOCKERS");
                    if (blockers.length === 0) {
                        console.log(`  ${chalk_1.default.green("✓ No blocking questions")}`);
                    }
                    else {
                        blockers.forEach((q) => console.log(`  ${chalk_1.default.red("✗")} ${q.id}: ${q.text}`));
                    }
                    break;
                }
                case "answer": {
                    const [id, ...answerParts] = rest;
                    if (!id || answerParts.length === 0) {
                        console.log(chalk_1.default.yellow("  Usage: /questions answer <id> <value>"));
                        return;
                    }
                    engine.answerQuestion(id, answerParts.join(" "));
                    await engine.save();
                    console.log(`  ${chalk_1.default.green("✓")} Answered question ${id}`);
                    break;
                }
                case "validate": {
                    const gate = new BlockerGate_1.BlockerGate(engine);
                    try {
                        gate.requireUnblocked("validation");
                        console.log(`  ${chalk_1.default.green("✓ COMPILATION CLEAR")}`);
                    }
                    catch (e) {
                        console.log(`  ${chalk_1.default.red("✗ COMPILATION BLOCKED")}: ${e.message}`);
                    }
                    break;
                }
                default:
                    console.log(chalk_1.default.yellow("  Subcommands: list, blockers, answer <id> <value>, validate"));
            }
        },
    });
    // ── /semantics ─────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "semantics",
        description: "Semantic Dictionary: list, define, extract",
        handler: async (args) => {
            const [sub, ...rest] = args.split(/\s+/);
            const dict = new LivingDictionary_1.LivingDictionary();
            await dict.load();
            switch (sub) {
                case "list": {
                    const entries = dict.getAllEntries();
                    tui.header(`SEMANTIC DICTIONARY (${entries.length} terms)`);
                    entries.forEach((entry) => {
                        console.log(`  ${chalk_1.default.cyan("▸")} ${chalk_1.default.bold(entry.term)}`);
                        if (entry.definition)
                            console.log(`     ${chalk_1.default.dim(entry.definition)}`);
                    });
                    if (entries.length === 0) {
                        console.log(`  ${chalk_1.default.dim("No terms defined")}`);
                    }
                    break;
                }
                case "define": {
                    const [term, ...defParts] = rest;
                    if (!term || defParts.length === 0) {
                        console.log(chalk_1.default.yellow("  Usage: /semantics define <term> <definition>"));
                        return;
                    }
                    dict.defineTerm(term, defParts.join(" "));
                    await dict.save();
                    console.log(`  ${chalk_1.default.green("✓")} Defined term: ${term}`);
                    break;
                }
                case "extract": {
                    const text = rest.join(" ") || "Analyze the codebase for common terms used across features and components";
                    const terms = await dict.discoverTerms(text);
                    tui.header("DISCOVERED TERMS");
                    terms.forEach((t) => console.log(`  ${chalk_1.default.cyan("▸")} ${t.term}: ${t.definition}`));
                    break;
                }
                default:
                    console.log(chalk_1.default.yellow("  Subcommands: list, define <term> <def>, extract [text]"));
            }
        },
    });
    // ── /impl ──────────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "impl",
        description: "Implementation Graph: plan, graph, batches",
        handler: async (args) => {
            const [sub, ...rest] = args.split(/\s+/);
            const compiler = new ImplGraphCompiler_1.ImplGraphCompiler();
            switch (sub) {
                case "plan":
                case "batches": {
                    const featureId = rest[0];
                    if (!featureId) {
                        console.log(chalk_1.default.yellow(`  Usage: /impl ${sub} <feature-id>`));
                        return;
                    }
                    const fCompiler = new FeatureGraphCompiler_1.FeatureGraphCompiler();
                    const fGraph = await fCompiler.compileFromContext();
                    const feature = fGraph.getFeatureById(featureId);
                    if (!feature) {
                        console.log(chalk_1.default.red(`  Feature "${featureId}" not found`));
                        return;
                    }
                    const implGraph = await compiler.compileFromFeature(feature);
                    tui.header(`IMPLEMENTATION PLAN: ${feature.name}`);
                    implGraph.batches.forEach((batch, i) => {
                        console.log(`  ${chalk_1.default.cyan(`Batch ${i + 1}:`)} ${batch.id}`);
                        batch.tasks.forEach((task) => {
                            console.log(`    ${chalk_1.default.dim("◉")} ${task.description || task.id}`);
                        });
                    });
                    break;
                }
                case "graph": {
                    const featureId = rest[0];
                    if (!featureId) {
                        console.log(chalk_1.default.yellow("  Usage: /impl graph <feature-id>"));
                        return;
                    }
                    const fCompiler = new FeatureGraphCompiler_1.FeatureGraphCompiler();
                    const fGraph = await fCompiler.compileFromContext();
                    const feature = fGraph.getFeatureById(featureId);
                    if (!feature) {
                        console.log(chalk_1.default.red(`  Feature "${featureId}" not found`));
                        return;
                    }
                    const implGraph = await compiler.compileFromFeature(feature);
                    tui.header(`IMPL GRAPH: ${feature.name}`);
                    const sorted = (0, core_1.topologicalSort)(implGraph);
                    sorted.forEach((node) => {
                        console.log(`  ${chalk_1.default.cyan("◉")} ${node.description || node.id}`);
                    });
                    break;
                }
                default:
                    console.log(chalk_1.default.yellow("  Subcommands: plan <id>, graph <id>, batches <id>"));
            }
        },
    });
    // ── /ops ───────────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "ops",
        description: "Operations: status, registry drift, rollback reference",
        handler: async () => {
            tui.header("OPERATIONS");
            const [operations, registry] = await Promise.all([
                controller.operationStatus(10),
                controller.registryDiff(),
            ]);
            console.log(`  ${chalk_1.default.dim("Registry:")} ${registry.summary}`);
            if (registry.items.length > 0) {
                registry.items.slice(0, 5).forEach((item) => {
                    console.log(`  ${chalk_1.default.yellow("!")} ${item.type}: ${chalk_1.default.gray(item.filePath)}`);
                });
            }
            console.log();
            console.log(chalk_1.default.bold.white("Recent operation history:"));
            if (operations.length === 0) {
                console.log(`  ${chalk_1.default.dim("No operation history entries yet")}`);
            }
            else {
                operations.forEach((entry) => {
                    console.log(`  ${chalk_1.default.cyan(entry.id)} ${entry.status} ${chalk_1.default.dim(entry.action)}`);
                });
            }
            console.log();
            console.log(chalk_1.default.dim("Rollback remains available through operation records and `mycontext op:rollback <id>`."));
        },
    });
    // ── /history ───────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "history",
        description: "Execution History: list, export",
        handler: async (args) => {
            const [sub] = args.split(/\s+/);
            const history = new ExecutionHistory_1.ExecutionHistory();
            switch (sub) {
                case "list": {
                    const entries = await history.list();
                    tui.header(`HISTORY (${entries.length} entries)`);
                    entries.slice(0, 10).forEach((e) => {
                        console.log(`  ${chalk_1.default.dim("◉")} ${chalk_1.default.bold(e.type || "event")}: ${e.action}`);
                        console.log(`     ${chalk_1.default.dim(e.timestamp)} · ${e.status}`);
                    });
                    if (entries.length === 0) {
                        console.log(`  ${chalk_1.default.dim("No history entries yet")}`);
                    }
                    break;
                }
                case "export": {
                    const exported = await history.export("json");
                    console.log(`  ${chalk_1.default.green("✓")} Exported ${exported.length} JSON character(s)`);
                    break;
                }
                default:
                    console.log(chalk_1.default.yellow("  Subcommands: list, export"));
            }
        },
    });
    // ── /agents ────────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "agents",
        description: "Agent Registry: list, status, metrics",
        handler: async (args) => {
            const [sub] = args.split(/\s+/);
            const registry = (0, registry_1.getDefaultRegistry)();
            await registry.load();
            switch (sub) {
                case "list": {
                    const defs = registry.listDefinitions();
                    tui.header(`AGENTS (${defs.length})`);
                    defs.forEach((def) => {
                        console.log(`  ${chalk_1.default.cyan("▸")} ${chalk_1.default.bold(def.name)}`);
                        console.log(`     ${chalk_1.default.dim(def.description)}`);
                        console.log(`     ${chalk_1.default.dim("Scopes:")} ${def.scopes.join(", ")}`);
                    });
                    break;
                }
                case "status": {
                    const report = registry.getMetricsReport();
                    tui.header("AGENT STATUS");
                    console.log(`  ${chalk_1.default.dim("Total:")} ${report.totalAgents} agents`);
                    console.log(`  ${chalk_1.default.dim("Runs:")} ${report.totalRuns} total`);
                    console.log(`  ${chalk_1.default.dim("Errors:")} ${report.totalErrors}`);
                    report.agents.forEach((a) => {
                        const status = a.errorCount > 0 ? chalk_1.default.red("✗") : chalk_1.default.green("✓");
                        console.log(`  ${status} ${chalk_1.default.cyan(a.name)}: ${a.runCount} runs`);
                    });
                    break;
                }
                case "metrics": {
                    const report = registry.getMetricsReport();
                    tui.header("AGENT METRICS");
                    const successRate = report.totalRuns > 0
                        ? Math.round(((report.totalRuns - report.totalErrors) / report.totalRuns) * 100)
                        : 0;
                    console.log(`  ${chalk_1.default.dim("Total agents:")} ${report.totalAgents}`);
                    console.log(`  ${chalk_1.default.dim("Success rate:")} ${successRate}%`);
                    if (Object.keys(report.byCapability).length > 0) {
                        console.log(chalk_1.default.dim(`  By capability:`));
                        for (const [cap, count] of Object.entries(report.byCapability)) {
                            console.log(`    · ${cap}: ${count} agent(s)`);
                        }
                    }
                    break;
                }
                default:
                    console.log(chalk_1.default.yellow("  Subcommands: list, status, metrics"));
            }
        },
    });
    // ── /execute ───────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "execute",
        description: "Run the full semantic-to-execution pipeline",
        handler: async (args) => {
            if (!args.trim()) {
                const pending = controller.getPendingPlan();
                if (!pending) {
                    console.log(chalk_1.default.yellow("  Usage: /execute <prompt>"));
                    return;
                }
                const confirmed = await tui.promptConfirm("Save the pending plan to the Living Brain and execute it?", true);
                if (!confirmed)
                    return;
                await controller.commitPlan(pending);
            }
            tui.header("EXECUTING PIPELINE");
            const result = await controller.execute(args);
            console.log(`  ${result.pipeline.success ? chalk_1.default.green("✓") : chalk_1.default.red("✗")} Pipeline ${result.pipeline.success ? "completed" : "failed"}`);
            console.log(`  ${chalk_1.default.dim("Feature:")} ${result.pipeline.featureId || "none"}`);
            console.log(`  ${chalk_1.default.dim("Operations:")} ${result.pipeline.opsApplied || 0}`);
            result.pipeline.trace.forEach((trace) => {
                const icon = trace.status === "complete" ? chalk_1.default.green("✓") : trace.status === "failed" || trace.status === "blocked" ? chalk_1.default.red("✗") : chalk_1.default.gray("-");
                console.log(`  ${icon} ${trace.stage}${trace.detail ? chalk_1.default.dim(` - ${trace.detail}`) : ""}${trace.error ? chalk_1.default.red(` - ${trace.error}`) : ""}`);
            });
            renderVerificationSummary(result.verification);
        },
    });
    // ── /doctor ────────────────────────────────────────────────────────────
    shell.registerCommand({
        command: "doctor",
        description: "Validation: run doctor checks",
        handler: async (args) => {
            const [sub] = args.split(/\s+/);
            if (sub === "watch") {
                tui.header("DOCTOR WATCH MODE");
                console.log(chalk_1.default.yellow("  Use `mycontext validate:watch` in a separate terminal for watch mode."));
                return;
            }
            tui.header("DOCTOR");
            const summary = await controller.verify();
            renderVerificationSummary(summary);
        },
    });
    function renderVerificationSummary(summary) {
        tui.header("VERIFICATION");
        tui.keyValue({
            "Doctor": `${summary.doctor.score}/100 (${summary.doctor.grade})`,
            "Doctor Issues": `${summary.doctor.errors} error(s), ${summary.doctor.warnings} warning(s)`,
            "Registry": `${summary.registry.driftItems} item(s): ${summary.registry.summary}`,
            "Graph": `${summary.graph.features} feature(s), ${summary.graph.gaps} gap(s)`,
            "Semantics": `${summary.semantics.terms} term(s), ${summary.semantics.conflicts} conflict(s)`,
            "Repair Needed": summary.needsRepair ? "yes" : "no",
        });
    }
}
//# sourceMappingURL=registerNextCommands.js.map