"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.ImportProjectPlanCommand = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
const WorkflowAgent_1 = require("../agents/implementations/WorkflowAgent");
class ImportProjectPlanCommand {
    constructor() {
        this.workflowAgent = new WorkflowAgent_1.WorkflowAgent();
    }
    register(program) {
        program
            .command("import-project-plan")
            .description("Import and execute a mycontext PM project plan")
            .argument("<plan-file>", "Path to mycontext PM project plan JSON file")
            .option("-o, --output <dir>", "Output directory for generated project", "mycontext-project")
            .option("--validate", "Validate plan without executing", false)
            .option("--skip-confirmation", "Skip confirmation prompts", false)
            .option("--verbose", "Detailed output", false)
            .action(async (planFile, options) => {
            await this.importProjectPlan({ ...options, planFile });
        });
    }
    async importProjectPlan(options) {
        const { planFile, output, validate, skipConfirmation, verbose } = options;
        console.log(chalk_1.default.blue.bold("📋 Importing mycontext PM Project Plan\n"));
        try {
            // 1. Load and validate mycontext PM plan
            const pmPlan = await this.loadAndValidatePlan(planFile);
            if (validate) {
                console.log(chalk_1.default.green("✅ Plan validation successful!"));
                this.displayPlanSummary(pmPlan);
                return;
            }
            // 2. Display plan summary and get confirmation
            this.displayPlanSummary(pmPlan);
            if (!skipConfirmation) {
                const confirmed = await this.confirmExecution(pmPlan);
                if (!confirmed) {
                    console.log(chalk_1.default.yellow("Operation cancelled."));
                    return;
                }
            }
            // 3. Create project structure
            console.log(chalk_1.default.blue("\n🏗️  Creating project structure..."));
            const projectPath = await this.createProjectStructure(pmPlan, output || "mycontext-project");
            // 4. Save PM plan to project
            await this.savePlanToProject(pmPlan, projectPath);
            // 5. Execute MyContext workflow
            console.log(chalk_1.default.blue("\n🚀 Executing MyContext workflow..."));
            await this.executeMyContextWorkflow(pmPlan, projectPath);
            // 6. Display results
            this.displayResults(pmPlan, projectPath);
        }
        catch (error) {
            console.error(chalk_1.default.red("❌ Import failed:"), error instanceof Error ? error.message : "Unknown error");
            if (verbose) {
                console.error(chalk_1.default.red("Full error:"), error);
            }
            throw error;
        }
    }
    async loadAndValidatePlan(planFile) {
        console.log(chalk_1.default.gray(`Loading plan from: ${planFile}`));
        if (!fs_1.default.existsSync(planFile)) {
            throw new Error(`Plan file not found: ${planFile}`);
        }
        let planContent;
        try {
            planContent = fs_1.default.readFileSync(planFile, "utf8");
        }
        catch (error) {
            throw new Error(`Failed to read plan file: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
        let pmPlan;
        try {
            pmPlan = JSON.parse(planContent);
        }
        catch (error) {
            throw new Error(`Invalid JSON in plan file: ${error instanceof Error ? error.message : "Unknown error"}`);
        }
        // Validate required fields
        this.validatePlanStructure(pmPlan);
        console.log(chalk_1.default.green("✅ Plan loaded and validated"));
        return pmPlan;
    }
    validatePlanStructure(plan) {
        if (!plan.project) {
            throw new Error("Missing 'project' section in PM plan");
        }
        if (!plan.project.name || !plan.project.description) {
            throw new Error("Missing required project fields: name and description");
        }
        if (!plan.breakdown) {
            throw new Error("Missing 'breakdown' section in PM plan");
        }
        if (!plan.myContext) {
            throw new Error("Missing 'myContext' configuration section");
        }
        // Validate MyContext configuration
        const requiredFields = [
            "framework",
            "architecture",
            "generateServerActions",
            "generateRoutes",
        ];
        for (const field of requiredFields) {
            if (!(field in plan.myContext)) {
                throw new Error(`Missing required MyContext field: ${field}`);
            }
        }
    }
    displayPlanSummary(plan) {
        console.log(chalk_1.default.blue.bold("\n📋 mycontext PM Project Plan Summary"));
        console.log(chalk_1.default.gray("─".repeat(50)));
        // Project info
        console.log(chalk_1.default.cyan("🏗️  Project:"));
        console.log(`   Name: ${chalk_1.default.white(plan.project.name)}`);
        console.log(`   Description: ${chalk_1.default.white(plan.project.description.substring(0, 100))}...`);
        if (plan.project.techStack) {
            console.log(`   Tech Stack: ${chalk_1.default.white(plan.project.techStack.join(", "))}`);
        }
        // Timeline
        if (plan.project.timeline) {
            console.log(chalk_1.default.cyan("\n⏰ Timeline:"));
            console.log(`   Duration: ${chalk_1.default.white(plan.project.timeline.totalWeeks)} weeks`);
            console.log(`   Start: ${chalk_1.default.white(plan.project.timeline.startDate)}`);
            console.log(`   End: ${chalk_1.default.white(plan.project.timeline.endDate)}`);
        }
        // Budget
        if (plan.project.budget) {
            console.log(chalk_1.default.cyan("\n💰 Budget:"));
            console.log(`   Amount: ${chalk_1.default.white(plan.project.budget.amount)} ${plan.project.budget.currency}`);
        }
        // Task breakdown
        console.log(chalk_1.default.cyan("\n📊 Task Breakdown:"));
        console.log(`   Epics: ${chalk_1.default.white(plan.breakdown.epics?.length || 0)}`);
        console.log(`   User Stories: ${chalk_1.default.white(plan.breakdown.userStories?.length || 0)}`);
        console.log(`   Tasks: ${chalk_1.default.white(plan.breakdown.tasks?.length || 0)}`);
        console.log(`   Phases: ${chalk_1.default.white(plan.breakdown.phases?.length || 0)}`);
        // MyContext config
        console.log(chalk_1.default.cyan("\n⚙️  MyContext Configuration:"));
        console.log(`   Framework: ${chalk_1.default.white(plan.myContext.framework)}`);
        console.log(`   Architecture: ${chalk_1.default.white(plan.myContext.architecture)}`);
        console.log(`   Server Actions: ${chalk_1.default.white(plan.myContext.generateServerActions ? "Yes" : "No")}`);
        console.log(`   Routes: ${chalk_1.default.white(plan.myContext.generateRoutes ? "Yes" : "No")}`);
        console.log(`   Tests: ${chalk_1.default.white(plan.myContext.withTests ? "Yes" : "No")}`);
        console.log(`   Complete Architecture: ${chalk_1.default.white(plan.myContext.completeArchitecture ? "Yes" : "No")}`);
        // Components
        if (plan.components) {
            console.log(chalk_1.default.cyan("\n🧩 Components:"));
            console.log(`   UI Components: ${chalk_1.default.white(plan.components.ui?.length || 0)}`);
            console.log(`   Pages: ${chalk_1.default.white(plan.components.pages?.length || 0)}`);
            console.log(`   API Endpoints: ${chalk_1.default.white(plan.components.api?.length || 0)}`);
        }
    }
    async confirmExecution(plan) {
        const { default: prompts } = await Promise.resolve().then(() => __importStar(require("prompts")));
        const response = await prompts({
            type: "confirm",
            name: "confirm",
            message: `Execute mycontext PM project plan for "${plan.project.name}"?`,
            initial: true,
        });
        return response.confirm;
    }
    async createProjectStructure(plan, outputDir) {
        const projectPath = path_1.default.resolve(outputDir);
        // Create output directory
        if (!fs_1.default.existsSync(projectPath)) {
            fs_1.default.mkdirSync(projectPath, { recursive: true });
        }
        // Initialize basic project structure
        const myContextDir = path_1.default.join(projectPath, ".mycontext");
        if (!fs_1.default.existsSync(myContextDir)) {
            fs_1.default.mkdirSync(myContextDir, { recursive: true });
        }
        console.log(chalk_1.default.green(`✅ Project structure created at: ${projectPath}`));
        return projectPath;
    }
    async savePlanToProject(plan, projectPath) {
        const myContextDir = path_1.default.join(projectPath, ".mycontext");
        // Save PM plan
        const planPath = path_1.default.join(myContextDir, "pm-plan.json");
        fs_1.default.writeFileSync(planPath, JSON.stringify(plan, null, 2));
        // Save tasks for MyContext
        const tasks = this.convertPMTasksToMyContext(plan.breakdown.tasks || []);
        const todosPath = path_1.default.join(myContextDir, "todos.json");
        fs_1.default.writeFileSync(todosPath, JSON.stringify(tasks, null, 2));
        // Save project context
        const contextPath = path_1.default.join(myContextDir, "project-context.json");
        const projectContext = {
            name: plan.project.name,
            description: plan.project.description,
            techStack: plan.project.techStack,
            timeline: plan.project.timeline,
            budget: plan.project.budget,
            myContextConfig: plan.myContext,
            createdFromPM: true,
            createdAt: new Date().toISOString(),
        };
        fs_1.default.writeFileSync(contextPath, JSON.stringify(projectContext, null, 2));
        console.log(chalk_1.default.green("✅ PM plan saved to project"));
    }
    convertPMTasksToMyContext(pmTasks) {
        return pmTasks.map((task, index) => ({
            id: task.id || `task-${Date.now()}-${index}`,
            title: task.title,
            description: task.description,
            status: this.mapPMStatusToMyContext(task.status),
            priority: this.mapPMPriorityToMyContext(task.priority),
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
            estimatedHours: task.estimatedHours,
            dependencies: task.dependencies || [],
            relatedComponents: task.relatedComponents || [],
            tags: task.tags || [],
            projectId: "pm-generated",
        }));
    }
    mapPMStatusToMyContext(pmStatus) {
        const statusMap = {
            todo: "pending",
            in_progress: "in_progress",
            review: "in_review",
            done: "completed",
            blocked: "blocked",
            cancelled: "cancelled",
        };
        return statusMap[pmStatus || "todo"] || "pending";
    }
    mapPMPriorityToMyContext(pmPriority) {
        const priorityMap = {
            critical: "critical",
            high: "high",
            medium: "medium",
            low: "low",
        };
        return priorityMap[pmPriority || "medium"] || "medium";
    }
    async executeMyContextWorkflow(plan, projectPath) {
        const workflowInput = {
            description: plan.project.description,
            projectName: path_1.default.basename(projectPath),
            framework: plan.myContext.framework,
            withTests: plan.myContext.withTests || false,
            interactive: false,
            skipValidation: false,
            maxRetries: 3,
            completeArchitecture: plan.myContext.completeArchitecture || false,
            architectureType: plan.myContext.architecture,
            generateServerActions: plan.myContext.generateServerActions || false,
            generateRoutes: plan.myContext.generateRoutes || false,
            selfDocumenting: plan.myContext.completeArchitecture || false,
        };
        const result = await this.workflowAgent.run(workflowInput);
        if (!result.success) {
            throw new Error(`Workflow failed: ${result.failedSteps.join(", ")}`);
        }
        console.log(chalk_1.default.green("✅ MyContext workflow completed successfully"));
    }
    displayResults(plan, projectPath) {
        console.log(chalk_1.default.green.bold("\n🎉 mycontext PM Project Plan Successfully Imported!"));
        console.log(chalk_1.default.yellow(`📁 Project Location: ${path_1.default.resolve(projectPath)}`));
        console.log(chalk_1.default.blue.bold("\n🏗️  Generated Project Structure:"));
        const structure = [
            "├── .mycontext/",
            "│   ├── pm-plan.json          # Original mycontext PM plan",
            "│   ├── todos.json            # Task breakdown",
            "│   └── project-context.json  # Project metadata",
            "├── components/               # Generated components",
            "├── app/                     # Next.js app routes",
            "├── lib/                     # Utility functions",
            "└── package.json            # Dependencies",
        ];
        structure.forEach((line) => console.log(chalk_1.default.gray(line)));
        console.log(chalk_1.default.blue.bold("\n🚀 Next Steps:"));
        const nextSteps = [
            `cd ${path_1.default.relative(process.cwd(), projectPath)}`,
            "pnpm install",
            "pnpm dev",
            "# View project in browser",
            "# Review generated components",
            "# Customize as needed",
        ];
        nextSteps.forEach((step, index) => {
            console.log(chalk_1.default.cyan(`   ${index + 1}. ${step}`));
        });
        // PM Integration hint
        console.log(chalk_1.default.yellow.bold("\n🔄 For mycontext PM Integration:"));
        console.log(chalk_1.default.gray(`   • Project ID: ${plan.project.name
            .toLowerCase()
            .replace(/\s+/g, "-")}`));
        console.log(chalk_1.default.gray("   • Use 'mycontext export-progress' to sync status"));
        console.log(chalk_1.default.gray("   • Use 'mycontext sync-with-pm' for real-time updates"));
    }
    static getHelpText() {
        return `
${chalk_1.default.blue.bold("📋 MyContext Import Project Plan Command")}

${chalk_1.default.yellow("Description:")}
  Import and execute a mycontext PM project plan to generate a complete application

${chalk_1.default.yellow("Usage:")}
  mycontext import-project-plan <plan-file> [options]

${chalk_1.default.yellow("Arguments:")}
  plan-file              Path to mycontext PM project plan JSON file

${chalk_1.default.yellow("Options:")}
  -o, --output <dir>     Output directory (default: mycontext-project)
  --validate             Validate plan without executing
  --skip-confirmation    Skip confirmation prompts
  --verbose              Detailed output

${chalk_1.default.yellow("mycontext PM Plan Format:")}
  {
    "project": {
      "name": "My Project",
      "description": "Project description...",
      "techStack": ["Next.js", "TypeScript"],
      "timeline": {
        "startDate": "2024-01-01",
        "endDate": "2024-02-01",
        "totalWeeks": 4
      }
    },
    "breakdown": {
      "epics": [...],
      "userStories": [...],
      "tasks": [...],
      "phases": [...]
    },
    "myContext": {
      "framework": "nextjs",
      "architecture": "nextjs-app-router",
      "generateServerActions": true,
      "generateRoutes": true,
      "withTests": true,
      "completeArchitecture": true
    },
    "components": {
      "ui": [...],
      "pages": [...],
      "api": [...]
    }
  }

${chalk_1.default.yellow("Examples:")}
  ${chalk_1.default.gray("# Validate a PM plan")}
  ${chalk_1.default.cyan("mycontext import-project-plan ./pm-plan.json --validate")}

  ${chalk_1.default.gray("# Import and execute PM plan")}
  ${chalk_1.default.cyan("mycontext import-project-plan ./pm-plan.json -o my-project")}

  ${chalk_1.default.gray("# Import with custom output directory")}
  ${chalk_1.default.cyan("mycontext import-project-plan ./pm-plan.json --output ./projects/my-app --skip-confirmation")}

${chalk_1.default.yellow("Integration with mycontext PM:")}
  This command enables seamless integration between mycontext PM planning and MyContext code generation.
  mycontext PM can generate structured project plans that MyContext automatically converts into
  production-ready applications.

${chalk_1.default.yellow("Next Steps After Import:")}
  1. Navigate to the generated project directory
  2. Install dependencies: pnpm install
  3. Start development: pnpm dev
  4. Review and customize generated components
  5. Sync progress back to mycontext PM using export-progress
`;
    }
}
exports.ImportProjectPlanCommand = ImportProjectPlanCommand;
//# sourceMappingURL=import-project-plan.js.map