"use strict";
/**
 * ProjectSetupAgent Implementation
 *
 * Handles project initialization and setup tasks in the build workflow.
 * Manages project structure creation, dependency installation, and basic configuration.
 */
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.ProjectSetupAgent = void 0;
const init_1 = require("../../commands/init");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const child_process_1 = require("child_process");
const chalk_1 = __importDefault(require("chalk"));
class ProjectSetupAgent {
    constructor() {
        this.name = "ProjectSetupAgent";
        this.description = "Handles project initialization, dependency management, and basic configuration setup";
        this.personality = "Methodical project architect that ensures proper foundation and configuration";
        this.llmProvider = "system"; // Uses system commands, not AI
        this.expertise = [
            "project-setup",
            "dependency-management",
            "configuration",
            "framework-setup",
        ];
    }
    async run(input) {
        const errors = [];
        const dependencies = [];
        const configFiles = [];
        try {
            let projectPath;
            if (input.existing) {
                // Handle existing project
                projectPath = path.resolve(input.projectName);
                if (!fs.existsSync(projectPath)) {
                    throw new Error(`Existing project directory not found: ${projectPath}`);
                }
                console.log(chalk_1.default.blue(`📁 Working with existing project: ${projectPath}`));
                // Check if it's already a MyContext project
                const mycontextDir = path.join(projectPath, ".mycontext");
                const isMyContextProject = fs.existsSync(mycontextDir);
                if (isMyContextProject && !input.migrate) {
                    console.log(chalk_1.default.yellow("⚠️  Project is already initialized with MyContext"));
                    return {
                        success: true,
                        projectPath,
                        initialized: false,
                        dependencies,
                        configFiles,
                    };
                }
                if (input.migrate) {
                    await this.migrateExistingProject(projectPath);
                }
            }
            else {
                // Create new project
                projectPath = await this.initializeNewProject(input);
                configFiles.push("package.json", "tsconfig.json", "tailwind.config.js");
            }
            // Install dependencies if not skipped
            if (!input.skipDependencies) {
                console.log(chalk_1.default.blue("📦 Installing dependencies..."));
                try {
                    (0, child_process_1.execSync)("pnpm install", { cwd: projectPath, stdio: "inherit" });
                    dependencies.push("next", "react", "react-dom", "typescript", "tailwindcss", "shadcn/ui");
                }
                catch (error) {
                    errors.push(`Failed to install dependencies: ${error}`);
                }
            }
            // Create MyContext directory structure
            await this.createMyContextStructure(projectPath);
            return {
                success: true,
                projectPath,
                initialized: true,
                dependencies,
                configFiles,
                errors: errors.length > 0 ? errors : undefined,
            };
        }
        catch (error) {
            return {
                success: false,
                projectPath: path.resolve(input.projectName),
                initialized: false,
                dependencies,
                configFiles,
                errors: [error instanceof Error ? error.message : "Unknown error"],
            };
        }
    }
    async initializeNewProject(input) {
        const initCommand = new init_1.InitCommand();
        const projectPath = path.resolve(input.projectName);
        console.log(chalk_1.default.blue(`🚀 Initializing new ${input.framework} project: ${input.projectName}`));
        await initCommand.execute(input.projectName, {
            framework: input.framework,
            yes: true,
            verbose: false,
        });
        return projectPath;
    }
    async migrateExistingProject(projectPath) {
        console.log(chalk_1.default.blue("🔄 Migrating existing project to MyContext..."));
        // Create .mycontext directory
        const mycontextDir = path.join(projectPath, ".mycontext");
        if (!fs.existsSync(mycontextDir)) {
            fs.mkdirSync(mycontextDir, { recursive: true });
        }
        // Create basic MyContext structure
        const basicFiles = [
            "01-prd.md",
            "02-types.ts",
            "03-branding.md",
            "04-component-list.json",
            "06-env.example",
        ];
        for (const file of basicFiles) {
            const filePath = path.join(mycontextDir, file);
            if (!fs.existsSync(filePath)) {
                // Create placeholder files
                const content = this.getPlaceholderContent(file);
                fs.writeFileSync(filePath, content);
            }
        }
        console.log(chalk_1.default.green("✅ Project migrated successfully"));
    }
    async createMyContextStructure(projectPath) {
        const mycontextDir = path.join(projectPath, ".mycontext");
        if (!fs.existsSync(mycontextDir)) {
            fs.mkdirSync(mycontextDir, { recursive: true });
        }
        // Create context files structure
        const contextFiles = [
            "01a-features.md",
            "01b-user-flows.md",
            "01c-edge-cases.md",
            "01d-technical-specs.md",
            "01-prd.md",
            "02-types.ts",
            "03-branding.md",
            "04-component-list.json",
            "06-env.example",
        ];
        for (const file of contextFiles) {
            const filePath = path.join(mycontextDir, file);
            if (!fs.existsSync(filePath)) {
                const content = this.getPlaceholderContent(file);
                fs.writeFileSync(filePath, content);
            }
        }
    }
    getPlaceholderContent(filename) {
        const placeholders = {
            "01a-features.md": "# Product Features\n\nThis file will contain the detailed feature specifications.\n\n## Next Steps\n1. Run `mycontext generate-context-files` to populate this file\n2. Review and refine the generated content\n3. Run `mycontext compile-prd` to create the PRD\n",
            "01b-user-flows.md": "# User Flows\n\nThis file will contain user journey mappings.\n",
            "01c-edge-cases.md": "# Edge Cases\n\nThis file will contain error scenarios and edge conditions.\n",
            "01d-technical-specs.md": "# Technical Specifications\n\nThis file will contain technical requirements and architecture decisions.\n",
            "01-prd.md": "# Product Requirements Document\n\nThis file will be compiled from the context files.\n",
            "02-types.ts": "// TypeScript type definitions\nexport interface User {\n  id: string;\n  name: string;\n  email: string;\n}\n",
            "03-branding.md": "# Brand Guidelines\n\nThis file will contain brand specifications and design tokens.\n",
            "04-component-list.json": '{"groups": {}, "metadata": {"version": "1.0.0"}}',
            "06-env.example": "# MyContext Environment Variables\n# Copy this file to .env and add your API keys\n\nMYCONTEXT_QWEN_API_KEY=your_qwen_api_key_here\nMYCONTEXT_GITHUB_TOKEN=your_github_token_here\n",
        };
        return placeholders[filename] || "# Placeholder content\n";
    }
    validate(input) {
        if (!input.projectName || !input.framework) {
            return false;
        }
        const validFrameworks = ["nextjs", "react", "vue", "angular"];
        if (!validFrameworks.includes(input.framework)) {
            return false;
        }
        return true;
    }
    async cleanup() {
        // No cleanup needed for this agent
    }
    async getStatus() {
        return {
            name: this.name,
            status: "idle",
            lastRun: new Date(),
            errorCount: 0,
            successCount: 0,
        };
    }
}
exports.ProjectSetupAgent = ProjectSetupAgent;
//# sourceMappingURL=ProjectSetupAgent.js.map