#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BuildAppCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const prompts_1 = __importDefault(require("prompts"));
const WorkflowAgent_1 = require("../agents/implementations/WorkflowAgent");
class BuildAppCommand {
    constructor() {
        this.workflowAgent = new WorkflowAgent_1.WorkflowAgent();
        // Legacy methods removed - now using WorkflowAgent for all functionality
        // The new agent-based workflow provides better coordination, error handling, and user interaction
    }
    async execute(options) {
        // Handle mycontext PM plan input
        let pmPlanData = null;
        if (options.pmPlan) {
            pmPlanData = await this.loadPMPlan(options.pmPlan);
            console.log(chalk_1.default.blue.bold("🤖 Building App from mycontext PM Project Plan\n"));
        }
        else {
            console.log(chalk_1.default.blue.bold("🚀 Building Complete App with MyContext\n"));
        }
        // Merge mycontext PM plan data with command options
        const finalOptions = this.mergeOptionsWithPMPlan(options, pmPlanData);
        const { description, output = "mycontext-app", framework = "nextjs", withTests = false, verbose = false, existing = false, migrate = false, interactive = false, skipValidation = false, maxRetries = 3, completeArchitecture = false, architectureType = "nextjs-app-router", serverActions = true, routes = true, pmPlan, autoSync = false, webhookUrl, score = false, } = finalOptions;
        // Display different header for PM plan builds
        if (pmPlanData) {
            console.log(chalk_1.default.cyan("📋 PM Plan:"));
            console.log(`   Project: ${chalk_1.default.white(pmPlanData.project.name)}`);
            console.log(`   Description: ${chalk_1.default.white(pmPlanData.project.description.substring(0, 60))}...`);
            console.log(`   Tasks: ${chalk_1.default.white(pmPlanData.breakdown.tasks?.length || 0)}`);
            console.log(`   Framework: ${chalk_1.default.white(framework)}`);
            console.log(`   Architecture: ${chalk_1.default.white(architectureType)}`);
        }
        else {
            console.log(chalk_1.default.gray(`Description: ${description}`));
        }
        console.log(chalk_1.default.gray(`Output: ${output}`));
        console.log(chalk_1.default.gray(`Framework: ${framework}`));
        console.log(chalk_1.default.gray(`Interactive Mode: ${interactive ? "Enabled" : "Disabled"}`));
        console.log(chalk_1.default.gray(`Max Retries: ${maxRetries}`));
        if (completeArchitecture) {
            console.log(chalk_1.default.blue.bold("\n🏗️  Complete Architecture Mode"));
            console.log(chalk_1.default.gray(`Architecture Type: ${architectureType}`));
            console.log(chalk_1.default.gray(`Server Actions: ${serverActions ? "Yes" : "No"}`));
            console.log(chalk_1.default.gray(`Routes: ${routes ? "Yes" : "No"}`));
        }
        console.log();
        // Interactive prompts for complete architecture
        let finalCompleteArchitecture = completeArchitecture;
        let finalArchitectureType = architectureType;
        if (interactive && !completeArchitecture) {
            const architecturePrompts = await (0, prompts_1.default)([
                {
                    type: "confirm",
                    name: "useCompleteArch",
                    message: "Generate complete architecture (components + actions + routes)?",
                    initial: true,
                },
                {
                    type: (prev) => (prev ? "select" : null),
                    name: "archType",
                    message: "Choose architecture type:",
                    choices: [
                        {
                            title: "Next.js App Router (Recommended)",
                            value: "nextjs-app-router",
                        },
                        { title: "Next.js Pages Router", value: "nextjs-pages" },
                        { title: "React SPA", value: "react-spa" },
                    ],
                    initial: 0,
                },
            ]);
            if (architecturePrompts.useCompleteArch) {
                finalCompleteArchitecture = true;
                finalArchitectureType =
                    architecturePrompts.archType || architectureType;
                console.log(chalk_1.default.blue.bold("\n🏗️  Complete Architecture Mode Enabled"));
                console.log(chalk_1.default.gray(`Architecture Type: ${finalArchitectureType}`));
                console.log();
            }
        }
        try {
            // Ensure description is available
            if (!description) {
                throw new Error("Project description is required");
            }
            // Use the new WorkflowAgent for agent-based, interactive workflow
            const workflowInput = {
                description,
                projectName: output,
                framework: framework,
                withTests,
                interactive,
                skipValidation,
                maxRetries,
                // Complete Architecture Options
                completeArchitecture: finalCompleteArchitecture,
                architectureType: finalArchitectureType,
                generateServerActions: serverActions,
                generateRoutes: routes,
                selfDocumenting: finalCompleteArchitecture, // Auto-enable if complete architecture
            };
            const result = await this.workflowAgent.run(workflowInput);
            if (result.success) {
                console.log(chalk_1.default.green.bold("\n✅ App built successfully with MyContext!"));
                console.log(chalk_1.default.yellow(`\n📁 Output directory: ${path_1.default.resolve(result.projectPath)}`));
                if (finalCompleteArchitecture) {
                    console.log(chalk_1.default.green.bold("\n🏗️  Complete Architecture Generated:"));
                    console.log(chalk_1.default.gray(`   ✅ Components with self-documentation`));
                    if (serverActions) {
                        console.log(chalk_1.default.gray(`   ✅ Server actions in actions/`));
                    }
                    if (routes) {
                        console.log(chalk_1.default.gray(`   ✅ Next.js routes in app/`));
                    }
                    console.log(chalk_1.default.gray(`   ✅ Architecture plan in .mycontext/`));
                }
                console.log(chalk_1.default.yellow(`\n🚀 To start the app:`));
                console.log(chalk_1.default.gray(`   cd ${result.projectPath}`));
                console.log(chalk_1.default.gray(`   pnpm dev`));
                console.log(chalk_1.default.yellow(`\n🌐 To preview:`));
                console.log(chalk_1.default.gray(`   Visit https://studio.mycontext.app`));
                console.log(chalk_1.default.gray(`   Upload .mycontext/ from ${result.projectPath}`));
                // Show workflow statistics
                if (interactive || verbose) {
                    console.log(chalk_1.default.blue(`\n📊 Workflow Statistics:`));
                    console.log(chalk_1.default.gray(`   • Completed Steps: ${result.completedSteps.length}`));
                    console.log(chalk_1.default.gray(`   • User Interactions: ${result.userInteractions}`));
                    console.log(chalk_1.default.gray(`   • Total Retries: ${result.totalRetries}`));
                    console.log(chalk_1.default.gray(`   • Duration: ${Math.round(result.duration / 1000)}s`));
                }
            }
            else {
                console.log(chalk_1.default.red.bold("\n❌ Workflow failed"));
                console.log(chalk_1.default.red(`Failed steps: ${result.failedSteps.join(", ")}`));
                // Provide recovery options if interactive
                if (interactive && result.failedSteps.length > 0) {
                    console.log(chalk_1.default.yellow(`\n🔧 Recovery Options:`));
                    console.log(chalk_1.default.gray(`   • Run individual commands for failed steps`));
                    console.log(chalk_1.default.gray(`   • Check .mycontext/ directory for generated files`));
                    console.log(chalk_1.default.gray(`   • Review error logs above for specific issues`));
                }
                throw new Error(`Workflow failed with ${result.failedSteps.length} failed steps`);
            }
        }
        catch (error) {
            console.log(chalk_1.default.red.bold("\n❌ Build failed"));
            console.log(chalk_1.default.red(`Error: ${error instanceof Error ? error.message : "Unknown error"}`));
            // Provide helpful next steps
            console.log(chalk_1.default.yellow(`\n🔧 Troubleshooting:`));
            console.log(chalk_1.default.gray(`   • Check that all dependencies are installed`));
            console.log(chalk_1.default.gray(`   • Verify API keys are configured (optional)`));
            console.log(chalk_1.default.gray(`   • Review the generated files in .mycontext/`));
            console.log(chalk_1.default.gray(`   • Try running individual commands manually`));
            if (finalCompleteArchitecture) {
                console.log(chalk_1.default.yellow(`\n🏗️  Complete Architecture Troubleshooting:`));
                console.log(chalk_1.default.gray(`   • Ensure component list exists (.mycontext/04-component-list.json)`));
                console.log(chalk_1.default.gray(`   • Check that PRD and context files are generated`));
                console.log(chalk_1.default.gray(`   • Try basic generation first without --complete-architecture`));
                console.log(chalk_1.default.gray(`   • Review architecture plan in .mycontext/architecture-plan.json`));
            }
            throw error;
        }
    }
    // mycontext PM Integration Methods
    async loadPMPlan(planFile) {
        if (!fs_1.default.existsSync(planFile)) {
            throw new Error(`PM plan file not found: ${planFile}`);
        }
        try {
            const planContent = fs_1.default.readFileSync(planFile, "utf8");
            const pmPlan = JSON.parse(planContent);
            // Basic validation
            if (!pmPlan.project || !pmPlan.breakdown || !pmPlan.myContext) {
                throw new Error("Invalid PM plan structure");
            }
            return pmPlan;
        }
        catch (error) {
            if (error instanceof SyntaxError) {
                throw new Error(`Invalid JSON in PM plan file: ${error.message}`);
            }
            throw error;
        }
    }
    mergeOptionsWithPMPlan(options, pmPlan) {
        if (!pmPlan) {
            // Ensure description is provided when no PM plan
            if (!options.description) {
                throw new Error("Description is required when not using a PM plan");
            }
            return options;
        }
        // Merge PM plan data with command options
        return {
            ...options,
            description: pmPlan.project.description,
            framework: pmPlan.myContext.framework,
            withTests: pmPlan.myContext.withTests,
            completeArchitecture: pmPlan.myContext.completeArchitecture,
            architectureType: pmPlan.myContext.architecture,
            serverActions: pmPlan.myContext.generateServerActions,
            routes: pmPlan.myContext.generateRoutes,
            // Keep command-line options if explicitly provided
            output: options.output,
            verbose: options.verbose,
            interactive: options.interactive,
            skipValidation: options.skipValidation,
            maxRetries: options.maxRetries,
        };
    }
    // Help text method
    static getHelpText() {
        return `
${chalk_1.default.blue.bold("🚀 MyContext Build App Command")}

${chalk_1.default.yellow("Usage:")}
  mycontext build-app --description "<description>" [options]

${chalk_1.default.yellow("Basic Options:")}
  --description <desc>      Application description (required)
  --output <dir>           Output directory (default: mycontext-app)
  --framework <name>       Framework: nextjs|react|vue|angular (default: nextjs)
  --with-tests            Include test generation
  --interactive           Interactive mode with prompts
  --verbose               Detailed output
  --max-retries <n>       Maximum retry attempts (default: 3)
  --skip-validation       Skip validation steps
  --score                 Perform post-build premium design scoring

${chalk_1.default.yellow("🏗️  Complete Architecture Options:")}
  --complete-architecture  Generate full-stack architecture
  --architecture-type      nextjs-app-router (default) | nextjs-pages | react-spa
  --server-actions         Generate server actions (default: true with --complete-architecture)
  --routes                 Generate Next.js routes (default: true with --complete-architecture)

${chalk_1.default.yellow("🤖 mycontext PM Integration Options:")}
  --pm-plan <file>         Use mycontext PM project plan JSON file
  --auto-sync              Automatically sync progress with mycontext PM
  --webhook-url <url>      Webhook URL for progress updates

${chalk_1.default.yellow("📖 Examples:")}
  ${chalk_1.default.gray("# Basic build")}
  ${chalk_1.default.cyan('mycontext build-app --description "E-commerce platform"')}

  ${chalk_1.default.gray("# Complete architecture")}
  ${chalk_1.default.cyan('mycontext build-app --description "E-commerce platform" --complete-architecture')}

  ${chalk_1.default.gray("# Interactive with architecture")}
  ${chalk_1.default.cyan('mycontext build-app --description "E-commerce platform" --interactive')}

  ${chalk_1.default.gray("# Specific architecture type")}
  ${chalk_1.default.cyan('mycontext build-app --description "Blog" --complete-architecture --architecture-type nextjs-pages')}

  ${chalk_1.default.gray("# Build from mycontext PM project plan")}
  ${chalk_1.default.cyan("mycontext build-app --pm-plan ./pm-project-plan.json")}

  ${chalk_1.default.gray("# Build from PM plan with auto-sync")}
  ${chalk_1.default.cyan("mycontext build-app --pm-plan ./pm-plan.json --auto-sync --webhook-url https://mycontext-pm.example.com/webhook")}

${chalk_1.default.yellow("🎯 What Gets Generated:")}

  ${chalk_1.default.gray("Basic Mode:")}
  • Project structure
  • Context files (PRD, types, brand)
  • Basic React components
  • Component documentation

  ${chalk_1.default.gray("Complete Architecture Mode:")}
  • Everything from Basic Mode, plus:
  • Server actions with validation
  • Next.js App Router routes
  • Self-documenting components
  • Complete architecture plan
  • Production-ready structure

${chalk_1.default.yellow("💡 Tips:")}
  • Use ${chalk_1.default.cyan("--interactive")} for guided setup
  • Use ${chalk_1.default.cyan("--complete-architecture")} for full-stack apps
  • Review generated files in .mycontext/ directory
  • Check architecture-plan.json for complete overview
`;
    }
}
exports.BuildAppCommand = BuildAppCommand;
//# sourceMappingURL=build-app.js.map