"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.GenerateAssetsCommand = void 0;
exports.registerGenerateAssetsCommand = registerGenerateAssetsCommand;
const chalk_1 = __importDefault(require("chalk"));
const fs = __importStar(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const AICore_1 = require("../core/ai/AICore");
const spinner_1 = require("../utils/spinner");
const logger_1 = require("../utils/logger");
const BrainClient_1 = require("../core/brain/BrainClient");
class GenerateAssetsCommand {
    constructor() {
        this.spinner = new spinner_1.EnhancedSpinner("Preparing asset generation...");
        this.brain = BrainClient_1.BrainClient.getInstance();
    }
    async execute(options) {
        const projectPath = process.cwd();
        const contextDir = path_1.default.join(projectPath, ".mycontext");
        const manifestPath = path_1.default.join(contextDir, "images-manifest.json");
        const assetsDir = options.output ? path_1.default.resolve(projectPath, options.output) : path_1.default.join(projectPath, "public", "assets", "images");
        this.spinner.start();
        if (!fs.existsSync(manifestPath)) {
            this.spinner.fail("No images-manifest.json found");
            console.log(chalk_1.default.red("\n❌ Run 'mycontext ideate' first to generate a visual asset plan."));
            return;
        }
        try {
            const manifest = await fs.readJson(manifestPath);
            let assets = [];
            if (Array.isArray(manifest)) {
                assets = manifest;
            }
            else if (manifest.visualAssets && Array.isArray(manifest.visualAssets)) {
                assets = manifest.visualAssets;
            }
            else if (manifest.assets && Array.isArray(manifest.assets)) {
                assets = manifest.assets;
            }
            if (assets.length === 0) {
                this.spinner.fail("Invalid manifest format or no assets found");
                return;
            }
            await fs.ensureDir(assetsDir);
            const ai = AICore_1.AICore.getInstance({
                workingDirectory: projectPath,
                fallbackEnabled: true
            });
            console.log(chalk_1.default.blue(`\n🎨 Generating assets in ${assetsDir}...\n`));
            for (const asset of assets) {
                console.log(chalk_1.default.gray(`   [PLAN] ${asset.id} (${asset.type}): ${asset.description}`));
                const assetPath = path_1.default.join(assetsDir, `${asset.id}.png`);
                // Check if asset already exists
                if (fs.existsSync(assetPath)) {
                    console.log(chalk_1.default.yellow(`   ⏩ Asset ${asset.id} already exists, skipping.`));
                    await this.brain.addUpdate("AssetGenerator", "builder", "action", `Skipped existing visual asset: ${asset.id}`, { id: asset.id, type: asset.type, path: assetPath });
                    continue;
                }
                // Active generation
                this.spinner.updateText(`Generating ${asset.id}...`);
                console.log(chalk_1.default.blue(`   🤖 Requesting AI Generation for ${asset.id}...`));
                try {
                    await ai.generateImage(asset.description, assetPath);
                    console.log(chalk_1.default.green(`   ✅ Asset ${asset.id} generated successfully.`));
                    await this.brain.addUpdate("AssetGenerator", "builder", "action", `Generated visual asset: ${asset.id}`, { id: asset.id, type: asset.type, path: assetPath });
                }
                catch (err) {
                    console.log(chalk_1.default.red(`   ❌ Failed to generate ${asset.id}: ${err.message}`));
                    // For agentic guidance, we still log the failure for Brain visibility
                    await this.brain.addUpdate("AssetGenerator", "builder", "error", `Failed to generate visual asset: ${asset.id}`, { id: asset.id, error: err.message });
                }
            }
            console.log(chalk_1.default.green(`\n✅ Asset generation pass complete.`));
            console.log(chalk_1.default.gray(`   Run 'mycontext generate:screens' to use these assets.\n`));
        }
        catch (error) {
            this.spinner.fail("Asset generation failed");
            logger_1.logger.error("Asset generation error:", error.message);
            throw error;
        }
    }
}
exports.GenerateAssetsCommand = GenerateAssetsCommand;
function registerGenerateAssetsCommand(program) {
    program
        .command("generate:assets")
        .alias("gas")
        .description("Generate visual assets planned in images-manifest.json")
        .option("-o, --output <path>", "Output directory for assets (default: public/assets/images)")
        .action(async (options) => {
        const command = new GenerateAssetsCommand();
        await command.execute(options);
    });
}
//# sourceMappingURL=generate-assets.js.map