"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.GenerateScreensListCommand = void 0;
exports.registerGenerateScreensListCommand = registerGenerateScreensListCommand;
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 hybridAIClient_1 = require("../utils/hybridAIClient");
/**
 * Generate Screens List Command
 * Extracts screens from user flows and creates structured list with routes, components, and demo data needs
 */
class GenerateScreensListCommand {
    constructor() {
        this.spinner = new spinner_1.EnhancedSpinner("Loading context files...");
        this.aiClient = new hybridAIClient_1.HybridAIClient();
        this.contextDir = ".mycontext";
    }
    async execute(options = {}) {
        this.spinner.start();
        try {
            // Load existing context files
            const context = await this.loadContext();
            if (!context.userFlows && !context.features && !context.prd) {
                this.spinner.fail("No context files found");
                console.log(chalk_1.default.yellow("\n💡 Generate context first:"));
                console.log(chalk_1.default.cyan("   mycontext generate context --full\n"));
                return;
            }
            this.spinner.updateText("Analyzing user flows for screens...");
            // Build the AI prompt
            const prompt = this.buildScreensPrompt(context);
            this.spinner.updateText("Generating screens list with AI...");
            // Generate with AI
            const response = await this.aiClient.generateText(prompt, {
                maxTokens: 8192,
                temperature: 0.3, // Lower temperature for structured output
            });
            if (!response) {
                throw new Error("AI generation failed");
            }
            // Parse the response
            const screens = this.parseScreensResponse(response.text);
            // Generate markdown output
            const markdown = this.generateMarkdown(screens, context);
            // Write to file
            const outputPath = options.output || path_1.default.join(this.contextDir, "02-screens-list.md");
            await fs.ensureDir(path_1.default.dirname(outputPath));
            await fs.writeFile(outputPath, markdown, "utf-8");
            // Sync with Living Brain (context.json)
            await this.syncWithLivingContext(screens);
            this.spinner.succeed("Screens list generated!");
            console.log(chalk_1.default.green(`\n✅ Generated ${screens.length} screens`));
            console.log(chalk_1.default.gray(`   Saved to: ${outputPath}\n`));
            // Print summary
            console.log(chalk_1.default.bold("📱 Screens Overview:"));
            screens.forEach((screen, idx) => {
                console.log(chalk_1.default.cyan(`   ${idx + 1}. ${screen.name}`));
                console.log(chalk_1.default.gray(`      Route: ${screen.route}`));
                console.log(chalk_1.default.gray(`      Components: ${screen.components.slice(0, 3).join(", ")}${screen.components.length > 3 ? "..." : ""}`));
            });
            console.log(chalk_1.default.yellow("\n💡 Next Steps:"));
            console.log(chalk_1.default.gray("   1. mycontext generate components-manifest"));
            console.log(chalk_1.default.gray("   2. mycontext generate actions"));
        }
        catch (error) {
            this.spinner.fail(`Failed to generate screens list: ${error.message}`);
            logger_1.logger.error("Screens list generation error:", error);
        }
    }
    async loadContext() {
        const context = {};
        const contextDir = this.contextDir;
        // Load PRD
        const prdPath = path_1.default.join(contextDir, fileNames_1.CONTEXT_FILES.PRD);
        if (await fs.pathExists(prdPath)) {
            context.prd = await fs.readFile(prdPath, "utf-8");
        }
        // Load features (01a)
        const featuresPath = path_1.default.join(contextDir, "01a-features.md");
        if (await fs.pathExists(featuresPath)) {
            context.features = await fs.readFile(featuresPath, "utf-8");
        }
        // Load user flows (01b)
        const flowsPath = path_1.default.join(contextDir, "01b-user-flows.md");
        if (await fs.pathExists(flowsPath)) {
            context.userFlows = await fs.readFile(flowsPath, "utf-8");
        }
        // Load edge cases (01c)
        const edgeCasesPath = path_1.default.join(contextDir, "01c-edge-cases.md");
        if (await fs.pathExists(edgeCasesPath)) {
            context.edgeCases = await fs.readFile(edgeCasesPath, "utf-8");
        }
        // Load technical specs (01d)
        const techSpecsPath = path_1.default.join(contextDir, "01d-technical-specs.md");
        if (await fs.pathExists(techSpecsPath)) {
            context.technicalSpecs = await fs.readFile(techSpecsPath, "utf-8");
        }
        // Load types (02-types.ts)
        const typesPath = path_1.default.join(contextDir, "02-types.ts");
        if (await fs.pathExists(typesPath)) {
            context.types = await fs.readFile(typesPath, "utf-8");
        }
        // Load screenshot-derived context
        const screenshotContextPath = path_1.default.join(contextDir, "context.md");
        if (await fs.pathExists(screenshotContextPath)) {
            context.screenshotContext = await fs.readFile(screenshotContextPath, "utf-8");
        }
        return context;
    }
    buildScreensPrompt(context) {
        let prompt = `You are a UI/UX architect. Analyze the following project context and extract ALL screens needed for this application.

For each screen, provide:
1. Name (PascalCase, e.g., "DashboardScreen", "TaskDetailScreen")
2. Route (URL path, e.g., "/dashboard", "/tasks/:id")
3. Brief description (1-2 sentences)
4. Components needed (list of component names)
5. User flow steps that involve this screen
6. Sample data needs (what data this screen displays/edits)

OUTPUT FORMAT (JSON array):
\`\`\`json
[
  {
    "name": "DashboardScreen",
    "route": "/dashboard",
    "description": "Main dashboard showing overview and quick actions",
    "components": ["Header", "MetricCards", "TaskList", "QuickActions"],
    "userFlowSteps": ["User lands here after login", "Can navigate to all main sections"],
    "sampleDataNeeds": ["User stats", "Recent tasks", "Notifications count"]
  }
]
\`\`\`

PROJECT CONTEXT:
`;
        if (context.prd) {
            prompt += `\n## PRD:\n${context.prd.substring(0, 2000)}\n`;
        }
        if (context.features) {
            prompt += `\n## Features:\n${context.features.substring(0, 3000)}\n`;
        }
        if (context.userFlows) {
            prompt += `\n## User Flows:\n${context.userFlows.substring(0, 3000)}\n`;
        }
        if (context.technicalSpecs) {
            prompt += `\n## Technical Specs (API endpoints):\n${context.technicalSpecs.substring(0, 2000)}\n`;
        }
        if (context.screenshotContext) {
            prompt += `\n## Design Reference (from screenshot):\n${context.screenshotContext.substring(0, 1500)}\n`;
        }
        prompt += `
Be comprehensive - include ALL screens including:
- Authentication screens (login, register, forgot password)
- Main navigation screens (dashboard, home)
- CRUD screens for each entity (list, detail, create, edit)
- Settings and profile screens
- Error and empty state screens

Output ONLY the JSON array, no explanation.`;
        return prompt;
    }
    parseScreensResponse(response) {
        try {
            // Extract JSON from response
            const jsonMatch = response.match(/\[[\s\S]*\]/);
            if (!jsonMatch) {
                logger_1.logger.warn("Could not find JSON in response, attempting to parse entire response");
                return [];
            }
            const screens = JSON.parse(jsonMatch[0]);
            return screens.map((s) => ({
                name: s.name || "UnnamedScreen",
                route: s.route || "/",
                description: s.description || "",
                components: s.components || [],
                userFlowSteps: s.userFlowSteps || [],
                sampleDataNeeds: s.sampleDataNeeds || [],
                designNotes: s.designNotes,
            }));
        }
        catch (error) {
            logger_1.logger.error("Failed to parse screens response:", error);
            return [];
        }
    }
    generateMarkdown(screens, context) {
        let md = `# Screens List

> Auto-generated from project context. ${screens.length} screens identified.

## Overview

| # | Screen | Route | Components |
|---|--------|-------|------------|
`;
        screens.forEach((screen, idx) => {
            md += `| ${idx + 1} | ${screen.name} | \`${screen.route}\` | ${screen.components.length} |\n`;
        });
        md += `\n---\n\n## Screen Details\n\n`;
        screens.forEach((screen, idx) => {
            md += `### ${idx + 1}. ${screen.name}\n\n`;
            md += `**Route**: \`${screen.route}\`\n\n`;
            md += `**Description**: ${screen.description}\n\n`;
            md += `**Components**:\n`;
            screen.components.forEach(comp => {
                md += `- ${comp}\n`;
            });
            md += `\n**User Flow Steps**:\n`;
            screen.userFlowSteps.forEach(step => {
                md += `- ${step}\n`;
            });
            md += `\n**Sample Data Needs**:\n`;
            screen.sampleDataNeeds.forEach(data => {
                md += `- ${data}\n`;
            });
            if (screen.designNotes) {
                md += `\n**Design Notes**: ${screen.designNotes}\n`;
            }
            md += `\n---\n\n`;
        });
        md += `\n---
*Generated by MyContext CLI*
*Last updated: ${new Date().toISOString()}*
`;
        return md;
    }
    async asyncLoadLivingContext() {
        const contextPath = path_1.default.join(this.contextDir, "context.json");
        if (await fs.pathExists(contextPath)) {
            return await fs.readJson(contextPath);
        }
        return null;
    }
    async syncWithLivingContext(screens) {
        try {
            const livingContext = await this.asyncLoadLivingContext();
            if (!livingContext)
                return;
            // Map screens to RouteDefinitions
            const routes = screens.map(screen => ({
                path: screen.route,
                type: "page",
                components: screen.components,
                actions: [],
                metadata: {
                    title: screen.name,
                    description: screen.description
                }
            }));
            // Update the routes in living context
            livingContext.routes = routes;
            livingContext.metadata.lastUpdatedAt = new Date().toISOString();
            const contextPath = path_1.default.join(this.contextDir, "context.json");
            await fs.writeJson(contextPath, livingContext, { spaces: 2 });
            logger_1.logger.info(`Synced ${screens.length} routes to context.json`);
        }
        catch (error) {
            logger_1.logger.error("Failed to sync screens with living context:", error);
        }
    }
}
exports.GenerateScreensListCommand = GenerateScreensListCommand;
// Register the command
function registerGenerateScreensListCommand(program) {
    program
        .command("generate:screens-list")
        .alias("gsl")
        .description("Generate a structured list of screens from user flows and context")
        .option("-o, --output <path>", "Output file path", ".mycontext/02-screens-list.md")
        .option("-v, --verbose", "Enable verbose logging")
        .option("-f, --format <format>", "Output format (markdown|json)", "markdown")
        .action(async (options) => {
        const command = new GenerateScreensListCommand();
        await command.execute(options);
    });
}
//# sourceMappingURL=generate-screens-list.js.map