"use strict";
// Setup Complete Command
// Single-command guided setup for complete project initialization
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.SetupCompleteCommand = void 0;
const chalk_1 = __importDefault(require("chalk"));
const prompts_1 = __importDefault(require("prompts"));
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const generate_1 = require("./generate");
const progress_1 = require("../utils/progress");
const spinner_1 = require("../utils/spinner");
class SetupCompleteCommand {
    constructor() {
        this.spinner = new spinner_1.EnhancedSpinner("Setting up project...");
    }
    register(program) {
        program
            .command("setup-complete")
            .description("Complete guided project setup with AI assistance")
            .option("-d, --description <text>", "Project description")
            .option("-n, --name <name>", "Project name")
            .option("-o, --output <dir>", "Output directory")
            .option("--force", "Overwrite existing files without confirmation")
            .option("--interactive", "Force interactive mode")
            .option("--auto-continue", "Continue to component generation automatically")
            .option("--skip-confirmation", "Skip confirmation prompts")
            .action(async (options) => {
            await this.execute(options);
        });
    }
    async execute(options) {
        try {
            console.log(chalk_1.default.blue.bold("🚀 MyContext Complete Project Setup\n"));
            console.log("This guided setup will create your complete project structure with AI assistance.\n");
            // Get project preferences
            const preferences = await this.gatherProjectPreferences(options);
            // Confirm setup
            if (!options.skipConfirmation) {
                await this.confirmSetup(preferences);
            }
            // Execute complete setup workflow
            await this.executeCompleteSetup(preferences, options);
            // Show success and next steps
            await this.showSetupComplete(preferences);
        }
        catch (error) {
            console.error(chalk_1.default.red("❌ Setup failed:"), error);
            console.log(chalk_1.default.yellow("\n💡 Troubleshooting:"));
            console.log("  • Check your internet connection for AI services");
            console.log("  • Verify API keys are configured");
            console.log("  • Try with --force to overwrite existing files");
            console.log("  • Use --interactive for guided setup");
            throw error;
        }
    }
    async gatherProjectPreferences(options) {
        // If all options provided and not interactive, use them directly
        if (options.description && options.name && !options.interactive) {
            return {
                name: options.name,
                description: options.description,
                type: "moderate", // default
                techStack: ["Next.js", "TypeScript", "Tailwind CSS"],
                features: ["responsive", "modern"],
                timeline: "standard",
                useAdminStarter: false, // default
            };
        }
        console.log(chalk_1.default.cyan("📋 Let's gather some information about your project:\n"));
        // Project name
        const nameResponse = await (0, prompts_1.default)({
            type: "text",
            name: "name",
            message: "Project name:",
            initial: options.name || "my-awesome-app",
            validate: (value) => value.length >= 2 || "Project name must be at least 2 characters",
        });
        // Project description
        const descriptionResponse = await (0, prompts_1.default)({
            type: "text",
            name: "description",
            message: "Describe your project:",
            initial: options.description || "",
            validate: (value) => value.length >= 10 ||
                "Please provide a detailed description (at least 10 characters)",
        });
        // Project complexity
        const complexityResponse = await (0, prompts_1.default)({
            type: "select",
            name: "type",
            message: "Project complexity:",
            choices: [
                {
                    title: "Simple (landing page, blog, portfolio)",
                    value: "simple",
                    description: "Basic website with 5-10 components",
                },
                {
                    title: "Moderate (dashboard, e-commerce, SaaS)",
                    value: "moderate",
                    description: "Full application with 15-25 components",
                },
                {
                    title: "Complex (social platform, LMS, marketplace)",
                    value: "complex",
                    description: "Advanced application with 30+ components",
                },
            ],
        });
        // Tech stack preferences
        const techStackResponse = await (0, prompts_1.default)({
            type: "multiselect",
            name: "techStack",
            message: "Select your preferred technologies:",
            choices: [
                { title: "Next.js", value: "Next.js", selected: true },
                { title: "React", value: "React" },
                { title: "TypeScript", value: "TypeScript", selected: true },
                { title: "Tailwind CSS", value: "Tailwind CSS", selected: true },
                { title: "Prisma", value: "Prisma" },
                { title: "NextAuth.js", value: "NextAuth.js" },
                { title: "Stripe", value: "Stripe" },
                { title: "Supabase", value: "Supabase" },
            ],
            min: 1,
            hint: "Use space to select, enter to confirm",
        });
        // Admin starter option
        const adminStarterResponse = await (0, prompts_1.default)({
            type: "confirm",
            name: "useAdminStarter",
            message: "Include admin starter template? (Auth + User Management)",
            initial: false,
            hint: "Adds pre-built admin dashboard with authentication and user management features",
        });
        // Timeline preference
        const timelineResponse = await (0, prompts_1.default)({
            type: "select",
            name: "timeline",
            message: "Development timeline:",
            choices: [
                { title: "Quick (1-2 weeks)", value: "quick" },
                { title: "Standard (2-4 weeks)", value: "standard", selected: true },
                { title: "Extended (1-3 months)", value: "extended" },
            ],
        });
        return {
            name: nameResponse.name,
            description: descriptionResponse.description,
            type: complexityResponse.type,
            techStack: techStackResponse.techStack,
            features: this.getDefaultFeatures(complexityResponse.type),
            timeline: timelineResponse.timeline,
            useAdminStarter: adminStarterResponse.useAdminStarter,
        };
    }
    getDefaultFeatures(type) {
        const baseFeatures = ["responsive", "accessible"];
        switch (type) {
            case "simple":
                return [...baseFeatures, "fast", "seo-friendly"];
            case "moderate":
                return [...baseFeatures, "interactive", "data-driven", "user-accounts"];
            case "complex":
                return [
                    ...baseFeatures,
                    "real-time",
                    "multi-tenant",
                    "advanced-analytics",
                    "api-driven",
                ];
            default:
                return baseFeatures;
        }
    }
    async confirmSetup(preferences) {
        console.log(chalk_1.default.cyan("\n📋 Setup Summary:"));
        console.log(`   Project: ${chalk_1.default.white(preferences.name)}`);
        console.log(`   Type: ${chalk_1.default.white(preferences.type)}`);
        console.log(`   Tech Stack: ${chalk_1.default.white(preferences.techStack.join(", "))}`);
        console.log(`   Timeline: ${chalk_1.default.white(preferences.timeline)}`);
        console.log(`   Key Features: ${chalk_1.default.white(preferences.features.join(", "))}`);
        console.log(`   Admin Starter: ${chalk_1.default.white(preferences.useAdminStarter ? "Yes" : "No")}`);
        console.log("");
        const confirmResponse = await (0, prompts_1.default)({
            type: "confirm",
            name: "confirm",
            message: "Ready to create this project?",
            initial: true,
        });
        if (!confirmResponse.confirm) {
            console.log(chalk_1.default.yellow("Setup cancelled."));
            process.exit(0);
        }
    }
    async executeCompleteSetup(preferences, options) {
        const outputDir = options.output || preferences.name;
        const projectPath = path_1.default.resolve(outputDir);
        // Initialize progress tracker with enhanced features
        const progressTracker = new progress_1.ProgressTracker("Complete Project Setup");
        progressTracker
            .addStep("init", "Initialize project structure", 2000)
            .addStep("context", "Generate context files", 8000)
            .addStep("architecture", "Generate project architecture", 15000)
            .addStep("components", "Generate components", 20000);
        // Add admin starter step if requested
        if (preferences.useAdminStarter) {
            progressTracker.addStep("admin-starter", "Setup admin starter template", 5000);
        }
        console.log(chalk_1.default.blue.bold(`\n🏗️ Creating project: ${preferences.name}`));
        console.log(chalk_1.default.gray(`Location: ${projectPath}`));
        console.log(chalk_1.default.gray(`Estimated time: ~${this.estimateTotalTime(preferences)} minutes\n`));
        // Start real-time progress updates
        const progressInterval = progressTracker.startProgressUpdates(3000);
        // Check if directory exists
        if ((await fs_extra_1.default.pathExists(projectPath)) && !options.force) {
            const overwriteResponse = await (0, prompts_1.default)({
                type: "confirm",
                name: "overwrite",
                message: `Directory ${outputDir} already exists. Overwrite?`,
                initial: false,
            });
            if (!overwriteResponse.overwrite) {
                console.log(chalk_1.default.yellow("Setup cancelled."));
                return;
            }
        }
        try {
            // Step 1: Initialize project
            progressTracker.startStep("init");
            console.log(chalk_1.default.cyan("📁 Step 1: Initializing project structure..."));
            // Create project directory
            await fs_extra_1.default.ensureDir(projectPath);
            process.chdir(projectPath);
            // Create basic package.json
            const packageJson = {
                name: preferences.name.toLowerCase().replace(/\s+/g, "-"),
                version: "0.1.0",
                description: preferences.description,
                scripts: {
                    dev: "next dev",
                    build: "next build",
                    start: "next start",
                    lint: "next lint",
                },
                dependencies: {},
                devDependencies: {},
            };
            await fs_extra_1.default.writeJson("package.json", packageJson, { spaces: 2 });
            progressTracker.completeStep("init", "✅ Project initialized");
            console.log(chalk_1.default.gray(`   Created project structure`));
            // Step 2: Generate context files
            progressTracker.startStep("context");
            console.log(chalk_1.default.cyan("📝 Step 2: Generating context files..."));
            const contextDescription = this.buildContextDescription(preferences);
            const generateCommand = new generate_1.GenerateCommand();
            await generateCommand.execute({
                type: "context",
                full: true,
                description: contextDescription,
                force: true,
            });
            progressTracker.completeStep("context", "✅ Context files generated");
            console.log(chalk_1.default.gray(`   Generated PRD and feature specifications`));
            // Step 3: Generate architecture
            progressTracker.startStep("architecture");
            console.log(chalk_1.default.cyan("🏗️ Step 3: Generating project architecture..."));
            await generateCommand.execute({
                type: "architecture",
                description: contextDescription,
                output: path_1.default.join(projectPath, ".mycontext"),
                autoContinue: options.autoContinue || false,
                force: true,
            });
            progressTracker.completeStep("architecture", "✅ Architecture generated");
            console.log(chalk_1.default.gray(`   Generated types, components, and project structure`));
            // Step 4: Setup admin starter (if requested)
            if (preferences.useAdminStarter) {
                progressTracker.startStep("admin-starter");
                console.log(chalk_1.default.cyan("🚀 Step 4: Setting up admin starter template..."));
                const { CloneStarterCommand } = await Promise.resolve().then(() => __importStar(require("./clone-starter")));
                const cloneCommand = new CloneStarterCommand();
                // TODO: Replace with actual admin starter repo URL
                await cloneCommand.execute({
                    url: "https://github.com/your-username/admin-starter-template", // Placeholder
                    output: projectPath,
                    install: true,
                    setup: true,
                    verbose: false,
                });
                progressTracker.completeStep("admin-starter", "✅ Admin starter setup");
                console.log(chalk_1.default.gray(`   Cloned and configured admin starter template`));
            }
            // Step 5: Generate components (if auto-continue enabled)
            if (options.autoContinue) {
                progressTracker.startStep("components");
                console.log(chalk_1.default.cyan("🧩 Step 5: Generating components..."));
                const { GenerateComponentsCommand } = await Promise.resolve().then(() => __importStar(require("./generate-components")));
                const generateComponentsCommand = new GenerateComponentsCommand();
                await generateComponentsCommand.execute("all", {
                    withTests: true,
                    all: true,
                });
                progressTracker.completeStep("components", "✅ Components generated");
                console.log(chalk_1.default.gray(`   Generated component implementations`));
            }
            // Show final progress
            clearInterval(progressInterval);
            console.log(chalk_1.default.gray(`\n📊 ${progressTracker.getDetailedProgress()}`));
        }
        catch (error) {
            // Clean up progress interval
            clearInterval(progressInterval);
            // Note: We don't have a getCurrentStep method, so we'll use a generic failure message
            console.error(chalk_1.default.red("❌ Setup failed:"), error);
            throw error;
        }
    }
    estimateTotalTime(preferences) {
        // Base time estimates in minutes
        const baseTimes = {
            simple: 3,
            moderate: 5,
            complex: 8,
        };
        let totalMinutes = baseTimes[preferences.type];
        // Add time for admin starter
        if (preferences.useAdminStarter) {
            totalMinutes += 2;
        }
        // Add time for component generation if auto-continue is enabled
        if (preferences.features.includes("interactive") ||
            preferences.features.includes("real-time")) {
            totalMinutes += 2;
        }
        // Add time for complex tech stacks
        if (preferences.techStack.length > 4) {
            totalMinutes += 1;
        }
        return Math.ceil(totalMinutes);
    }
    buildContextDescription(preferences) {
        const typeDescriptions = {
            simple: "a simple, clean website",
            moderate: "a full-featured web application",
            complex: "an advanced, scalable web platform",
        };
        return `Create ${typeDescriptions[preferences.type]} called "${preferences.name}" with the following requirements:

Project Description: ${preferences.description}

Technical Requirements:
• Tech Stack: ${preferences.techStack.join(", ")}
• Complexity Level: ${preferences.type}
• Key Features: ${preferences.features.join(", ")}
• Timeline: ${preferences.timeline}

Please generate comprehensive context files that will guide the development of this ${preferences.type} project using modern best practices and the specified technology stack.`;
    }
    async showSetupComplete(preferences) {
        const projectPath = path_1.default.resolve(preferences.name);
        console.log(chalk_1.default.green.bold(`\n🎉 Project "${preferences.name}" setup complete!`));
        console.log("");
        console.log(chalk_1.default.cyan("📁 Project Structure:"));
        console.log(`   Location: ${chalk_1.default.white(projectPath)}`);
        console.log(`   Type: ${chalk_1.default.white(preferences.type)} application`);
        console.log(`   Tech Stack: ${chalk_1.default.white(preferences.techStack.join(", "))}`);
        console.log("");
        console.log(chalk_1.default.cyan("📋 Generated Files:"));
        console.log("   • PRD and feature specifications");
        console.log("   • TypeScript type definitions");
        console.log("   • Component architecture");
        console.log("   • Project structure");
        if (preferences.type === "moderate" || preferences.type === "complex") {
            console.log("   • Brand guidelines");
        }
        console.log("");
        console.log(chalk_1.default.cyan("🚀 Next Steps:"));
        // Change to project directory
        console.log(`   ${chalk_1.default.cyan(`cd ${preferences.name}`)}`);
        // Install dependencies
        console.log(`   ${chalk_1.default.cyan("pnpm install")}  # Install dependencies`);
        // Start development
        console.log(`   ${chalk_1.default.cyan("pnpm dev")}     # Start development server`);
        if (!preferences.techStack.includes("Next.js")) {
            console.log(`   ${chalk_1.default.cyan("npm run dev")}  # Alternative start command`);
        }
        console.log("");
        console.log(chalk_1.default.cyan("🔧 Development Commands:"));
        console.log(`   ${chalk_1.default.gray("mycontext generate components")}  # Generate more components`);
        console.log(`   ${chalk_1.default.gray("mycontext build-app")}           # Build complete application`);
        console.log(`   ${chalk_1.default.gray("Visit https://studio.mycontext.app")}   # Preview generated components`);
        console.log("");
        console.log(chalk_1.default.green("💡 Tip: Your project is ready for development!"));
        console.log(chalk_1.default.gray("   Use 'mycontext --help' for more commands."));
    }
    static getHelpText() {
        return `
${chalk_1.default.blue.bold("🚀 MyContext Setup Complete Command")}

${chalk_1.default.yellow("Description:")}
  Complete guided project setup with AI assistance. This single command creates
  your entire project structure, from initial concept to working application.

${chalk_1.default.yellow("What it does:")}
  1. 📁 Creates project directory and initializes structure
  2. 📝 Generates comprehensive context files (PRD, features, specs)
  3. 🏗️ Creates complete project architecture (types, components, structure)
  4. 🧩 Optionally generates component implementations
  5. 📋 Provides next steps and development guidance

${chalk_1.default.yellow("Usage:")}
  mycontext setup-complete [options]

${chalk_1.default.yellow("Interactive Mode (Recommended for first-time users):")}
  mycontext setup-complete --interactive

${chalk_1.default.yellow("Direct Mode (For automation/scripts):")}
  mycontext setup-complete \\
    --name "My Project" \\
    --description "A modern web application for task management" \\
    --auto-continue

${chalk_1.default.yellow("Options:")}
  -n, --name <name>         Project name
  -d, --description <text>  Project description
  -o, --output <dir>        Output directory (default: project name)
  --force                   Overwrite existing files
  --interactive             Force interactive mode
  --auto-continue           Generate components automatically
  --skip-confirmation       Skip confirmation prompts

${chalk_1.default.yellow("Project Types:")}
  • Simple: Landing pages, portfolios, blogs (5-10 components)
  • Moderate: Dashboards, e-commerce, SaaS apps (15-25 components)
  • Complex: Social platforms, LMS, marketplaces (30+ components)

${chalk_1.default.yellow("Examples:")}
  ${chalk_1.default.gray("# Interactive setup (recommended)")}
  ${chalk_1.default.cyan("mycontext setup-complete --interactive")}

  ${chalk_1.default.gray("# Direct setup with description")}
  ${chalk_1.default.cyan('mycontext setup-complete --name "TaskApp" --description "A modern task management application"')}

  ${chalk_1.default.gray("# Complete setup with components")}
  ${chalk_1.default.cyan('mycontext setup-complete --name "Ecommerce" --description "Online store" --auto-continue')}

${chalk_1.default.yellow("Generated Structure:")}
  project/
  ├── .mycontext/           # Context and configuration
  │   ├── 01-prd.md        # Product requirements
  │   ├── 02-types.ts      # TypeScript definitions
  │   ├── 03-branding.md   # Design guidelines
  │   ├── 04-component-list.json # Component specifications
  │   └── 05-project-structure.md # Architecture
  ├── components/           # Generated components (if --auto-continue)
  ├── package.json          # Project configuration
  └── README.md            # Setup documentation

${chalk_1.default.green("💡 This command replaces 4-6 separate commands with one guided experience!")}
`;
    }
}
exports.SetupCompleteCommand = SetupCompleteCommand;
//# sourceMappingURL=setup-complete.js.map