"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.ReviewContextCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const prompts_1 = __importDefault(require("prompts"));
const fs = __importStar(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const fileSystem_1 = require("../utils/fileSystem");
const ContextValidator_1 = require("../services/ContextValidator");
class ReviewContextCommand {
    constructor() {
        this.fs = new fileSystem_1.FileSystemManager();
        this.contextValidator = new ContextValidator_1.ContextValidator();
    }
    async execute(options) {
        console.log(chalk_1.default.blue("🔍 Reviewing context files and auto-generated features..."));
        try {
            const contextDir = ".mycontext";
            // Check if auto-generated.json exists
            const autoGeneratedPath = path_1.default.join(contextDir, "auto-generated.json");
            if (!(await this.fs.exists(autoGeneratedPath))) {
                console.log(chalk_1.default.yellow("⚠️  No auto-generated features found. Run 'mycontext generate:context' first."));
                return;
            }
            // Load auto-generated data
            const autoGeneratedData = JSON.parse(await this.fs.readFile(autoGeneratedPath));
            const { features, gaps } = autoGeneratedData;
            if (features.length === 0 && gaps.length === 0) {
                console.log(chalk_1.default.green("✅ No features or gaps to review."));
                return;
            }
            // Review critical gaps first
            if (!options.skipGaps && gaps.length > 0) {
                await this.reviewGaps(gaps, options);
            }
            // Review auto-generated features
            if (features.length > 0) {
                await this.reviewFeatures(features, options);
            }
            // Save approvals
            await this.saveApprovals(contextDir, features, gaps);
            console.log(chalk_1.default.green("✅ Context review completed!"));
        }
        catch (error) {
            console.error(chalk_1.default.red("❌ Context review failed:"), error);
            throw error;
        }
    }
    /**
     * Review critical gaps and get user input
     */
    async reviewGaps(gaps, options) {
        const criticalGaps = gaps.filter((gap) => gap.category === "critical");
        const importantGaps = gaps.filter((gap) => gap.category === "important");
        const optionalGaps = gaps.filter((gap) => gap.category === "optional");
        if (criticalGaps.length > 0) {
            console.log(chalk_1.default.red("\n❌ Critical information missing:"));
            await this.handleGaps(criticalGaps, "critical", options);
        }
        if (importantGaps.length > 0) {
            console.log(chalk_1.default.yellow("\n⚠️  Important information missing:"));
            await this.handleGaps(importantGaps, "important", options);
        }
        if (optionalGaps.length > 0) {
            console.log(chalk_1.default.blue("\n💡 Optional improvements:"));
            await this.handleGaps(optionalGaps, "optional", options);
        }
    }
    /**
     * Handle gaps of a specific category
     */
    async handleGaps(gaps, category, options) {
        for (const gap of gaps) {
            console.log(chalk_1.default.yellow(`\n${gap.question}`));
            console.log(chalk_1.default.gray(`   ${gap.reasoning}`));
            if (gap.suggestedAnswers && gap.suggestedAnswers.length > 0) {
                const response = await (0, prompts_1.default)({
                    type: "select",
                    name: "answer",
                    message: "Choose an answer:",
                    choices: gap.suggestedAnswers.map((answer, index) => ({
                        title: answer,
                        value: answer,
                        description: `Option ${String.fromCharCode(97 + index)}`,
                    })),
                    initial: 0,
                });
                if (response.answer) {
                    // Store the answer for later use
                    gap.userAnswer = response.answer;
                }
            }
            else {
                const response = await (0, prompts_1.default)({
                    type: "text",
                    name: "answer",
                    message: "Please provide the missing information:",
                    validate: (value) => value.length > 0 ? true : "Please provide an answer",
                });
                if (response.answer) {
                    gap.userAnswer = response.answer;
                }
            }
        }
    }
    /**
     * Review auto-generated features
     */
    async reviewFeatures(features, options) {
        console.log(chalk_1.default.yellow("\n📋 Auto-generated Features Review"));
        console.log(chalk_1.default.gray("Review each feature and decide whether to keep it:"));
        for (const feature of features) {
            console.log(chalk_1.default.blue(`\n${feature.feature}`));
            console.log(chalk_1.default.gray(`   Reasoning: ${feature.reasoning}`));
            console.log(chalk_1.default.gray(`   Confidence: ${feature.confidence}`));
            console.log(chalk_1.default.gray(`   Source: ${feature.contextSource}`));
            if (options.autoApprove) {
                feature.approved = true;
                console.log(chalk_1.default.green("   ✅ Auto-approved"));
                continue;
            }
            const response = await (0, prompts_1.default)({
                type: "select",
                name: "action",
                message: "What would you like to do?",
                choices: [
                    {
                        title: "Accept",
                        value: "accept",
                        description: "Keep this feature",
                    },
                    {
                        title: "Reject",
                        value: "reject",
                        description: "Remove this feature",
                    },
                    { title: "Edit", value: "edit", description: "Modify this feature" },
                    { title: "Skip", value: "skip", description: "Decide later" },
                ],
                initial: 0,
            });
            switch (response.action) {
                case "accept":
                    feature.approved = true;
                    feature.modified = false;
                    console.log(chalk_1.default.green("   ✅ Accepted"));
                    break;
                case "reject":
                    feature.approved = false;
                    feature.modified = false;
                    console.log(chalk_1.default.red("   ❌ Rejected"));
                    break;
                case "edit":
                    await this.editFeature(feature);
                    break;
                case "skip":
                    feature.approved = null;
                    console.log(chalk_1.default.yellow("   ⏭️  Skipped"));
                    break;
            }
        }
    }
    /**
     * Edit a feature
     */
    async editFeature(feature) {
        const response = await (0, prompts_1.default)({
            type: "text",
            name: "editedFeature",
            message: "Edit the feature description:",
            initial: feature.feature,
            validate: (value) => value.length > 0 ? true : "Please provide a description",
        });
        if (response.editedFeature) {
            feature.feature = response.editedFeature;
            feature.approved = true;
            feature.modified = true;
            console.log(chalk_1.default.green("   ✏️  Feature updated"));
        }
    }
    /**
     * Save approvals to file
     */
    async saveApprovals(contextDir, features, gaps) {
        const approvalsData = {
            features: features.reduce((acc, feature) => {
                acc[feature.id] = {
                    approved: feature.approved,
                    modified: feature.modified || false,
                    feature: feature.feature,
                    reasoning: feature.reasoning,
                };
                return acc;
            }, {}),
            gaps_addressed: gaps.reduce((acc, gap) => {
                if (gap.userAnswer) {
                    acc[gap.id] = gap.userAnswer;
                }
                return acc;
            }, {}),
            timestamp: new Date().toISOString(),
            version: "1.0",
        };
        await this.fs.writeFile(path_1.default.join(contextDir, "approvals.json"), JSON.stringify(approvalsData, null, 2));
        // Update PRD with gap answers
        await this.updatePRDWithAnswers(contextDir, gaps);
        console.log(chalk_1.default.green("   💾 Approvals saved to .mycontext/approvals.json"));
    }
    /**
     * Update PRD with gap answers
     */
    async updatePRDWithAnswers(contextDir, gaps) {
        // PRD is an export of the Living Brain; do not mutate markdown exports.
        // Gaps are saved to approvals.json and should be imported via `--import-exports` on the next brain sync.
        return;
    }
    /**
     * Update a section in PRD content
     */
    updatePRDSection(content, sectionHeader, newContent) {
        const lines = content.split("\n");
        const sectionIndex = lines.findIndex((line) => line.trim() === sectionHeader);
        if (sectionIndex === -1) {
            // Section doesn't exist, add it at the end
            return content + `\n\n${sectionHeader}\n${newContent}`;
        }
        // Find the end of the section (next ## or end of file)
        let endIndex = sectionIndex + 1;
        while (endIndex < lines.length && !lines[endIndex]?.startsWith("##")) {
            endIndex++;
        }
        // Insert the new content before the end of the section
        lines.splice(endIndex, 0, newContent);
        return lines.join("\n");
    }
    /**
     * Get approval status for a feature
     */
    static async getFeatureApproval(featureId) {
        try {
            const approvalsPath = ".mycontext/approvals.json";
            if (!(await fs.pathExists(approvalsPath))) {
                return null;
            }
            const approvalsData = JSON.parse(await fs.readFile(approvalsPath, "utf8"));
            const feature = approvalsData.features[featureId];
            return feature ? feature.approved : null;
        }
        catch (error) {
            return null;
        }
    }
    /**
     * Check if all critical gaps are addressed
     */
    static async areCriticalGapsAddressed() {
        try {
            const autoGeneratedPath = ".mycontext/auto-generated.json";
            const approvalsPath = ".mycontext/approvals.json";
            if (!(await fs.pathExists(autoGeneratedPath)) ||
                !(await fs.pathExists(approvalsPath))) {
                return false;
            }
            const autoGeneratedData = JSON.parse(await fs.readFile(autoGeneratedPath, "utf8"));
            const approvalsData = JSON.parse(await fs.readFile(approvalsPath, "utf8"));
            const criticalGaps = autoGeneratedData.gaps.filter((gap) => gap.category === "critical");
            return criticalGaps.every((gap) => approvalsData.gaps_addressed[gap.id]);
        }
        catch (error) {
            return false;
        }
    }
}
exports.ReviewContextCommand = ReviewContextCommand;
//# sourceMappingURL=review-context.js.map