"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.SetupMode = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const ContextSyncer_1 = require("../services/ContextSyncer");
class SetupMode {
    constructor(shell, projectPath = process.cwd()) {
        this.name = "setup";
        this.displayName = "Setup";
        this.description = "Guided project onboarding";
        this.icon = "🌱";
        this.shell = shell;
        this.projectPath = projectPath;
    }
    async initialize() {
        // No-op
    }
    async start() {
        const tui = this.shell.getTUI();
        tui.header("🌱 DREAM INTERVIEW");
        console.log(chalk_1.default.gray("Tell me the dream. MyContext will keep the constraints, compiler, and verification gates.\n"));
        try {
            // 1. Project Name
            const projectName = await tui.promptInput("Enter Project Name:", path.basename(this.projectPath));
            // 2. Project Description
            const projectDescription = await tui.promptInput("Describe the app you want to build:", "A useful AI-native application");
            const targetAudience = await tui.promptInput("Who is it for?", "People who need this workflow");
            const coreConstraint = await tui.promptInput("Name one important constraint:", "Keep the first version small, usable, and verifiable");
            // 3. Project Type
            const projectType = await tui.promptMenu("Select Project Type:", [
                { title: "Fullstack Application (Next.js, etc.)", value: "fullstack" },
                { title: "Landing Page (HTML/JS/CSS)", value: "landing-page" },
                { title: "Basic / General Utility", value: "basic" },
            ]);
            // 4. API Key Check
            let apiKey = process.env.GEMINI_API_KEY || "";
            if (!apiKey) {
                apiKey = await tui.promptInput("Enter your Gemini API Key (leaves blank to use default env):");
            }
            tui.separator();
            const spinner = tui.spinner("Initializing Living Brain...", "cyan");
            // Build context structure with deep specs & flows natively supported
            const initialContext = {
                metadata: {
                    version: "4.2.30",
                    generatedAt: new Date().toISOString(),
                    lastUpdatedAt: new Date().toISOString(),
                    projectConfig: {
                        name: projectName,
                        description: projectDescription,
                        framework: projectType === "fullstack" ? "Next.js" : "HTML",
                        styling: "Vanilla CSS",
                        theme: "dark",
                    },
                },
                projectType,
                project: {
                    name: projectName,
                    description: projectDescription,
                    techStack: [
                        "Node.js",
                        "TypeScript",
                        projectType === "fullstack" ? "Next.js" : "HTML/CSS",
                        "MyContext compiler pipeline",
                    ],
                },
                prd: {
                    title: projectName,
                    problemStatement: projectDescription,
                    goals: [
                        "Turn plain-language product intent into a constrained first app",
                        "Keep implementation aligned with the Living Brain",
                        coreConstraint,
                    ],
                    successMetrics: [
                        "User can complete the core flow",
                        "Execution passes MyContext verification gates",
                        "No implementation happens outside auditable operations",
                    ],
                    targetAudience,
                },
                features: [
                    {
                        id: "FEAT-CORE-01",
                        name: "Initial Landing Structure",
                        description: "Default responsive layout framework",
                        priority: "high",
                        userValue: "Instant premium user onboarding",
                        acceptanceCriteria: [
                            "Layout renders cleanly on mobile and desktop",
                            "Dark/light theme switches work correctly",
                        ],
                        dependencies: [],
                        status: "planned",
                    },
                ],
                flows: [
                    {
                        id: "FLOW-CORE-01",
                        name: "Initial Launch Journey",
                        description: "User loads the application for the first time",
                        actors: ["User"],
                        steps: ["Open landing page", "View introduction banner"],
                        structuredSteps: [
                            {
                                stepNumber: 1,
                                action: "Open landing page",
                                expectedOutcome: "Responsive layout renders cleanly",
                            },
                        ],
                    },
                ],
                specifications: {},
                components: [],
                actions: [],
                routes: [],
                brain: {
                    narrative: `Living Brain for ${projectName}`,
                    status: "active",
                    doctrine: {
                        userRole: "The human is the dreamer and constraint giver.",
                        systemRole: "MyContext is the guard, compiler, builder, verifier, and repair loop.",
                        defaultFlow: "Plan first, preview Brain mutation, then execute through operations after confirmation.",
                    },
                    checkpoints: [
                        { id: "init", label: "Initial setup", status: "complete" },
                    ],
                },
            };
            const mycontextDir = path.join(this.projectPath, ".mycontext");
            await fs.ensureDir(mycontextDir);
            // Write context.json
            await fs.outputJson(path.join(mycontextDir, "context.json"), initialContext, { spaces: 2 });
            // Save key to .env if provided and not currently set
            if (apiKey && !process.env.GEMINI_API_KEY) {
                const envPath = path.join(this.projectPath, ".env");
                const envLine = `\nGEMINI_API_KEY=${apiKey}\n`;
                await fs.appendFile(envPath, envLine);
                process.env.GEMINI_API_KEY = apiKey;
            }
            // Sync and render initial markdown views
            const syncer = new ContextSyncer_1.ContextSyncer(this.projectPath);
            await syncer.refreshMarkdownViews(initialContext);
            tui.stopSpinner("success", "Living Brain successfully initialized!");
            tui.log.success("\n🎉 Setup complete! Transitioning to Agent Chat Cockpit...");
            // Short delay for visual polish
            await new Promise((resolve) => setTimeout(resolve, 1500));
            // Switch to Chat mode
            await this.shell.switchMode("chat");
        }
        catch (e) {
            tui.stopSpinner("error", `Setup failed: ${e.message}`);
            tui.log.error("An error occurred during guided setup.");
        }
    }
    async stop() {
        // No-op
    }
    async handleInput(input) {
        return true;
    }
    renderStatus() {
        return chalk_1.default.yellow("Setup Status: Configuration Required");
    }
}
exports.SetupMode = SetupMode;
//# sourceMappingURL=SetupMode.js.map