"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.GenerateDesignPromptCommand = void 0;
exports.registerGenerateDesignPromptCommand = registerGenerateDesignPromptCommand;
const chalk_1 = __importDefault(require("chalk"));
const fs = __importStar(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const fileNames_1 = require("../constants/fileNames");
const spinner_1 = require("../utils/spinner");
const logger_1 = require("../utils/logger");
const contextRenderer_1 = require("../utils/contextRenderer");
class GenerateDesignPromptCommand {
    constructor() {
        this.spinner = new spinner_1.EnhancedSpinner("Generating design prompt...");
    }
    ensureCanonicalPrd(contextDir) {
        const canonicalPrdPath = path_1.default.join(contextDir, fileNames_1.CONTEXT_FILES.PRD);
        if (fs.existsSync(canonicalPrdPath))
            return;
        const legacyCandidates = [
            "02-prd.md",
            "prd.md",
            "PRD.md",
            "01_PRD.md",
        ];
        for (const legacyFile of legacyCandidates) {
            const legacyPath = path_1.default.join(contextDir, legacyFile);
            if (!fs.existsSync(legacyPath))
                continue;
            try {
                const content = fs.readFileSync(legacyPath, "utf8");
                if (!content.trim())
                    continue;
                fs.copySync(legacyPath, canonicalPrdPath);
                return;
            }
            catch {
                // Silent best-effort repair
            }
        }
    }
    loadLivingBrain(contextDir) {
        const brainPath = path_1.default.join(contextDir, "context.json");
        if (!fs.existsSync(brainPath))
            return null;
        try {
            return fs.readJsonSync(brainPath);
        }
        catch {
            return null;
        }
    }
    buildContextFromBrain(brain) {
        // Map gdp sections to ContextRenderer exports
        return {
            prd: this.cleanContent(contextRenderer_1.ContextRenderer.renderPRD(brain)),
            features: this.cleanContent(contextRenderer_1.ContextRenderer.renderFeatures(brain)),
            userFlows: this.cleanContent(contextRenderer_1.ContextRenderer.renderUserFlows(brain)),
            edgeCases: this.cleanContent(contextRenderer_1.ContextRenderer.renderEdgeCases(brain)),
            technicalSpecs: this.cleanContent(contextRenderer_1.ContextRenderer.renderTechnicalSpecs(brain)),
            branding: this.cleanContent(contextRenderer_1.ContextRenderer.renderBrandGuide(brain)),
            // projectStructure intentionally omitted here (separate artifact, if present)
        };
    }
    async execute(options) {
        const projectPath = process.cwd();
        const contextDir = path_1.default.join(projectPath, ".mycontext");
        this.spinner.start();
        // Check if .mycontext directory exists
        if (!fs.existsSync(contextDir)) {
            this.spinner.fail("No .mycontext directory found");
            console.log(chalk_1.default.red("\n❌ No .mycontext directory found. Run 'mycontext generate context' first."));
            return;
        }
        // Silent auto-repair: ensure canonical PRD name exists
        this.ensureCanonicalPrd(contextDir);
        const brain = this.loadLivingBrain(contextDir);
        // Load context: brain-first, then markdown files
        const context = brain
            ? { ...this.buildContextFromBrain(brain), ...(await this.loadContextFiles(contextDir)) }
            : await this.loadContextFiles(contextDir);
        // Safety Check: Ensure sufficient context (PRD is required)
        if (!context.prd || context.prd.length < 100) {
            this.spinner.fail("Insufficient context for design prompt");
            console.log(chalk_1.default.red("\n❌ Insufficient project context found. Please run 'mycontext generate context --full' first to populate your PRD and features."));
            return;
        }
        // Generate the design prompt
        const prompt = this.generateDesignPrompt(context, options.format || "general");
        // Determine output path
        const outputPath = options.output
            ? path_1.default.resolve(options.output)
            : path_1.default.join(contextDir, "design-prompt.txt");
        // Write the prompt
        await fs.writeFile(outputPath, prompt, "utf8");
        this.spinner.succeed("Design prompt generated");
        console.log(chalk_1.default.green(`\n✅ Design prompt saved to: ${outputPath}`));
        console.log(chalk_1.default.blue("\n💡 Next Step: Copy this prompt and paste it into your AI design tool (Stitch, etc.)"));
        console.log(chalk_1.default.gray(`\n📋 Prompt length: ${prompt.length} characters (${Math.ceil(prompt.length / 1000)}k)`));
        // Also output to console if requested
        if (options.format === "api") {
            console.log(chalk_1.default.yellow("\n📡 API JSON format:"));
            console.log(JSON.stringify({
                prompt,
                metadata: {
                    generatedAt: new Date().toISOString(),
                    format: options.format,
                    contextFiles: Object.keys(context).filter((key) => context[key]),
                },
            }, null, 2));
        }
    }
    async loadContextFiles(contextDir) {
        const context = {};
        const files = [
            { key: "prd", file: fileNames_1.CONTEXT_FILES.PRD },
            { key: "features", file: fileNames_1.CONTEXT_FILES.FEATURES },
            { key: "userFlows", file: fileNames_1.CONTEXT_FILES.USER_FLOWS },
            { key: "edgeCases", file: fileNames_1.CONTEXT_FILES.EDGE_CASES },
            { key: "technicalSpecs", file: fileNames_1.CONTEXT_FILES.TECHNICAL_SPECS },
            { key: "branding", file: fileNames_1.CONTEXT_FILES.BRANDING },
            { key: "projectStructure", file: fileNames_1.CONTEXT_FILES.PROJECT_STRUCTURE },
        ];
        for (const { key, file } of files) {
            const filePath = path_1.default.join(contextDir, file);
            if (fs.existsSync(filePath)) {
                try {
                    const content = fs.readFileSync(filePath, "utf8");
                    // Clean up markdown headers and metadata for cleaner prompt
                    const cleaned = this.cleanContent(content);
                    if (cleaned.trim()) {
                        context[key] = cleaned;
                    }
                }
                catch (error) {
                    logger_1.logger.warn(`Could not load ${file}`);
                }
            }
        }
        // Load component list if exists
        const componentListPath = path_1.default.join(contextDir, fileNames_1.CONTEXT_FILES.COMPONENT_LIST);
        if (fs.existsSync(componentListPath)) {
            try {
                const componentList = JSON.parse(fs.readFileSync(componentListPath, "utf8"));
                context.componentList = JSON.stringify(componentList, null, 2);
            }
            catch (error) {
                logger_1.logger.warn("Could not load component list");
            }
        }
        return context;
    }
    cleanContent(content) {
        // Remove metadata footers
        return content
            .replace(/---\s*\n[\s\S]*?Generated by:.*?\n[\s\S]*?---/g, "")
            .replace(/\*\*Generated\*\*:.*?\n/g, "")
            .replace(/\*\*Source Context Files\*\*:.*?\n/g, "")
            .replace(/## Document Information[\s\S]*?$/g, "")
            .replace(/## Context File References[\s\S]*?$/g, "")
            .trim();
    }
    generateDesignPrompt(context, format) {
        const sections = [];
        // Header
        sections.push("# App Design Context");
        sections.push("This document contains all the context needed to design beautiful, production-ready UI screens for this application.");
        sections.push("");
        // PRD Section (most important)
        if (context.prd) {
            sections.push("## Product Requirements Document (PRD)");
            sections.push(context.prd);
            sections.push("");
        }
        // Features Section
        if (context.features) {
            sections.push("## Features & User Actions");
            sections.push(context.features);
            sections.push("");
        }
        // User Flows Section
        if (context.userFlows) {
            sections.push("## User Flows");
            sections.push(context.userFlows);
            sections.push("");
        }
        // Branding Section (critical for design)
        if (context.branding) {
            sections.push("## Brand Guidelines & Design System");
            sections.push(context.branding);
            sections.push("");
        }
        // Technical Specs (for understanding constraints)
        if (context.technicalSpecs) {
            sections.push("## Technical Specifications");
            sections.push(context.technicalSpecs);
            sections.push("");
        }
        // Edge Cases (for comprehensive design)
        if (context.edgeCases) {
            sections.push("## Edge Cases & Error States");
            sections.push(context.edgeCases);
            sections.push("");
        }
        // Component List (if exists)
        if (context.componentList) {
            sections.push("## Required Components");
            sections.push("The following components should be included in the design:");
            sections.push("```json");
            sections.push(context.componentList);
            sections.push("```");
            sections.push("");
        }
        // Project Structure (for context)
        if (context.projectStructure) {
            sections.push("## Project Structure");
            sections.push(context.projectStructure);
            sections.push("");
        }
        // Format-specific instructions
        if (format === "stitch") {
            sections.push("---");
            sections.push("");
            sections.push("## Design Instructions for Stitch");
            sections.push("");
            sections.push("Please create beautiful, modern UI designs for this application based on the context above.");
            sections.push("");
            sections.push("Design Requirements:");
            sections.push("- Follow the brand guidelines and design system specified above");
            sections.push("- Create designs for all user flows and features mentioned");
            sections.push("- Include all required components from the component list");
            sections.push("- Consider edge cases and error states in your designs");
            sections.push("- Ensure designs are mobile-first and responsive");
            sections.push("- Use modern UI/UX best practices and accessibility standards");
        }
        else if (format === "general") {
            sections.push("---");
            sections.push("");
            sections.push("Use this context to design beautiful UI screens for this application.");
            sections.push("Focus on the user flows, features, and brand guidelines provided above.");
        }
        return sections.join("\n");
    }
}
exports.GenerateDesignPromptCommand = GenerateDesignPromptCommand;
function registerGenerateDesignPromptCommand(program) {
    program
        .command("generate:design-prompt")
        .alias("gdp")
        .description("Generate a design prompt optimized for AI design tools (Stitch, etc.)")
        .option("-o, --output <path>", "Output file path (default: .mycontext/design-prompt.txt)")
        .option("-f, --format <format>", "Output format: stitch, general, or api (default: general)")
        .action(async (options) => {
        const command = new GenerateDesignPromptCommand();
        await command.execute(options);
    });
}
//# sourceMappingURL=generate-design-prompt.js.map