"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.IdeateCommand = void 0;
exports.registerIdeateCommand = registerIdeateCommand;
const chalk_1 = __importDefault(require("chalk"));
const fs = __importStar(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const spinner_1 = require("../utils/spinner");
const hybridAIClient_1 = require("../utils/hybridAIClient");
const logger_1 = require("../utils/logger");
const BrainClient_1 = require("../core/brain/BrainClient");
class IdeateCommand {
    constructor() {
        this.spinner = new spinner_1.EnhancedSpinner("Dreaming up UI concepts...");
        this.ai = new hybridAIClient_1.HybridAIClient();
        this.brain = BrainClient_1.BrainClient.getInstance();
    }
    async execute(options) {
        const projectPath = process.cwd();
        const contextDir = path_1.default.join(projectPath, ".mycontext");
        const ideasDir = options.output ? path_1.default.resolve(projectPath, options.output) : path_1.default.join(contextDir, "ideas");
        this.spinner.start();
        if (!fs.existsSync(contextDir)) {
            this.spinner.fail("No .mycontext directory found");
            console.log(chalk_1.default.red("\n❌ Run 'mycontext init' first to establish project context."));
            return;
        }
        try {
            await fs.ensureDir(ideasDir);
            // 1. Load context
            const contextPath = path_1.default.join(contextDir, "context.json");
            let projectContext = {};
            if (fs.existsSync(contextPath)) {
                projectContext = await fs.readJson(contextPath);
            }
            const industry = options.industry || projectContext?.prd?.title || "SaaS Application";
            const count = options.count || 3;
            this.spinner.updateText(`Generating ${count} creative concepts and visual asset plan for ${industry}...`);
            await this.brain.addUpdate("Ideator", "planner", "thought", `Exploring ${count} UI concepts and ${industry} visual assets.`);
            // 2. Build Ideation Prompt
            const ideationPrompt = `
        You are a World-Class UI/UX Creative Director and Visual Specialist. 
        Generate ${count} distinct, high-fidelity UI/UX concepts for a project in the "${industry}" industry.
        
        Context: ${JSON.stringify(projectContext)}
        
        For each concept, provide:
        1. **Concept Name**: A bold, catchy name.
        2. **Visual Direction**: Color palette, typography, and "vibe" (e.g., Glassmorphism, Brutalism, Cyberpunk, Apple-esque).
        3. **Key Layout Innovations**: Unique ways to present information relevant to this industry.
        4. **User Experience Hook**: A specific interaction or flow that makes this stand out.

        ## VISUAL ASSETS PLAN
        Identify exactly 8 high-impact visual assets required for a premier landing page and dashboard for this project.
        For each asset, provide:
        - "id": kebab-case name (e.g., hero-background, feature-analytics-icon)
        - "type": (e.g., hero-image, icon, avatar, product-shot)
        - "description": detailed visual prompt for an image generator
        
        Format the response in two parts:
        Part 1: The Markdown Report.
        Part 2: A JSON block at the end with the VISUAL ASSETS PLAN data.
      `;
            const response = await this.ai.generateText(ideationPrompt);
            // Extract Markdown and JSON
            const jsonMatch = response.text.match(/```json\n([\s\S]*?)\n```/);
            const manifestData = (jsonMatch && jsonMatch[1]) ? JSON.parse(jsonMatch[1]) : null;
            const markdownReport = response.text.replace(/```json\n[\s\S]*?\n```/, "").trim();
            const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
            const reportName = `ideation-report-${timestamp}.md`;
            const reportPath = path_1.default.join(ideasDir, reportName);
            await fs.writeFile(reportPath, markdownReport, "utf8");
            if (manifestData) {
                const manifestPath = path_1.default.join(contextDir, "images-manifest.json");
                await fs.writeJson(manifestPath, manifestData, { spaces: 2 });
                await this.brain.addUpdate("Ideator", "planner", "action", `Generated visual asset manifest with ${manifestData.visualAssets?.length || 0} planned assets.`);
                console.log(chalk_1.default.gray(`   ✅ Visual Asset Manifest saved to ${manifestPath}`));
            }
            // Sync with Brain narrative
            const conceptNames = response.text.match(/\*\*Concept Name\*\*:\s*([^\n]+)/g) || [];
            if (conceptNames.length > 0) {
                const narrative = `Focusing on UI concepts: ${conceptNames.map(n => n.replace(/\*\*Concept Name\*\*:\s*/, "").trim()).join(", ")}.`;
                await this.brain.setNarrative(narrative);
            }
            this.spinner.succeed(`Generated ${count} concepts!`);
            console.log(chalk_1.default.green(`\n🎨 Ideation Report saved to: ${reportPath}\n`));
            console.log(chalk_1.default.blue("Next steps:"));
            console.log(chalk_1.default.gray(`  1. Review the ideas in ${reportPath}`));
            console.log(chalk_1.default.gray(`  2. Run 'mycontext generate:assets' to create real AI images.`));
            console.log(chalk_1.default.gray(`  3. Use 'mycontext generate:screens' to visualize your favorite concept.`));
            console.log(chalk_1.default.gray(`  4. Run 'mycontext analyze' if you have a reference image matching a concept.\n`));
        }
        catch (error) {
            this.spinner.fail("Ideation failed");
            logger_1.logger.error("Ideation error:", error.message);
            throw error;
        }
    }
}
exports.IdeateCommand = IdeateCommand;
function registerIdeateCommand(program) {
    program
        .command("ideate")
        .description("Generate creative UI/UX concepts based on project context")
        .option("-i, --industry <name>", "Specific industry for ideation")
        .option("-c, --count <number>", "Number of concepts to generate", "3")
        .option("-o, --output <path>", "Output directory for ideas")
        .action(async (options) => {
        const command = new IdeateCommand();
        await command.execute({
            industry: options.industry,
            count: parseInt(options.count),
            output: options.output
        });
    });
}
//# sourceMappingURL=ideate.js.map