"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentChatMode = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const ChatFirstController_1 = require("./ChatFirstController");
const LandingPageOrchestrator_1 = require("../services/LandingPageOrchestrator");
class AgentChatMode {
    constructor(shell, projectPath = process.cwd(), controller) {
        this.name = "chat";
        this.displayName = "Agent Chat";
        this.description = "Autonomous specification cockpit";
        this.icon = "💬";
        this.context = null;
        this.shell = shell;
        this.projectPath = projectPath;
        this.controller = controller || new ChatFirstController_1.ChatFirstController(projectPath);
    }
    async initialize() {
        await this.loadContext();
    }
    async loadContext() {
        const brainPath = path.join(this.projectPath, ".mycontext", "context.json");
        if (await fs.pathExists(brainPath)) {
            try {
                this.context = await fs.readJson(brainPath);
            }
            catch (e) {
                this.context = null;
            }
        }
    }
    async start() {
        const tui = this.shell.getTUI();
        tui.header("💬 MYCONTEXT AGENT CHAT");
        if (!this.context) {
            tui.log.error("Living Brain context.json not found! Switching to Setup Mode...");
            await new Promise((resolve) => setTimeout(resolve, 1500));
            await this.shell.switchMode("setup");
            return;
        }
        // Display high-level dashboard
        tui.log.info(`Project: ${chalk_1.default.bold.cyan(this.context.metadata?.projectConfig?.name || "Unknown")}`);
        tui.log.info(`Description: ${chalk_1.default.gray(this.context.metadata?.projectConfig?.description || "N/A")}`);
        const specCount = this.context.specifications ? Object.keys(this.context.specifications).length : 0;
        const flowCount = this.context.flows ? this.context.flows.length : 0;
        tui.keyValue({
            "Active Specifications": String(specCount),
            "User Flows": String(flowCount),
            "Central Source": ".mycontext/context.json",
        });
        tui.separator();
        console.log(chalk_1.default.gray("Describe the app or feature you want. I will plan first, then build only after you confirm."));
        console.log(chalk_1.default.gray("Try: 'build me a booking app for salons' or 'verify the project'."));
        console.log(chalk_1.default.gray("Type your request below:\n"));
    }
    async stop() {
        // No-op
    }
    async handleInput(input) {
        const tui = this.shell.getTUI();
        if (!this.context) {
            tui.log.error("No active context loaded!");
            return true;
        }
        try {
            tui.userMessage(input);
            const routeSpinner = tui.spinner("Analyzing intent...", "cyan");
            const intent = await this.controller.routeIntent(input);
            routeSpinner.stop();
            tui.log.info(`Intent: ${intent.action} (${intent.reason})`);
            switch (intent.action) {
                case "explore": {
                    const lines = await this.controller.explore(input);
                    tui.assistantMessage(lines.join("\n"));
                    break;
                }
                case "clarify": {
                    const blockers = await this.controller.clarify(input);
                    if (blockers.length === 0) {
                        tui.assistantMessage("Blockers are clear. Say 'build it' when you want me to execute through the compiler.");
                    }
                    else {
                        this.renderBlockers(blockers);
                    }
                    break;
                }
                case "verify": {
                    const spinner = tui.spinner("Running MyContext verification gates...", "cyan");
                    const summary = await this.controller.verify();
                    spinner.succeed("Verification complete");
                    this.renderVerification(summary);
                    break;
                }
                case "compile_landing_page": {
                    tui.assistantMessage("Starting the Landing Page Orchestrator pipeline...");
                    let outputDir = path.join(this.projectPath, "components/landing-page");
                    if (await fs.pathExists(path.join(this.projectPath, "apps/site"))) {
                        outputDir = path.join(this.projectPath, "apps/site/components/landing-page");
                    }
                    else if (await fs.pathExists(path.join(this.projectPath, "../../apps/site"))) {
                        outputDir = path.join(this.projectPath, "../../apps/site/components/landing-page");
                    }
                    else if (await fs.pathExists(path.join(this.projectPath, "src/components"))) {
                        outputDir = path.join(this.projectPath, "src/components/landing-page");
                    }
                    const orchestrator = new LandingPageOrchestrator_1.LandingPageOrchestrator(this.projectPath, outputDir, false);
                    // Phase groupings for better UX (each phase may include multiple pipeline stages)
                    const phases = [
                        { name: "Baseline Check", target: "BASELINE_CHECK", msg: "Verifying shadcn/ui installation..." },
                        { name: "Project Context", target: "CONTEXT_GENERATED", msg: "Extracting Project Context..." },
                        { name: "Narrative & Manifests", target: "PRIMITIVE_MAPPING_GENERATED", msg: "Building narrative, section manifest, and component inventory..." },
                        { name: "Content Schema", target: "CONTENT_SCHEMA_GENERATED", msg: "Generating content schemas..." },
                        { name: "Component Skeletons", target: "SKELETON_GENERATED", msg: "Generating structure-only component skeletons..." },
                        { name: "Content Population", target: "CONTENT_POPULATED", msg: "Populating components with marketing copy..." },
                        { name: "Section Validation", target: "SECTION_VALIDATED", msg: "Validating individual sections..." },
                        { name: "Design Refinement", target: "CLASSNAME_REFINED", msg: "Running constrained design refinement..." },
                        { name: "Final Validation", target: "FINAL_VALIDATED", msg: "Type-checking final components..." }
                    ];
                    for (let i = 0; i < phases.length; i++) {
                        const phase = phases[i];
                        // Skip if we've already passed this stage
                        if (orchestrator.isStageCompleted(phase.target)) {
                            tui.log.info(`${phase.name} completed (loaded from cache).`);
                            continue;
                        }
                        const spinner = tui.spinner(`[Phase ${i + 1}/${phases.length}] ${phase.msg}`, "cyan");
                        // Advance until we reach the target stage
                        while (orchestrator.state.stage !== phase.target &&
                            orchestrator.state.stage !== "FINAL_VALIDATED" &&
                            orchestrator.state.stage !== "SELF_HEALED") {
                            await orchestrator.advance();
                        }
                        spinner.succeed(`${phase.name} completed.`);
                        // Allow TUI to pause after content population for feedback before refinement
                        if (phase.target === "CONTENT_POPULATED") {
                            tui.assistantMessage(`Component skeletons populated at ${outputDir}`);
                            const proceed = await tui.promptConfirm("Proceed with Design Refinement and Validation?", true);
                            if (!proceed) {
                                tui.assistantMessage("Pipeline paused. You can manually review components before refinement.");
                                break;
                            }
                        }
                    }
                    if (orchestrator.state.stage === "FINAL_VALIDATED" || orchestrator.state.stage === "SELF_HEALED") {
                        tui.assistantMessage(`Landing Page Compilation Completed Successfully! Files are ready at: ${outputDir}`);
                        tui.assistantMessage(orchestrator.getCompilationSummary());
                    }
                    break;
                }
                case "heal_runtime_error": {
                    const spinner = tui.spinner("Analyzing error and self-healing component(s)...", "cyan");
                    const result = await this.controller.healError(input);
                    if (result.success) {
                        spinner.succeed("Self-healing complete!");
                        tui.assistantMessage(`Successfully healed the error!
Fixed components: ${result.healedFiles.join(", ")}

Explanation:
${result.explanation || "No explanation provided."}`);
                    }
                    else {
                        spinner.fail("Self-healing failed");
                        tui.log.error(`Error during self-healing: ${result.error}`);
                        tui.assistantMessage(`Self-healing failed: ${result.error}`);
                    }
                    break;
                }
                case "execute": {
                    const pending = this.controller.getPendingPlan();
                    if (pending) {
                        const confirmed = await tui.promptConfirm("Save the pending plan to the Living Brain and execute it?", true);
                        if (!confirmed) {
                            tui.assistantMessage("Execution cancelled. The plan is still pending in this TUI session.");
                            break;
                        }
                        await this.controller.commitPlan(pending);
                        await this.loadContext();
                    }
                    const spinner = tui.spinner("Executing through the MyContext compiler...", "cyan");
                    const result = await this.controller.execute(input);
                    spinner.succeed("Compiler execution finished");
                    this.renderExecution(result);
                    await this.loadContext();
                    break;
                }
                case "plan":
                default: {
                    const spinner = tui.spinner("Compiling a constrained plan preview...", "cyan");
                    const plan = await this.controller.plan(input);
                    spinner.succeed("Plan preview ready");
                    this.renderPlan(plan);
                    if (plan.blockers.length > 0) {
                        tui.assistantMessage("Answer the blocking question(s), then I can build. Example: answer q-abc123 InstantDB");
                        break;
                    }
                    const confirmed = await tui.promptConfirm("Save this plan to the Living Brain?", true);
                    if (confirmed) {
                        await this.controller.commitPlan(plan);
                        await this.loadContext();
                        tui.assistantMessage("Plan saved. Say 'build it' to execute through MyContext operations.");
                    }
                    else {
                        tui.assistantMessage("Plan kept as an unsaved preview. Say 'build it' if you want to save and execute it.");
                    }
                }
            }
        }
        catch (err) {
            tui.log.error(`Error processing request: ${err.message}`);
        }
        return true;
    }
    renderStatus() {
        if (!this.context)
            return chalk_1.default.red("Offline");
        const specCount = this.context.specifications ? Object.keys(this.context.specifications).length : 0;
        return chalk_1.default.green(`Brain Connected | Specifications: ${specCount}`);
    }
    renderPlan(plan) {
        const tui = this.shell.getTUI();
        tui.header("PLAN PREVIEW");
        tui.list(plan.mutation.summary);
        if (plan.nextFeature) {
            tui.separator();
            tui.keyValue({
                "Next Feature": `${plan.nextFeature.name} (${plan.nextFeature.id})`,
                "Description": plan.nextFeature.description,
            });
        }
        if (plan.batches.length > 0) {
            tui.separator();
            console.log(chalk_1.default.bold.white("Implementation batches:"));
            for (const batch of plan.batches) {
                console.log(`  ${chalk_1.default.cyan(batch.id)} ${chalk_1.default.dim(`${batch.taskCount} task(s)`)}`);
                for (const task of batch.tasks.slice(0, 5)) {
                    console.log(`    ${chalk_1.default.dim("-")} ${task}`);
                }
            }
        }
        if (plan.blockers.length > 0) {
            this.renderBlockers(plan.blockers);
        }
    }
    renderBlockers(blockers) {
        const tui = this.shell.getTUI();
        tui.separator();
        console.log(chalk_1.default.bold.yellow("Blocking questions:"));
        for (const blocker of blockers) {
            console.log(`  ${chalk_1.default.red("!")} ${chalk_1.default.cyan(blocker.id)} ${blocker.text}`);
            if (blocker.options?.length) {
                console.log(`     ${chalk_1.default.dim(`Options: ${blocker.options.join(", ")}`)}`);
            }
        }
    }
    renderExecution(result) {
        const tui = this.shell.getTUI();
        tui.header("EXECUTION RESULT");
        tui.keyValue({
            "Pipeline": result.pipeline.success ? "success" : "failed",
            "Feature": result.pipeline.featureId || "none",
            "Operations": String(result.pipeline.opsApplied || 0),
            "Duration": `${result.pipeline.duration}ms`,
        });
        for (const trace of result.pipeline.trace) {
            const marker = trace.status === "complete" ? chalk_1.default.green("✓") : trace.status === "blocked" || trace.status === "failed" ? chalk_1.default.red("✗") : chalk_1.default.gray("-");
            console.log(`  ${marker} ${trace.stage}${trace.detail ? chalk_1.default.dim(` - ${trace.detail}`) : ""}${trace.error ? chalk_1.default.red(` - ${trace.error}`) : ""}`);
        }
        this.renderVerification(result.verification);
    }
    renderVerification(summary) {
        const tui = this.shell.getTUI();
        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",
        });
        if (summary.needsRepair) {
            tui.log.warn("Repair path available: describe the failure or say 'verify' after fixing constraints.");
        }
        else {
            tui.log.success("All verification gates are clear.");
        }
    }
}
exports.AgentChatMode = AgentChatMode;
//# sourceMappingURL=AgentChatMode.js.map