"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.ExportProgressCommand = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
class ExportProgressCommand {
    register(program) {
        program
            .command("export-progress")
            .description("Export project progress for mycontext PM synchronization")
            .option("-o, --output <file>", "Output file path", "progress-export.json")
            .option("-f, --format <type>", "Output format: json|summary", "json")
            .option("-w, --webhook <url>", "Webhook URL to send progress to mycontext PM")
            .option("-p, --project-id <id>", "Project ID for mycontext PM sync")
            .option("--verbose", "Detailed output", false)
            .option("--include-tasks", "Include detailed task information", true)
            .option("--include-components", "Include generated components list", true)
            .option("--include-metrics", "Include project metrics", true)
            .action(async (options) => {
            await this.exportProgress(options);
        });
    }
    async exportProgress(options) {
        const { output, format, webhook, projectId, verbose, includeTasks = true, includeComponents = true, includeMetrics = true, } = options;
        console.log(chalk_1.default.blue.bold("📊 Exporting Project Progress\n"));
        try {
            // Load project context
            const projectContext = await this.loadProjectContext();
            // Load current tasks
            const tasks = await this.loadTasks();
            // Analyze generated components
            const components = await this.analyzeComponents();
            // Calculate metrics
            const metrics = this.calculateMetrics(tasks, components);
            // Create mycontext PM output
            const pmOutput = {
                projectId: projectId || projectContext?.projectId || this.generateProjectId(),
                timestamp: new Date().toISOString(),
                status: "success",
                progress: {
                    completedTasks: tasks.filter((t) => t.status === "completed").length,
                    totalTasks: tasks.length,
                    completionPercentage: tasks.length > 0
                        ? (tasks.filter((t) => t.status === "completed").length /
                            tasks.length) *
                            100
                        : 0,
                    currentPhase: this.determineCurrentPhase(tasks),
                    nextMilestone: this.determineNextMilestone(tasks),
                    blockers: this.identifyBlockers(tasks),
                },
                generated: {
                    components: components.componentFiles,
                    pages: components.pageFiles,
                    apiEndpoints: components.apiFiles,
                    tests: components.testFiles,
                },
                errors: [],
                suggestions: this.generateSuggestions(tasks, metrics),
                nextSteps: this.generateNextSteps(tasks, metrics),
            };
            // Output based on format
            if (format === "summary") {
                this.displaySummary(pmOutput, tasks, components, metrics);
            }
            else {
                // Save JSON output
                const outputPath = path_1.default.resolve(output || "progress-export.json");
                fs_1.default.writeFileSync(outputPath, JSON.stringify(pmOutput, null, 2));
                console.log(chalk_1.default.green(`✅ Progress exported to: ${outputPath}`));
                if (verbose) {
                    this.displayDetailedProgress(pmOutput);
                }
            }
            // Send to webhook if specified
            if (webhook) {
                await this.sendToWebhook(webhook, pmOutput);
            }
            // Display key insights
            this.displayInsights(pmOutput);
        }
        catch (error) {
            console.error(chalk_1.default.red("❌ Export failed:"), error instanceof Error ? error.message : "Unknown error");
            if (verbose) {
                console.error(chalk_1.default.red("Full error:"), error);
            }
            throw error;
        }
    }
    async loadProjectContext() {
        const contextPaths = [
            path_1.default.join(process.cwd(), ".mycontext", "project-context.json"),
            path_1.default.join(process.cwd(), ".mycontext", "context.json"),
        ];
        for (const contextPath of contextPaths) {
            if (fs_1.default.existsSync(contextPath)) {
                try {
                    const context = JSON.parse(fs_1.default.readFileSync(contextPath, "utf8"));
                    return context;
                }
                catch (error) {
                    console.warn(chalk_1.default.yellow(`Warning: Could not parse ${contextPath}`));
                }
            }
        }
        console.log(chalk_1.default.yellow("⚠️  No project context found, using defaults"));
        return null;
    }
    async loadTasks() {
        const todosPath = path_1.default.join(process.cwd(), ".mycontext", "todos.json");
        if (fs_1.default.existsSync(todosPath)) {
            try {
                const todos = JSON.parse(fs_1.default.readFileSync(todosPath, "utf8"));
                return Array.isArray(todos) ? todos : [];
            }
            catch (error) {
                console.warn(chalk_1.default.yellow("Warning: Could not parse todos.json"));
            }
        }
        console.log(chalk_1.default.yellow("⚠️  No tasks found"));
        return [];
    }
    async analyzeComponents() {
        const result = {
            componentFiles: [],
            pageFiles: [],
            apiFiles: [],
            testFiles: [],
            totalFiles: 0,
        };
        try {
            // Analyze components directory
            const componentsDir = path_1.default.join(process.cwd(), "components");
            if (fs_1.default.existsSync(componentsDir)) {
                const componentFiles = await this.findFiles(componentsDir, [
                    "**/*.{tsx,ts,jsx,js}",
                ]);
                result.componentFiles = componentFiles.map((f) => path_1.default.relative(process.cwd(), f));
            }
            // Analyze pages/app directory
            const pagesDir = path_1.default.join(process.cwd(), "app");
            const pagesDirAlt = path_1.default.join(process.cwd(), "pages");
            const pageDir = fs_1.default.existsSync(pagesDir)
                ? pagesDir
                : fs_1.default.existsSync(pagesDirAlt)
                    ? pagesDirAlt
                    : null;
            if (pageDir) {
                const pageFiles = await this.findFiles(pageDir, [
                    "**/*.{tsx,ts,jsx,js}",
                ]);
                result.pageFiles = pageFiles.map((f) => path_1.default.relative(process.cwd(), f));
            }
            // Analyze API routes
            const apiDir = path_1.default.join(process.cwd(), "app", "api");
            if (fs_1.default.existsSync(apiDir)) {
                const apiFiles = await this.findFiles(apiDir, ["**/*.{ts,js}"]);
                result.apiFiles = apiFiles.map((f) => path_1.default.relative(process.cwd(), f));
            }
            // Analyze test files
            const testFiles = await this.findFiles(process.cwd(), [
                "**/*.{test,spec}.{tsx,ts,jsx,js}",
            ]);
            result.testFiles = testFiles.map((f) => path_1.default.relative(process.cwd(), f));
            result.totalFiles =
                result.componentFiles.length +
                    result.pageFiles.length +
                    result.apiFiles.length +
                    result.testFiles.length;
        }
        catch (error) {
            console.warn(chalk_1.default.yellow("Warning: Could not analyze components:"), error);
        }
        return result;
    }
    async findFiles(dir, patterns) {
        // Simple file finder - in production, this would use glob properly
        const results = [];
        const walk = (currentDir) => {
            const items = fs_1.default.readdirSync(currentDir);
            for (const item of items) {
                const fullPath = path_1.default.join(currentDir, item);
                const stat = fs_1.default.statSync(fullPath);
                if (stat.isDirectory() &&
                    !item.startsWith(".") &&
                    item !== "node_modules") {
                    walk(fullPath);
                }
                else if (stat.isFile()) {
                    // Simple pattern matching
                    for (const pattern of patterns) {
                        if (this.matchesPattern(fullPath, pattern)) {
                            results.push(fullPath);
                            break;
                        }
                    }
                }
            }
        };
        walk(dir);
        return results;
    }
    matchesPattern(filePath, pattern) {
        // Very basic pattern matching - in production, use proper glob library
        const fileName = path_1.default.basename(filePath);
        const ext = path_1.default.extname(fileName);
        if (pattern.includes("{")) {
            // Handle {tsx,ts,jsx,js} patterns
            const extPattern = pattern.match(/\{([^}]+)\}/)?.[1];
            if (extPattern) {
                const exts = extPattern.split(",");
                return exts.some((e) => fileName.endsWith(`.${e.trim()}`));
            }
        }
        if (pattern.includes(".test") || pattern.includes(".spec")) {
            return fileName.includes(".test") || fileName.includes(".spec");
        }
        return pattern.includes(ext.substring(1));
    }
    calculateMetrics(tasks, components) {
        const completedTasks = tasks.filter((t) => t.status === "completed");
        const inProgressTasks = tasks.filter((t) => t.status === "in_progress");
        const blockedTasks = tasks.filter((t) => t.status === "blocked");
        const estimatedHours = tasks.reduce((sum, t) => sum + (t.estimatedHours || 0), 0);
        const actualHours = completedTasks.reduce((sum, t) => sum + (t.actualHours || 0), 0);
        return {
            totalTasks: tasks.length,
            completedTasks: completedTasks.length,
            inProgressTasks: inProgressTasks.length,
            blockedTasks: blockedTasks.length,
            completionPercentage: tasks.length > 0 ? (completedTasks.length / tasks.length) * 100 : 0,
            estimatedHours,
            actualHours,
            velocity: actualHours > 0 ? completedTasks.length / actualHours : 0,
            componentsGenerated: components.totalFiles,
            testCoverage: components.testFiles.length > 0
                ? (components.testFiles.length /
                    (components.componentFiles.length +
                        components.pageFiles.length)) *
                    100
                : 0,
        };
    }
    determineCurrentPhase(tasks) {
        // Simple phase detection based on task completion patterns
        const completedCount = tasks.filter((t) => t.status === "completed").length;
        const totalCount = tasks.length;
        if (completedCount === 0)
            return "Planning";
        if (completedCount < totalCount * 0.3)
            return "Setup";
        if (completedCount < totalCount * 0.7)
            return "Development";
        if (completedCount < totalCount)
            return "Testing";
        return "Completed";
    }
    determineNextMilestone(tasks) {
        const pendingTasks = tasks.filter((t) => t.status !== "completed");
        if (pendingTasks.length === 0)
            return "Project Complete";
        // Find next high-priority task
        const nextTask = pendingTasks
            .filter((t) => t.priority === "critical" || t.priority === "high")
            .sort((a, b) => {
            const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
            const aPriority = priorityOrder[a.priority] ?? 2;
            const bPriority = priorityOrder[b.priority] ?? 2;
            return aPriority - bPriority;
        })[0];
        return nextTask ? nextTask.title : "Continue development";
    }
    identifyBlockers(tasks) {
        return tasks.filter((t) => t.status === "blocked").map((t) => t.title);
    }
    generateSuggestions(tasks, metrics) {
        const suggestions = [];
        if (metrics.blockedTasks > 0) {
            suggestions.push("Resolve blocked tasks to maintain momentum");
        }
        if (metrics.completionPercentage < 50 && tasks.length > 10) {
            suggestions.push("Consider breaking large tasks into smaller, manageable units");
        }
        if (metrics.testCoverage < 50) {
            suggestions.push("Increase test coverage for better code quality");
        }
        if (metrics.velocity > 0 && metrics.velocity < 0.5) {
            suggestions.push("Consider optimizing development workflow for better velocity");
        }
        return suggestions;
    }
    generateNextSteps(tasks, metrics) {
        const nextSteps = [];
        if (metrics.blockedTasks > 0) {
            nextSteps.push("Address blocked tasks and dependencies");
        }
        const pendingHighPriority = tasks.filter((t) => (t.status === "pending" || t.status === "todo") &&
            (t.priority === "critical" || t.priority === "high"));
        if (pendingHighPriority.length > 0) {
            nextSteps.push(`Focus on ${pendingHighPriority.length} high-priority tasks`);
        }
        if (metrics.testCoverage < 70) {
            nextSteps.push("Add unit tests for generated components");
        }
        if (metrics.completionPercentage < 100) {
            nextSteps.push("Continue development on remaining tasks");
        }
        return nextSteps;
    }
    displaySummary(pmOutput, tasks, components, metrics) {
        console.log(chalk_1.default.blue.bold("📊 Project Progress Summary"));
        console.log(chalk_1.default.gray("─".repeat(50)));
        console.log(chalk_1.default.cyan("🎯 Progress:"));
        console.log(`   Completion: ${chalk_1.default.white(pmOutput.progress.completionPercentage.toFixed(1))}%`);
        console.log(`   Tasks: ${chalk_1.default.white(pmOutput.progress.completedTasks)}/${pmOutput.progress.totalTasks} completed`);
        console.log(`   Current Phase: ${chalk_1.default.white(pmOutput.progress.currentPhase)}`);
        if (pmOutput.progress.nextMilestone) {
            console.log(`   Next Milestone: ${chalk_1.default.white(pmOutput.progress.nextMilestone)}`);
        }
        console.log(chalk_1.default.cyan("\n📁 Generated Files:"));
        console.log(`   Components: ${chalk_1.default.white(components.componentFiles.length)}`);
        console.log(`   Pages: ${chalk_1.default.white(components.pageFiles.length)}`);
        console.log(`   API Endpoints: ${chalk_1.default.white(components.apiFiles.length)}`);
        console.log(`   Tests: ${chalk_1.default.white(components.testFiles.length)}`);
        console.log(chalk_1.default.cyan("\n📈 Metrics:"));
        console.log(`   Estimated Hours: ${chalk_1.default.white(metrics.estimatedHours)}`);
        console.log(`   Actual Hours: ${chalk_1.default.white(metrics.actualHours)}`);
        if (metrics.velocity > 0) {
            console.log(`   Velocity: ${chalk_1.default.white(metrics.velocity.toFixed(2))} tasks/hour`);
        }
        if (pmOutput.progress.blockers && pmOutput.progress.blockers.length > 0) {
            console.log(chalk_1.default.cyan("\n🚫 Blockers:"));
            pmOutput.progress.blockers.forEach((blocker) => {
                console.log(`   • ${chalk_1.default.red(blocker)}`);
            });
        }
        if (pmOutput.suggestions && pmOutput.suggestions.length > 0) {
            console.log(chalk_1.default.cyan("\n💡 Suggestions:"));
            pmOutput.suggestions.forEach((suggestion) => {
                console.log(`   • ${chalk_1.default.yellow(suggestion)}`);
            });
        }
    }
    displayDetailedProgress(pmOutput) {
        console.log(chalk_1.default.blue.bold("\n📋 Detailed Progress Export"));
        console.log(chalk_1.default.gray("─".repeat(50)));
        console.log(JSON.stringify(pmOutput, null, 2));
    }
    async sendToWebhook(webhookUrl, pmOutput) {
        try {
            console.log(chalk_1.default.gray(`📤 Sending progress to webhook...`));
            // Use PM Integration Service for robust webhook communication
            const { PMIntegrationService } = await Promise.resolve().then(() => __importStar(require("../services/PMIntegrationService")));
            const integrationService = new PMIntegrationService({
                webhookUrl: webhookUrl,
                retryAttempts: 3,
                timeout: 30000,
            });
            await integrationService.exportProgress(pmOutput, webhookUrl);
            console.log(chalk_1.default.green(`✅ Progress sent to mycontext PM webhook`));
            console.log(chalk_1.default.gray(`   Webhook: ${webhookUrl}`));
            console.log(chalk_1.default.gray(`   Project: ${pmOutput.projectId}`));
        }
        catch (error) {
            console.warn(chalk_1.default.yellow(`Warning: Could not send to webhook: ${error}`));
            throw error;
        }
    }
    displayInsights(pmOutput) {
        console.log(chalk_1.default.blue.bold("\n🎯 mycontext PM Integration Ready"));
        console.log(chalk_1.default.cyan("🔄 Sync Commands:"));
        console.log(`   ${chalk_1.default.gray("mycontext export-progress --webhook <pm-url>")}`);
        console.log(`   ${chalk_1.default.gray("mycontext sync-with-pm --project-id " + pmOutput.projectId)}`);
        if (pmOutput.nextSteps && pmOutput.nextSteps.length > 0) {
            console.log(chalk_1.default.cyan("\n📋 Recommended Next Steps:"));
            pmOutput.nextSteps.forEach((step, index) => {
                console.log(`   ${index + 1}. ${chalk_1.default.white(step)}`);
            });
        }
    }
    generateProjectId() {
        // Generate a project ID based on current directory and timestamp
        const dirName = path_1.default.basename(process.cwd());
        const timestamp = Date.now();
        return `${dirName}-${timestamp}`;
    }
    static getHelpText() {
        return `
${chalk_1.default.blue.bold("📊 MyContext Export Progress Command")}

${chalk_1.default.yellow("Description:")}
  Export project progress and status for mycontext PM synchronization and monitoring

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

${chalk_1.default.yellow("Options:")}
  -o, --output <file>         Output file path (default: progress-export.json)
  -f, --format <type>         Output format: json|summary (default: json)
  -w, --webhook <url>         Webhook URL to send progress to mycontext PM
  -p, --project-id <id>       Project ID for mycontext PM sync
  --verbose                   Detailed output
  --include-tasks             Include detailed task information (default: true)
  --include-components        Include generated components list (default: true)
  --include-metrics           Include project metrics (default: true)

${chalk_1.default.yellow("Output Formats:")}

${chalk_1.default.cyan("JSON Format:")} Complete structured data for mycontext PM consumption
\`\`\`json
{
  "projectId": "my-project-1234567890",
  "timestamp": "2024-01-15T10:30:00Z",
  "status": "success",
  "progress": {
    "completedTasks": 8,
    "totalTasks": 12,
    "completionPercentage": 66.7,
    "currentPhase": "Development",
    "nextMilestone": "API Integration",
    "blockers": ["Database setup pending"]
  },
  "generated": {
    "components": ["Button.tsx", "Input.tsx", "Card.tsx"],
    "pages": ["Home.tsx", "Dashboard.tsx"],
    "apiEndpoints": ["users.ts", "posts.ts"],
    "tests": ["Button.test.tsx", "Input.test.tsx"]
  },
  "suggestions": [
    "Consider adding error boundaries",
    "Increase test coverage"
  ],
  "nextSteps": [
    "Complete API integration",
    "Add user authentication"
  ]
}
\`\`\`

${chalk_1.default.cyan("Summary Format:")} Human-readable progress report
\`\`\`
📊 Project Progress Summary
──────────────────────────────────────────────────
🎯 Progress:
   Completion: 66.7%
   Tasks: 8/12 completed
   Current Phase: Development
   Next Milestone: API Integration

📁 Generated Files:
   Components: 15
   Pages: 3
   API Endpoints: 5
   Tests: 8

📈 Metrics:
   Estimated Hours: 120
   Actual Hours: 85
   Velocity: 0.094 tasks/hour
\`\`\`

${chalk_1.default.yellow("Examples:")}
  ${chalk_1.default.gray("# Export progress to file")}
  ${chalk_1.default.cyan("mycontext export-progress -o ./progress.json")}

  ${chalk_1.default.gray("# Export summary to console")}
  ${chalk_1.default.cyan("mycontext export-progress --format summary")}

  ${chalk_1.default.gray("# Send progress to mycontext PM webhook")}
  ${chalk_1.default.cyan("mycontext export-progress --webhook https://mycontext-pm.example.com/webhook")}

  ${chalk_1.default.gray("# Export with custom project ID")}
  ${chalk_1.default.cyan("mycontext export-progress --project-id my-project-001")}

${chalk_1.default.yellow("mycontext PM Integration:")}
  This command enables seamless integration between MyContext development workflow
  and mycontext PM monitoring. The exported progress data includes:

  • Task completion status and metrics
  • Generated components and files
  • Project velocity and estimates
  • Blockers and suggestions
  • Next steps and milestones

  mycontext PM can use this data to:
  • Monitor development progress in real-time
  • Provide contextual suggestions and tips
  • Identify blockers and propose solutions
  • Generate status reports and updates
  • Adjust timelines and resource allocation

${chalk_1.default.yellow("Webhook Integration:")}
  When using webhooks, the progress data is automatically sent to your mycontext PM
  system for real-time synchronization. This enables:

  • Live dashboard updates
  • Automated status reporting
  • Proactive issue detection
  • Intelligent resource suggestions

${chalk_1.default.yellow("Automation:")}
  Combine with cron jobs or CI/CD for automatic progress reporting:

  \`\`\`bash
  # Daily progress report
  0 18 * * 1-5 mycontext export-progress --webhook https://pm-ai.example.com/daily

  # CI/CD integration
  mycontext export-progress --webhook https://pm-ai.example.com/ci
  \`\`\`
`;
    }
}
exports.ExportProgressCommand = ExportProgressCommand;
//# sourceMappingURL=export-progress.js.map