"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AnalyzeScreenshotCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const gemini_vision_1 = require("../services/gemini-vision");
class AnalyzeScreenshotCommand {
    constructor(program) {
        this.program = program;
    }
    register() {
        this.program
            .command("analyze:ui <imagePath>")
            .description("Analyze a screenshot and generate context using Gemini Vision")
            .option("-o, --output <path>", "Output file path", ".mycontext/context.md")
            .option("--project-name <name>", "Project name", "My Project")
            .option("--json", "Output raw JSON analysis")
            .action(async (imagePath, options) => {
            await this.execute(imagePath, options);
        });
    }
    async execute(imagePath, options) {
        try {
            // Validate image exists
            if (!fs_1.default.existsSync(imagePath)) {
                console.log(chalk_1.default.red(`❌ Image not found: ${imagePath}`));
                process.exit(1);
            }
            console.log(chalk_1.default.blue("\n🔍 Analyzing screenshot with Gemini Vision...\n"));
            const spinner = (0, ora_1.default)("Connecting to Gemini API...").start();
            // Initialize Gemini service
            const geminiService = new gemini_vision_1.GeminiVisionService();
            spinner.text = "Analyzing UI components...";
            const analysis = await geminiService.analyzeScreenshot(imagePath);
            spinner.succeed("Analysis complete!");
            // Output results
            if (options.json) {
                console.log(JSON.stringify(analysis, null, 2));
                return;
            }
            // Display summary
            console.log(chalk_1.default.green("\n╔══════════════════════════════════════╗"));
            console.log(chalk_1.default.green("║  Analysis Complete                   ║"));
            console.log(chalk_1.default.green("╚══════════════════════════════════════╝\n"));
            console.log(chalk_1.default.cyan("📦 Detected Components:"));
            analysis.components.slice(0, 5).forEach((comp) => {
                console.log(chalk_1.default.white(`  • ${comp.name}`) + chalk_1.default.gray(` (${comp.type})`));
            });
            if (analysis.components.length > 5) {
                console.log(chalk_1.default.gray(`  ... and ${analysis.components.length - 5} more`));
            }
            console.log(chalk_1.default.cyan("\n🎨 Design System:"));
            if (analysis.designSystem.colors.primary) {
                console.log(chalk_1.default.white(`  • Primary: ${analysis.designSystem.colors.primary}`));
            }
            if (analysis.designSystem.spacing.baseUnit) {
                console.log(chalk_1.default.white(`  • Base Unit: ${analysis.designSystem.spacing.baseUnit}`));
            }
            console.log(chalk_1.default.cyan("\n📐 Layout:"));
            console.log(chalk_1.default.white(`  • Type: ${analysis.layout.type}`));
            console.log(chalk_1.default.white(`  • ${analysis.layout.structure}`));
            console.log(chalk_1.default.cyan("\n💻 Recommended Tech Stack:"));
            analysis.techStack.suggested.forEach((tech) => {
                console.log(chalk_1.default.white(`  • ${tech}`));
            });
            // Generate context file
            const spinner2 = (0, ora_1.default)("Generating context file...").start();
            const contextContent = geminiService.generateContextFromAnalysis(analysis, options.projectName);
            // Ensure directory exists
            const outputDir = path_1.default.dirname(options.output);
            if (!fs_1.default.existsSync(outputDir)) {
                fs_1.default.mkdirSync(outputDir, { recursive: true });
            }
            fs_1.default.writeFileSync(options.output, contextContent, "utf-8");
            spinner2.succeed(`Context saved to ${options.output}`);
            console.log(chalk_1.default.green("\n╔══════════════════════════════════════╗"));
            console.log(chalk_1.default.green("║  🎉 Ready to Code!                   ║"));
            console.log(chalk_1.default.green("╚══════════════════════════════════════╝\n"));
            console.log(chalk_1.default.white("Next steps:"));
            console.log(chalk_1.default.gray("  1. ") + chalk_1.default.white(`cat ${options.output}`) + chalk_1.default.gray(" # Review context"));
            console.log(chalk_1.default.gray("  2. ") + chalk_1.default.white("mycontext generate:screens") + chalk_1.default.gray(" # Generate screens"));
            console.log(chalk_1.default.gray("  3. Preview at ") + chalk_1.default.cyan("https://studio.mycontext.app") + chalk_1.default.gray("\n"));
        }
        catch (error) {
            console.log(chalk_1.default.red(`\n❌ Error: ${error instanceof Error ? error.message : "Unknown error"}`));
            if (error instanceof Error && error.message.includes("API key")) {
                console.log(chalk_1.default.yellow("\n💡 Tip: Set your Gemini API key:"));
                console.log(chalk_1.default.gray("   export GEMINI_API_KEY=your_key_here"));
                console.log(chalk_1.default.gray("   Or add it to your .env file\n"));
            }
            process.exit(1);
        }
    }
}
exports.AnalyzeScreenshotCommand = AnalyzeScreenshotCommand;
//# sourceMappingURL=analyze-screenshot.js.map