"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.AddCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const fileSystem_1 = require("../utils/fileSystem");
const spinner_1 = require("../utils/spinner");
const CodeGenSubAgent_1 = require("../agents/implementations/CodeGenSubAgent");
const AICore_1 = require("../core/ai/AICore");
const child_process_1 = require("child_process");
const path = __importStar(require("path"));
const fs = __importStar(require("fs-extra"));
class AddCommand {
    constructor() {
        this.fs = new fileSystem_1.FileSystemManager();
        this.spinner = new spinner_1.EnhancedSpinner("Adding component...");
    }
    async execute(componentName, options) {
        const { group = "elements", shadcn = false } = options;
        console.log(chalk_1.default.blue.bold(`🚀 Adding component: ${chalk_1.default.white(componentName)}\n`));
        try {
            this.spinner.start();
            // 1. Detect if it's a shadcn primitive
            const isShadcnPrimitive = await this.isShadcnPrimitive(componentName);
            if (isShadcnPrimitive || shadcn) {
                this.spinner.updateText(`Installing shadcn primitive: ${componentName}...`);
                await this.installShadcnComponent(componentName);
                this.spinner.succeed(`Shadcn component ${componentName} installed.`);
                this.spinner.start().updateText(`Contextualizing ${componentName}...`);
            }
            // 2. Generate/Contextualize the component
            const codeGen = new CodeGenSubAgent_1.CodeGenSubAgent();
            const aiCore = AICore_1.AICore.getInstance();
            const livingContext = await aiCore.getLivingContext();
            if (!livingContext) {
                throw new Error("Living Brain (context.json) not found. Run 'mycontext init' first.");
            }
            const result = await codeGen.run({
                component: {
                    name: componentName,
                    description: `A ${componentName} component for the ${livingContext.prd.title} project.`,
                    type: "interactive",
                    dependencies: isShadcnPrimitive ? [componentName] : [],
                    tags: ["added-via-cli"]
                },
                group: group,
                context: livingContext,
                options: {
                    projectPath: process.cwd()
                }
            });
            // 3. Write the file
            const componentsDir = path.join(process.cwd(), "src", "components", group);
            await fs.ensureDir(componentsDir);
            const filePath = path.join(componentsDir, `${this.toPascalCase(componentName)}.tsx`);
            await fs.writeFile(filePath, result.code);
            // 4. Update Registry (Brain)
            await this.updateRegistry(componentName, group, filePath);
            this.spinner.succeed(`Component ${chalk_1.default.white(componentName)} added and contextualized!`);
            console.log(chalk_1.default.gray(`\nLocation: ${filePath}`));
        }
        catch (error) {
            this.spinner.fail("Failed to add component");
            throw error;
        }
    }
    async isShadcnPrimitive(name) {
        // Basic list of common shadcn primitives. In a real app, we might fetch this from the shadcn registry.
        const primitives = [
            "accordion", "alert", "alert-dialog", "aspect-ratio", "avatar", "badge", "button",
            "calendar", "card", "carousel", "checkbox", "collapsible", "combobox", "command",
            "context-menu", "dialog", "drawer", "dropdown-menu", "form", "hover-card", "input",
            "label", "menubar", "navigation-menu", "pagination", "popover", "progress",
            "radio-group", "resizable", "scroll-area", "select", "separator", "sheet",
            "skeleton", "slider", "switch", "table", "tabs", "textarea", "toast", "toggle",
            "tooltip"
        ];
        return primitives.includes(name.toLowerCase());
    }
    async installShadcnComponent(name) {
        try {
            const packageManager = this.detectPackageManager();
            const cmd = `${packageManager === 'npm' ? 'npx' : packageManager} shadcn@latest add ${name} --yes`;
            (0, child_process_1.execSync)(cmd, { stdio: "ignore" });
        }
        catch (error) {
            console.warn(chalk_1.default.yellow(`\n⚠️  Could not install shadcn component via CLI. Ensure shadcn is initialized.`));
        }
    }
    detectPackageManager() {
        if (fs.existsSync(path.join(process.cwd(), "pnpm-lock.yaml")))
            return "pnpm";
        if (fs.existsSync(path.join(process.cwd(), "yarn.lock")))
            return "yarn";
        return "npm";
    }
    toPascalCase(str) {
        return str
            .replace(/[-_]+/g, " ")
            .split(" ")
            .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
            .join("");
    }
    async updateRegistry(name, group, filePath) {
        const contextPath = path.join(process.cwd(), ".mycontext", "context.json");
        if (!(await fs.pathExists(contextPath)))
            return;
        const context = await fs.readJson(contextPath);
        if (!context.components)
            context.components = [];
        const existingIndex = context.components.findIndex((c) => c.name.toLowerCase() === name.toLowerCase());
        const componentData = {
            name: this.toPascalCase(name),
            path: path.relative(process.cwd(), filePath),
            group,
            status: "generated",
            generatedAt: new Date().toISOString()
        };
        if (existingIndex > -1) {
            context.components[existingIndex] = { ...context.components[existingIndex], ...componentData };
        }
        else {
            context.components.push(componentData);
        }
        await fs.writeJson(contextPath, context, { spaces: 2 });
    }
}
exports.AddCommand = AddCommand;
//# sourceMappingURL=add.js.map