"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.ContextLoader = void 0;
exports.loadProjectContext = loadProjectContext;
exports.getDescriptionFromContext = getDescriptionFromContext;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const fileNames_1 = require("../constants/fileNames");
/**
 * Loads project context from .mycontext directory
 * Provides fallback to context/ directory for backward compatibility
 */
class ContextLoader {
    constructor(projectPath = process.cwd()) {
        this.projectPath = projectPath;
    }
    /**
     * Load all available context files
     */
    async loadProjectContext(options = {}) {
        const context = {};
        const { verbose = false, required = false } = options;
        try {
            // Try .mycontext directory first (new structure)
            const mycontextDir = path.join(this.projectPath, ".mycontext");
            if (await fs.pathExists(mycontextDir)) {
                await this.loadFromDirectory(mycontextDir, context, verbose);
            }
            else if (required) {
                throw new Error("No .mycontext directory found. Run 'mycontext init' first.");
            }
            else {
                // Fallback to context/ directory (legacy structure)
                const contextDir = path.join(this.projectPath, "context");
                if (await fs.pathExists(contextDir)) {
                    if (verbose) {
                        console.log(chalk_1.default.gray("📁 Using legacy context/ directory"));
                    }
                    await this.loadFromDirectory(contextDir, context, verbose);
                }
            }
            if (verbose && Object.keys(context).length > 0) {
                console.log(chalk_1.default.green("✅ Context loaded successfully"));
                console.log(chalk_1.default.gray(`   Available: ${Object.keys(context).join(", ")}`));
            }
            return context;
        }
        catch (error) {
            if (required) {
                throw error;
            }
            if (verbose) {
                console.log(chalk_1.default.yellow("⚠️ Some context files could not be loaded"));
            }
            return context;
        }
    }
    /**
     * Load context from a specific directory
     */
    async loadFromDirectory(dir, context, verbose) {
        // Helper function to load a file with variants
        const loadFileWithVariants = async (canonicalName, contextKey, displayName) => {
            const variants = (0, fileNames_1.getAllFileNameVariants)(canonicalName);
            for (const variant of variants) {
                const filePath = path.join(dir, variant);
                if (await fs.pathExists(filePath)) {
                    const content = await fs.readFile(filePath, "utf8");
                    context[contextKey] = content;
                    if (verbose) {
                        console.log(chalk_1.default.gray(`   📄 ${displayName}: ${variant}`));
                    }
                    break;
                }
            }
        };
        // Load PRD
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.PRD, "prd", "PRD");
        // Load Types
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.TYPES, "types", "Types");
        // Load Brand
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.BRANDING, "brand", "Brand");
        // Load Component List (JSON)
        const compListVariants = (0, fileNames_1.getAllFileNameVariants)(fileNames_1.CONTEXT_FILES.COMPONENT_LIST);
        for (const variant of compListVariants) {
            const compListPath = path.join(dir, variant);
            if (await fs.pathExists(compListPath)) {
                try {
                    const compListRaw = await fs.readFile(compListPath, "utf8");
                    context.componentList = JSON.parse(compListRaw);
                    if (verbose) {
                        console.log(chalk_1.default.gray(`   📄 Component List: ${variant}`));
                    }
                    break;
                }
                catch (error) {
                    // Invalid JSON, try next variant
                    continue;
                }
            }
        }
        // Load A/B/C/D Context Files
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.FEATURES, "features", "Features");
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.USER_FLOWS, "userFlows", "User Flows");
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.EDGE_CASES, "edgeCases", "Edge Cases");
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.TECHNICAL_SPECS, "technicalSpecs", "Technical Specs");
        // Load Project Structure
        await loadFileWithVariants(fileNames_1.CONTEXT_FILES.PROJECT_STRUCTURE, "projectStructure", "Project Structure");
    }
    /**
     * Get a description from context files, with fallback priority
     */
    async getDescriptionFromContext(options = {}) {
        const context = await this.loadProjectContext(options);
        // Priority order: PRD > Types > User Stories > Technical Specs
        if (context.prd && context.prd.trim()) {
            return context.prd.trim();
        }
        if (context.types && context.types.trim()) {
            return context.types.trim();
        }
        if (context.userStories && context.userStories.trim()) {
            return context.userStories.trim();
        }
        if (context.technicalSpecs && context.technicalSpecs.trim()) {
            return context.technicalSpecs.trim();
        }
        return null;
    }
    /**
     * Check if context files exist
     */
    async hasContextFiles() {
        const context = await this.loadProjectContext();
        return Object.keys(context).length > 0;
    }
    /**
     * Get context summary for display
     */
    getContextSummary(context) {
        const parts = [];
        if (context.prd)
            parts.push("PRD");
        if (context.types)
            parts.push("Types");
        if (context.brand)
            parts.push("Brand");
        if (context.componentList)
            parts.push("Components");
        if (context.userStories)
            parts.push("User Stories");
        if (context.technicalSpecs)
            parts.push("Technical Specs");
        if (context.projectStructure)
            parts.push("Project Structure");
        return parts.length > 0 ? parts.join(", ") : "No context found";
    }
}
exports.ContextLoader = ContextLoader;
/**
 * Convenience function to load project context
 */
async function loadProjectContext(projectPath, options) {
    const loader = new ContextLoader(projectPath);
    return loader.loadProjectContext(options);
}
/**
 * Convenience function to get description from context
 */
async function getDescriptionFromContext(projectPath, options) {
    const loader = new ContextLoader(projectPath);
    return loader.getDescriptionFromContext(options);
}
//# sourceMappingURL=contextLoader.js.map