"use strict";
/**
 * Init Interactive Command
 *
 * The user-facing entry point for deterministic compilation with AI-powered inference.
 * This command implements the "Self-Organizing Planner" where the AI:
 * 1. Decomposes the project into inference tasks
 * 2. Auto-infers high-confidence tasks (≥90%)
 * 3. Self-critiques its work
 * 4. Learns from user corrections
 * 5. Only prompts for ambiguous items
 *
 * Flow:
 * 1. Ask: "What are you building?"
 * 2. Decompose into tasks with confidence scores
 * 3. Auto-infer high-confidence tasks
 * 4. Show checkpoints for review
 * 5. Prompt for low-confidence items
 * 6. Show final diff preview
 * 7. Get user approval
 * 8. Save ASL to .mycontext/asl.json
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.InitInteractiveCommand = void 0;
const inquirer_1 = __importDefault(require("inquirer"));
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const promises_1 = __importDefault(require("fs/promises"));
const path_1 = __importDefault(require("path"));
const Planner_1 = require("../services/Planner");
const InferenceEngine_1 = require("../services/InferenceEngine");
const AICore_1 = require("../core/ai/AICore");
const ScaffoldEngine_1 = require("../services/ScaffoldEngine");
const ScaffoldPreview_1 = require("../services/ScaffoldPreview");
class InitInteractiveCommand {
    constructor() {
        this.planner = new Planner_1.Planner();
        this.inferenceEngine = new InferenceEngine_1.InferenceEngine();
        this.ai = AICore_1.AICore.getInstance({
            fallbackEnabled: true,
            workingDirectory: process.cwd(),
        });
        this.asl = {
            version: "1.0",
            project: {
                name: "my-app",
                description: "",
                framework: "nextjs",
                backend: "instantdb",
                styling: "tailwind-shadcn",
                packageManager: "pnpm",
                typescript: true
            }
        };
    }
    /**
     * Main entry point - NEW INFERENCE-BASED FLOW
     */
    async execute() {
        console.log(chalk_1.default.bold.cyan("\n🎯 MyContext Interactive Setup\n"));
        console.log(chalk_1.default.dim("Describe your project and I'll build a complete specification with minimal questions.\n"));
        try {
            // Step 1: Get initial input
            const initialInput = await this.askInitialQuestion();
            // Step 2: Decompose into tasks
            console.log(chalk_1.default.cyan("\n🤖 Breaking down into tasks...\n"));
            const tasks = await this.planner.decompose(initialInput);
            // Seed project name from input if possible (basic heuristic)
            if (this.asl.project) {
                const nameMatch = initialInput.match(/^([A-Z][a-zA-Z0-9]+):/);
                if (nameMatch && nameMatch[1]) {
                    this.asl.project.name = nameMatch[1].toLowerCase();
                }
                else {
                    // Default to a sanitized version of first 2 words
                    const words = initialInput.split(' ').slice(0, 2).map(w => w.replace(/[^a-zA-Z0-9]/g, '').toLowerCase());
                    this.asl.project.name = words.join('-') || "my-app";
                }
            }
            this.displayTaskDecomposition(tasks);
            // Step 3: Recursive inference loop
            console.log(chalk_1.default.cyan("\n🤖 Auto-inferring high-confidence tasks...\n"));
            await this.recursiveInferenceLoop();
            // Step 4: Show checkpoints and get approval
            await this.showCheckpointsAndConfirm();
            // Step 5: Show final diff preview
            await this.showDiffPreview();
            // Step 6: Get final approval
            const approved = await this.getApproval();
            if (approved) {
                // Step 7: Save ASL
                await this.saveASL();
                console.log(chalk_1.default.green("\n✓ Specification complete!\n"));
                console.log(chalk_1.default.cyan("📊 Summary:"));
                console.log(chalk_1.default.gray(`   Auto-inferred: ${this.getAutoInferredCount()} items`));
                console.log(chalk_1.default.gray(`   User prompted: ${this.getUserPromptedCount()} items`));
                console.log(chalk_1.default.gray(`   Overall confidence: ${this.planner.getState().confidenceScore}%\n`));
                // Step 8: Ask about scaffolding
                const shouldScaffold = await this.askScaffold();
                if (shouldScaffold) {
                    // Step 9: Show full scaffold preview
                    await this.showScaffoldPreview();
                    // Step 10: Get scaffold confirmation
                    const scaffoldConfirmed = await this.confirmScaffold();
                    if (scaffoldConfirmed) {
                        // Step 11: Run scaffold
                        await this.runScaffold();
                    }
                    else {
                        console.log(chalk_1.default.cyan("\nYou can run scaffolding later with: ") + chalk_1.default.bold("mycontext scaffold --from-manifest\n"));
                    }
                }
                else {
                    console.log(chalk_1.default.cyan("\nNext step: Run ") + chalk_1.default.bold("mycontext scaffold --from-manifest\n"));
                }
            }
            else {
                console.log(chalk_1.default.yellow("\n⚠ Setup cancelled\n"));
            }
        }
        catch (error) {
            console.error(chalk_1.default.red("\n✗ Setup failed:"), error);
            throw error;
        }
    }
    // ============================================================================
    // NEW INFERENCE-BASED METHODS
    // ============================================================================
    /**
     * Ask single initial question
     */
    async askInitialQuestion() {
        const answers = await inquirer_1.default.prompt([
            {
                type: "input",
                name: "description",
                message: "What are you building?",
                validate: (input) => {
                    if (!input || input.length < 10) {
                        return "Please provide at least 10 characters describing your project";
                    }
                    return true;
                },
            },
        ]);
        return answers.description;
    }
    /**
     * Display task decomposition
     */
    displayTaskDecomposition(tasks) {
        console.log(chalk_1.default.bold("📋 Task decomposition:\n"));
        tasks.forEach((task, idx) => {
            const confidenceColor = task.confidence >= 90 ? chalk_1.default.green :
                task.confidence >= 70 ? chalk_1.default.yellow :
                    chalk_1.default.red;
            console.log(chalk_1.default.gray(`  ${idx + 1}.`) +
                ` ${task.description} - ` +
                confidenceColor(`${task.confidence}% confidence`));
        });
        console.log(chalk_1.default.gray(`\n  Total: ${tasks.length} tasks\n`));
    }
    /**
     * Recursive inference loop
     */
    async recursiveInferenceLoop() {
        const state = this.planner.getState();
        const completedTasks = [];
        const autoInferredTasks = [];
        while (true) {
            // Select next task
            const task = this.planner.selectNextTask();
            if (!task)
                break;
            if (task.autoInfer) {
                // Auto-infer with spinner
                const spinner = (0, ora_1.default)(`Inferring: ${task.description}`).start();
                try {
                    // Run inference
                    const inference = await this.inferenceEngine.infer(task, this.asl, completedTasks);
                    // Self-critique
                    const critique = await this.inferenceEngine.selfCritique(inference, this.asl);
                    spinner.stop();
                    if (critique.confidence >= 90) {
                        // Accept inference
                        this.mergeInference(inference.result);
                        task.inference = inference.result;
                        task.reasoning = inference.reasoning;
                        // Reveal context
                        const revelations = this.planner.revealContext(task, inference.result);
                        revelations.forEach(rev => {
                            console.log(chalk_1.default.green("✓") +
                                ` ${rev.message} ` +
                                chalk_1.default.gray(`(${rev.confidence}% confidence)`));
                        });
                        autoInferredTasks.push(task);
                        this.planner.markTaskComplete(task.id);
                        completedTasks.push(task);
                        // Update dependent tasks
                        this.planner.updateDependentTasks(task);
                    }
                    else {
                        // Drop to confirmation
                        task.needsConfirmation = true;
                        await this.confirmInference(task, inference, critique);
                    }
                }
                catch (error) {
                    spinner.fail(`Failed to infer: ${task.description}`);
                    console.error(chalk_1.default.red(error));
                }
            }
            else if (task.needsConfirmation) {
                // Suggest with confirmation
                await this.confirmInference(task, null);
            }
            else {
                // Direct user prompt
                await this.promptUser(task);
            }
        }
        // Create checkpoint if we auto-inferred anything
        if (autoInferredTasks.length > 0) {
            this.planner.createCheckpoint(autoInferredTasks);
        }
    }
    /**
     * Confirm inference with user
     */
    async confirmInference(task, inference, critique) {
        console.log(chalk_1.default.yellow("\n❓ Need confirmation:\n"));
        console.log(chalk_1.default.dim(`   ${task.description}\n`));
        if (inference) {
            console.log(chalk_1.default.dim("   Suggested:"));
            console.log(chalk_1.default.dim(`   ${JSON.stringify(inference.result, null, 2)}\n`));
            if (critique && critique.issues.length > 0) {
                console.log(chalk_1.default.yellow("   ⚠ Potential issues:"));
                critique.issues.forEach((issue) => {
                    console.log(chalk_1.default.yellow(`   • ${issue.message}`));
                });
                console.log();
            }
        }
        const { confirmed } = await inquirer_1.default.prompt([
            {
                type: "confirm",
                name: "confirmed",
                message: "Accept this inference?",
                default: true,
            },
        ]);
        if (confirmed && inference) {
            this.mergeInference(inference.result);
            task.inference = inference.result;
            this.planner.markTaskComplete(task.id);
        }
        else {
            // Fall back to direct prompt
            await this.promptUser(task);
        }
    }
    /**
     * Prompt user directly for a task
     */
    async promptUser(task) {
        console.log(chalk_1.default.cyan(`\n❓ ${task.description}\n`));
        // Generic text input for now
        // TODO: Add type-specific prompts (select, multi-select, etc.)
        const { answer } = await inquirer_1.default.prompt([
            {
                type: "input",
                name: "answer",
                message: "Your answer:",
            },
        ]);
        // Parse answer with AI
        const spinner = (0, ora_1.default)("Processing your answer...").start();
        try {
            const parsedInference = await this.inferenceEngine.infer({
                ...task,
                description: `${task.description}. User said: "${answer}"`,
            }, this.asl, []);
            this.mergeInference(parsedInference.result);
            task.inference = parsedInference.result;
            spinner.succeed("Answer processed");
            this.planner.markTaskComplete(task.id);
        }
        catch (error) {
            spinner.fail("Failed to process answer");
            console.error(chalk_1.default.red(error));
        }
    }
    /**
     * Helper to merge inference results into current ASL
     */
    mergeInference(result) {
        if (!result)
            return;
        // Handle entities (special case for array to object)
        if (result.entities) {
            if (!this.asl.entities)
                this.asl.entities = {};
            if (Array.isArray(result.entities)) {
                result.entities.forEach((entity) => {
                    this.asl.entities[entity.name] = entity;
                });
            }
            else {
                this.asl.entities = { ...this.asl.entities, ...result.entities };
            }
        }
        // Merge other sections
        if (result.project)
            this.asl.project = { ...this.asl.project, ...result.project };
        if (result.auth)
            this.asl.auth = { ...this.asl.auth, ...result.auth };
        if (result.permissions) {
            this.asl.permissions = [...(this.asl.permissions || []), ...result.permissions];
        }
        if (result.pages) {
            this.asl.pages = [...(this.asl.pages || []), ...result.pages];
        }
        if (result.design)
            this.asl.design = { ...this.asl.design, ...result.design };
    }
    /**
     * Show checkpoints and get confirmation
     */
    async showCheckpointsAndConfirm() {
        const state = this.planner.getState();
        if (state.checkpoints.length === 0)
            return;
        console.log(chalk_1.default.cyan("\n💡 Checkpoint - Review Auto-Inferred Items:\n"));
        state.checkpoints.forEach(checkpoint => {
            console.log(chalk_1.default.bold(`  Checkpoint ${checkpoint.id}:`));
            console.log(chalk_1.default.gray(`  ✓ ${checkpoint.summary.entitiesCreated.length} entities`));
            console.log(chalk_1.default.gray(`  ✓ ${checkpoint.summary.fieldsAdded} fields`));
            console.log(chalk_1.default.gray(`  ✓ ${checkpoint.summary.rolesCreated.length} roles`));
            console.log(chalk_1.default.gray(`  ✓ ${checkpoint.summary.permissionsAdded} permissions`));
            console.log(chalk_1.default.gray(`  ✓ ${checkpoint.summary.pagesCreated.length} pages`));
            console.log(chalk_1.default.gray(`  Overall confidence: ${checkpoint.summary.totalConfidence}%\n`));
        });
        const { action } = await inquirer_1.default.prompt([
            {
                type: "list",
                name: "action",
                message: "What would you like to do?",
                choices: [
                    { name: "Continue", value: "continue" },
                    { name: "Edit inferences", value: "edit" },
                    { name: "Cancel", value: "cancel" },
                ],
            },
        ]);
        if (action === "cancel") {
            throw new Error("User cancelled");
        }
        if (action === "edit") {
            // TODO: Implement interactive editing
            console.log(chalk_1.default.yellow("\n⚠ Interactive editing coming soon. For now, you can edit in the final diff.\n"));
        }
    }
    /**
     * Get counts for summary
     */
    getAutoInferredCount() {
        const state = this.planner.getState();
        return state.tasks.filter(t => t.autoInfer && t.completed).length;
    }
    getUserPromptedCount() {
        const state = this.planner.getState();
        return state.tasks.filter(t => !t.autoInfer && t.completed).length;
    }
    // ============================================================================
    // OLD METHODS (KEEP FOR COMPATIBILITY)
    // ============================================================================
    /**
     * OLD: Recursive clarification loop (legacy, not used in new flow)
     */
    async recursiveClarificationLoop_OLD() {
        let iteration = 0;
        const maxIterations = 20; // Safety limit
        while (!this.planner.isComplete(this.asl) && iteration < maxIterations) {
            iteration++;
            // Validate current ASL
            const validation = this.planner.validate(this.asl);
            console.log(chalk_1.default.cyan(`\n📊 Completeness: ${chalk_1.default.bold(validation.completeness + "%")}\n`));
            // Generate questions for gaps
            const questions = this.planner.generateQuestions(this.asl);
            if (questions.length === 0) {
                // No more questions, but still not complete
                // This shouldn't happen, but handle gracefully
                console.log(chalk_1.default.yellow("⚠ No more questions, but specification may be incomplete"));
                break;
            }
            // Ask questions in batches by category
            const categorized = this.categorizeQuestions(questions);
            for (const [category, categoryQuestions] of Object.entries(categorized)) {
                await this.askQuestionBatch(category, categoryQuestions);
            }
        }
        if (iteration >= maxIterations) {
            console.log(chalk_1.default.yellow("\n⚠ Reached maximum iterations. Proceeding with current state.\n"));
        }
    }
    /**
     * Ask a batch of questions for a specific category
     */
    async askQuestionBatch(category, questions) {
        console.log(chalk_1.default.bold.cyan(`\n📝 ${this.categoryLabel(category)}\n`));
        for (const question of questions) {
            const answer = await this.askQuestion(question);
            await this.processAnswer(question, answer);
        }
    }
    /**
     * Ask a single question
     */
    async askQuestion(question) {
        const inquirerQuestion = {
            type: this.mapQuestionType(question.type),
            name: "answer",
            message: question.text,
        };
        if (question.options) {
            inquirerQuestion.choices = question.options.map(opt => ({
                name: opt.description ? `${opt.label} - ${opt.description}` : opt.label,
                value: opt.value,
            }));
        }
        if (question.validation?.required) {
            inquirerQuestion.validate = (input) => {
                if (!input)
                    return "This field is required";
                return true;
            };
        }
        const { answer } = await inquirer_1.default.prompt([inquirerQuestion]);
        return answer;
    }
    /**
     * Process answer and update ASL
     */
    async processAnswer(question, answer) {
        const [section, ...rest] = question.id.split(".");
        switch (section) {
            case "project":
                this.updateProject(rest.join("."), answer);
                break;
            case "entities":
                await this.updateEntities(rest, answer);
                break;
            case "auth":
                this.updateAuth(rest.join("."), answer);
                break;
            case "permissions":
                this.updatePermissions(rest.join("."), answer);
                break;
            case "pages":
                await this.updatePages(rest, answer);
                break;
            case "design":
                this.updateDesign(rest.join("."), answer);
                break;
        }
    }
    /**
     * Update project section
     */
    updateProject(field, value) {
        if (!this.asl.project) {
            this.asl.project = {
                name: "",
                description: "",
                framework: "nextjs",
                backend: "instantdb",
            };
        }
        this.asl.project[field] = value;
    }
    /**
     * Update entities section (uses AI to parse)
     */
    async updateEntities(path, value) {
        if (!this.asl.entities)
            this.asl.entities = {};
        if (path[0] === "list") {
            // Parse entity list
            const entityNames = value.split(",").map((e) => e.trim());
            entityNames.forEach((name) => {
                if (!this.asl.entities[name]) {
                    this.asl.entities[name] = {
                        name,
                        fields: [],
                        timestamps: true,
                    };
                }
            });
        }
        else if (path[1] === "fields") {
            // Parse fields for specific entity
            const entityName = path[0];
            if (!entityName)
                return;
            const fields = await this.parseFieldsWithAI(entityName, value);
            if (this.asl.entities && this.asl.entities[entityName]) {
                this.asl.entities[entityName].fields = fields;
            }
        }
    }
    /**
     * Use AI to parse field definitions from natural language
     */
    async parseFieldsWithAI(entityName, userInput) {
        const spinner = (0, ora_1.default)(`Parsing fields for ${entityName}...`).start();
        try {
            const prompt = `Parse the following field definitions for entity "${entityName}" into structured JSON.

User input: ${userInput}

Return a JSON array of fields with this structure:
{
  "fields": [
    {
      "name": "fieldName",
      "type": "string" | "number" | "boolean" | "date" | "json" | "ref",
      "required": true | false,
      "description": "field description"
    }
  ]
}

Examples:
- "title (string, required), content (string), published (boolean)"
- "email (unique string), age (number), bio (optional string)"

Return only valid JSON, no markdown.`;
            const response = await this.ai.generateText(prompt, {
                temperature: 0.1,
                maxTokens: 1000,
            });
            const parsed = JSON.parse(response);
            spinner.succeed(`Parsed ${parsed.fields.length} fields for ${entityName}`);
            return parsed.fields;
        }
        catch (error) {
            spinner.fail("Failed to parse fields");
            console.error(error);
            return [];
        }
    }
    /**
     * Update auth section
     */
    updateAuth(field, value) {
        if (!this.asl.auth) {
            this.asl.auth = {
                provider: "email",
                roles: [],
            };
        }
        if (field === "provider") {
            this.asl.auth.provider = value;
        }
        else if (field === "roles") {
            // Convert array of role names to RoleSpec[]
            if (Array.isArray(value)) {
                this.asl.auth.roles = value.map(name => ({
                    name,
                    description: `${name} role`,
                }));
            }
        }
        else if (field === "needed") {
            if (!value) {
                delete this.asl.auth;
            }
        }
    }
    /**
     * Update permissions section
     */
    updatePermissions(field, value) {
        if (!this.asl.permissions)
            this.asl.permissions = [];
        if (field === "needed" && value) {
            // Generate default permissions based on roles and entities
            if (this.asl.auth?.roles && this.asl.entities) {
                this.asl.auth.roles.forEach(role => {
                    Object.keys(this.asl.entities).forEach(entity => {
                        if (role.name === "admin") {
                            // Admins get full access
                            this.asl.permissions.push({
                                role: role.name,
                                resource: entity,
                                actions: ["create", "read", "update", "delete"],
                            });
                        }
                        else {
                            // Regular users get limited access
                            this.asl.permissions.push({
                                role: role.name,
                                resource: entity,
                                actions: ["read"],
                                condition: { type: "own", field: "user_id" },
                            });
                        }
                    });
                });
            }
        }
    }
    /**
     * Update pages section (uses AI to parse)
     */
    async updatePages(path, value) {
        if (!this.asl.pages)
            this.asl.pages = [];
        if (path[0] === "list") {
            // Parse page list
            const pages = await this.parsePagesWithAI(value);
            this.asl.pages = pages;
        }
        else {
            // Update specific page field
            const match = path[0]?.match(/\d+/);
            const pageIndex = parseInt(match?.[0] || "0");
            const field = path[1];
            if (!this.asl.pages || !this.asl.pages[pageIndex] || !field)
                return;
            this.asl.pages[pageIndex][field] = value;
        }
    }
    /**
     * Use AI to parse page definitions
     */
    async parsePagesWithAI(userInput) {
        const spinner = (0, ora_1.default)("Parsing pages...").start();
        try {
            const prompt = `Parse the following page definitions into structured JSON.

User input: ${userInput}

Return a JSON array of pages with this structure:
{
  "pages": [
    {
      "path": "/path",
      "name": "PageName",
      "type": "page",
      "title": "Page Title",
      "public": true | false
    }
  ]
}

Examples:
- "Home (/), Posts (/posts), Profile (/profile)"
- "Landing page (public), Dashboard (/dashboard, protected), Settings"

Return only valid JSON, no markdown.`;
            const response = await this.ai.generateText(prompt, {
                temperature: 0.1,
                maxTokens: 1000,
            });
            const parsed = JSON.parse(response);
            spinner.succeed(`Parsed ${parsed.pages.length} pages`);
            return parsed.pages;
        }
        catch (error) {
            spinner.fail("Failed to parse pages");
            console.error(error);
            return [];
        }
    }
    /**
     * Update design section
     */
    updateDesign(field, value) {
        if (!this.asl.design) {
            this.asl.design = {
                theme: "light",
            };
        }
        this.asl.design[field] = value;
    }
    /**
     * Show diff preview
     */
    async showDiffPreview() {
        console.log(chalk_1.default.bold.cyan("\n📋 Generation Preview\n"));
        const diff = this.planner.generateDiff(this.asl);
        // Summary
        console.log(chalk_1.default.bold("Summary:"));
        console.log(chalk_1.default.green(`  ✓ ${diff.summary.totalFiles} files will be generated`));
        console.log(chalk_1.default.cyan(`  ✓ ~${Math.round(diff.summary.linesAdded)} lines of code`));
        console.log();
        // File breakdown
        console.log(chalk_1.default.bold("Files:"));
        const filesByType = this.groupFilesByType(diff.files);
        Object.entries(filesByType).forEach(([type, files]) => {
            console.log(chalk_1.default.cyan(`  ${this.fileTypeLabel(type)}: ${files.length}`));
        });
        console.log();
        // Registries
        if (diff.registries.length > 0) {
            console.log(chalk_1.default.bold("Registries:"));
            diff.registries.forEach(reg => {
                console.log(chalk_1.default.cyan(`  ${reg.type}: ${reg.added.length} items`));
            });
            console.log();
        }
        // Warnings
        if (diff.warnings && diff.warnings.length > 0) {
            console.log(chalk_1.default.bold.yellow("⚠ Warnings:"));
            diff.warnings.forEach(warning => {
                console.log(chalk_1.default.yellow(`  - ${warning}`));
            });
            console.log();
        }
        // Show sample files
        console.log(chalk_1.default.bold("Sample files:\n"));
        diff.files.slice(0, 5).forEach(file => {
            console.log(chalk_1.default.dim(`  ${file.path}`));
            if (file.preview) {
                console.log(chalk_1.default.dim(`    ${file.preview.split("\n").slice(0, 2).join("\n    ")}`));
            }
        });
        if (diff.files.length > 5) {
            console.log(chalk_1.default.dim(`  ... and ${diff.files.length - 5} more files`));
        }
        console.log();
    }
    /**
     * Get user approval
     */
    async getApproval() {
        const { approve } = await inquirer_1.default.prompt([
            {
                type: "confirm",
                name: "approve",
                message: "Generate these files?",
                default: true,
            },
        ]);
        return approve;
    }
    /**
     * Save ASL to .mycontext/asl.json
     */
    async saveASL() {
        const spinner = (0, ora_1.default)("Saving manifest...").start();
        try {
            // Ensure .mycontext directory exists
            const mycontextDir = path_1.default.join(process.cwd(), ".mycontext");
            await promises_1.default.mkdir(mycontextDir, { recursive: true });
            // Save ASL (legacy compatibility)
            const aslPath = path_1.default.join(mycontextDir, "asl.json");
            await promises_1.default.writeFile(aslPath, JSON.stringify(this.asl, null, 2), "utf-8");
            // Save to Living Brain (Preferred SSOT)
            const brainPath = path_1.default.join(mycontextDir, "context.json");
            let brain = {};
            try {
                const existing = await promises_1.default.readFile(brainPath, "utf-8");
                brain = JSON.parse(existing);
            }
            catch (e) {
                // use default skeleton if not exists
                brain = { version: "1.0.0", metadata: {}, prd: {}, specs: { techStack: {} }, components: [] };
            }
            // Merge ASL data into Brain
            brain.project_name = this.asl.project?.name || brain.project_name;
            brain.prd = {
                ...brain.prd,
                title: this.asl.project?.name || brain.prd.title,
                problemStatement: this.asl.project?.description || brain.prd.problemStatement,
            };
            if (this.asl.project?.framework) {
                brain.specs.techStack.frontend = [this.asl.project.framework, "Tailwind", "shadcn/ui"];
            }
            if (this.asl.project?.backend) {
                brain.specs.techStack.backend = [this.asl.project.backend];
            }
            // Store full ASL in metadata for deep recovery
            brain.metadata.asl = this.asl;
            brain.metadata.lastUpdatedAt = new Date().toISOString();
            await promises_1.default.writeFile(brainPath, JSON.stringify(brain, null, 2), "utf-8");
            spinner.succeed(`Manifest saved to ${chalk_1.default.cyan(".mycontext/asl.json")} and ${chalk_1.default.cyan(".mycontext/context.json")}`);
        }
        catch (error) {
            spinner.fail("Failed to save manifest");
            throw error;
        }
    }
    // ============================================================================
    // HELPER METHODS
    // ============================================================================
    categorizeQuestions(questions) {
        const categorized = {};
        questions.forEach(q => {
            if (!categorized[q.category]) {
                categorized[q.category] = [];
            }
            categorized[q.category].push(q);
        });
        return categorized;
    }
    categoryLabel(category) {
        const labels = {
            project: "Project Information",
            entities: "Data Models (Entities)",
            auth: "Authentication",
            permissions: "Permissions (RBAC)",
            pages: "Pages & Routes",
            design: "Design & Styling",
        };
        return labels[category] || category;
    }
    mapQuestionType(type) {
        const mapping = {
            text: "input",
            number: "number",
            boolean: "confirm",
            select: "list",
            "multi-select": "checkbox",
            "entity-builder": "input",
            "field-builder": "input",
        };
        return mapping[type] || "input";
    }
    groupFilesByType(files) {
        const grouped = {};
        files.forEach(file => {
            if (!grouped[file.type]) {
                grouped[file.type] = [];
            }
            grouped[file.type].push(file);
        });
        return grouped;
    }
    fileTypeLabel(type) {
        const labels = {
            schema: "Schema",
            type: "Types",
            page: "Pages",
            component: "Components",
            action: "Server Actions",
            config: "Configuration",
        };
        return labels[type] || type;
    }
    // ============================================================================
    // SCAFFOLD FLOW METHODS
    // ============================================================================
    /**
     * Ask if user wants to scaffold now
     */
    async askScaffold() {
        const { shouldScaffold } = await inquirer_1.default.prompt([
            {
                type: "confirm",
                name: "shouldScaffold",
                message: "Ready to scaffold your project?",
                default: true,
            },
        ]);
        return shouldScaffold;
    }
    /**
     * Show full scaffold preview (per user preference for "full manifest")
     */
    async showScaffoldPreview() {
        const spinner = (0, ora_1.default)("Generating scaffold preview...").start();
        try {
            const preview = new ScaffoldPreview_1.ScaffoldPreview(this.asl);
            const manifest = preview.generateManifest();
            spinner.stop();
            console.log(chalk_1.default.bold.cyan("\n📦 Scaffold Preview\n"));
            // File tree
            console.log(chalk_1.default.bold("Project Structure:\n"));
            console.log(manifest.fileTree);
            console.log();
            // Components summary
            console.log(chalk_1.default.bold("Components:"));
            console.log(chalk_1.default.cyan(`  shadCN: ${manifest.componentsSummary.shadcn.length} components`));
            console.log(chalk_1.default.gray(`  ${manifest.componentsSummary.shadcn.join(", ")}`));
            console.log(chalk_1.default.cyan(`  Custom: ${manifest.componentsSummary.custom} components`));
            console.log();
            // Features
            console.log(chalk_1.default.bold("Features:"));
            manifest.features.forEach(feature => {
                console.log(chalk_1.default.green(`  ✓ ${feature}`));
            });
            console.log();
            // Stats
            console.log(chalk_1.default.bold("Stats:"));
            console.log(chalk_1.default.cyan(`  Total files: ${manifest.totalFiles}`));
            console.log(chalk_1.default.cyan(`  Estimated time: ${manifest.estimatedTime}`));
            console.log();
        }
        catch (error) {
            spinner.fail("Failed to generate preview");
            console.error(chalk_1.default.red(error));
            throw error;
        }
    }
    /**
     * Get confirmation before scaffolding
     */
    async confirmScaffold() {
        const { confirmed } = await inquirer_1.default.prompt([
            {
                type: "confirm",
                name: "confirmed",
                message: "Proceed with scaffolding?",
                default: true,
            },
        ]);
        return confirmed;
    }
    /**
     * Run scaffold engine
     */
    async runScaffold() {
        console.log(chalk_1.default.cyan("\n🚀 Starting deterministic compilation...\n"));
        try {
            const scaffoldEngine = new ScaffoldEngine_1.ScaffoldEngine();
            await scaffoldEngine.scaffold(this.asl);
            console.log(chalk_1.default.green("\n✓ Project scaffolded successfully!\n"));
            console.log(chalk_1.default.bold("Next steps:\n"));
            console.log(chalk_1.default.cyan(`  1. cd ${this.asl.project?.name || "your-project"}`));
            console.log(chalk_1.default.cyan("  2. pnpm install"));
            console.log(chalk_1.default.cyan("  3. pnpm dev\n"));
        }
        catch (error) {
            console.error(chalk_1.default.red("\n✗ Scaffold failed:"), error);
            throw error;
        }
    }
}
exports.InitInteractiveCommand = InitInteractiveCommand;
//# sourceMappingURL=init-interactive.js.map