"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.predict = exports.PredictCommand = void 0;
const commander_1 = require("commander");
const chalk_1 = __importDefault(require("chalk"));
const ProjectIntelligence_1 = require("../agents/intelligence/ProjectIntelligence");
const spinner_1 = require("../utils/spinner");
const contextLoader_1 = require("../utils/contextLoader");
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
class PredictCommand {
    constructor() {
        this.intelligence = new ProjectIntelligence_1.ProjectIntelligenceEngine();
    }
    async execute(action, options) {
        const spinner = new spinner_1.EnhancedSpinner(`🔮 Predicting ${action}...`);
        try {
            spinner.start();
            // Load project context for better predictions
            const contextLoader = new contextLoader_1.ContextLoader();
            const projectContext = await contextLoader.loadProjectContext({
                verbose: options.verbose || false,
                required: false,
            });
            if (options.verbose) {
                const summary = contextLoader.getContextSummary(projectContext);
                console.log(chalk_1.default.gray(`📁 Context: ${summary}`));
            }
            // Analyze current project state
            const projectState = await this.intelligence.analyzeProject();
            let predictions;
            switch (action) {
                case "next":
                    predictions = await this.predictNextSteps(projectState, options);
                    break;
                case "dependencies":
                    predictions = await this.predictDependencies(projectState, options);
                    break;
                case "patterns":
                    predictions = await this.predictPatterns(projectState, options);
                    break;
                case "issues":
                    predictions = await this.predictIssues(projectState, options);
                    break;
                case "optimization":
                    predictions = await this.predictOptimizations(projectState, options);
                    break;
                default:
                    predictions = await this.predictGeneral(projectState, options);
            }
            spinner.success({ text: `Predictions generated for ${action}` });
            // Display predictions
            await this.displayPredictions(action, predictions, options);
            // Save predictions for learning
            await this.savePredictions(action, predictions);
        }
        catch (error) {
            spinner.error({ text: `Prediction failed: ${error.message}` });
            throw error;
        }
    }
    async predictNextSteps(projectState, options) {
        const predictions = {
            immediateActions: [],
            suggestedComponents: [],
            architecturalNeeds: [],
            dependencies: [],
            confidence: 0,
        };
        // Analyze current components to predict next needs
        const components = await this.getExistingComponents();
        const patterns = projectState.architecturalPatterns;
        // Predict based on common patterns
        if (this.hasComponent(components, "ProductCard") &&
            !this.hasComponent(components, "CartDialog")) {
            predictions.suggestedComponents.push({
                name: "CartDialog",
                reason: "ProductCard typically needs shopping cart functionality",
                confidence: 0.85,
                priority: "high",
            });
        }
        if (this.hasComponent(components, "LoginForm") &&
            !this.hasComponent(components, "AuthGuard")) {
            predictions.suggestedComponents.push({
                name: "AuthGuard",
                reason: "Authentication forms need route protection",
                confidence: 0.9,
                priority: "high",
            });
        }
        if (this.hasComponent(components, "DataTable") &&
            !this.hasComponent(components, "FilterPanel")) {
            predictions.suggestedComponents.push({
                name: "FilterPanel",
                reason: "Data tables benefit from filtering capabilities",
                confidence: 0.8,
                priority: "medium",
            });
        }
        // Predict architectural needs
        if (components.length > 10 &&
            !patterns.some((p) => p.name.includes("context"))) {
            predictions.architecturalNeeds.push({
                pattern: "State Management",
                reason: "Large component count suggests need for centralized state",
                confidence: 0.75,
                suggestion: "Consider Context API or state management library",
            });
        }
        if (patterns.some((p) => p.name.includes("api")) &&
            !this.hasPattern(patterns, "error-boundaries")) {
            predictions.architecturalNeeds.push({
                pattern: "Error Boundaries",
                reason: "API usage requires proper error handling",
                confidence: 0.8,
                suggestion: "Implement error boundaries for API components",
            });
        }
        // Predict immediate actions
        const recentFiles = projectState.codebaseAwareness.files
            .filter((f) => this.isRecentlyModified(f.lastModified))
            .sort((a, b) => b.lastModified.getTime() - a.lastModified.getTime());
        if (recentFiles.length > 0) {
            const latestFile = recentFiles[0];
            if (latestFile.type === "component" && !this.hasTests(latestFile.path)) {
                predictions.immediateActions.push({
                    action: "Generate Tests",
                    target: latestFile.path,
                    reason: "Recently created component needs test coverage",
                    confidence: 0.9,
                });
            }
        }
        // Calculate overall confidence
        predictions.confidence = this.calculateAverageConfidence([
            ...predictions.suggestedComponents,
            ...predictions.architecturalNeeds,
            ...predictions.immediateActions,
        ]);
        return predictions;
    }
    async predictDependencies(projectState, options) {
        const predictions = {
            needed: [],
            upgrades: [],
            potential_conflicts: [],
            optimization: [],
        };
        const components = await this.getExistingComponents();
        const existingDeps = await this.getPackageDependencies();
        // Predict needed dependencies based on components
        for (const component of components) {
            if (component.name.includes("Chart") &&
                !existingDeps.includes("recharts")) {
                predictions.needed.push({
                    package: "recharts",
                    reason: "Chart components typically need charting library",
                    confidence: 0.8,
                    alternative: "chart.js",
                });
            }
            if (component.name.includes("Form") &&
                !existingDeps.includes("react-hook-form")) {
                predictions.needed.push({
                    package: "react-hook-form",
                    reason: "Form components benefit from form management library",
                    confidence: 0.7,
                    alternative: "formik",
                });
            }
            if (component.name.includes("Animation") &&
                !existingDeps.includes("framer-motion")) {
                predictions.needed.push({
                    package: "framer-motion",
                    reason: "Animation components need animation library",
                    confidence: 0.85,
                    alternative: "react-spring",
                });
            }
        }
        // Predict potential optimization opportunities
        if (existingDeps.includes("lodash") &&
            !existingDeps.includes("lodash-es")) {
            predictions.optimization.push({
                change: "Switch to lodash-es",
                reason: "Better tree-shaking and smaller bundle size",
                confidence: 0.9,
                impact: "Bundle size reduction",
            });
        }
        if (existingDeps.includes("moment") && !existingDeps.includes("date-fns")) {
            predictions.optimization.push({
                change: "Replace moment with date-fns",
                reason: "Smaller bundle size and better performance",
                confidence: 0.8,
                impact: "Significant bundle size reduction",
            });
        }
        return predictions;
    }
    async predictPatterns(projectState, options) {
        const predictions = {
            emerging: [],
            recommended: [],
            antipatterns: [],
            modernization: [],
        };
        const patterns = projectState.architecturalPatterns;
        const components = await this.getExistingComponents();
        // Predict emerging patterns
        if (this.hasPattern(patterns, "react-hooks") && patterns.length > 5) {
            predictions.emerging.push({
                pattern: "Custom Hooks",
                reason: "Multiple components with hooks suggest need for custom hooks",
                confidence: 0.75,
                benefit: "Code reusability and separation of concerns",
            });
        }
        // Predict recommended patterns
        if (components.some((c) => c.name.includes("Modal")) &&
            !this.hasPattern(patterns, "portal-pattern")) {
            predictions.recommended.push({
                pattern: "Portal Pattern",
                reason: "Modal components should use React portals",
                confidence: 0.9,
                implementation: "Use ReactDOM.createPortal for modals",
            });
        }
        // Detect potential antipatterns
        const highComplexityComponents = projectState.codebaseAwareness.files.filter((f) => f.complexity > 15);
        if (highComplexityComponents.length > 0) {
            predictions.antipatterns.push({
                pattern: "God Components",
                files: highComplexityComponents.map((f) => f.path),
                reason: "Components with high complexity violate single responsibility",
                confidence: 0.8,
                fix: "Break down into smaller, focused components",
            });
        }
        return predictions;
    }
    async predictIssues(projectState, options) {
        const predictions = {
            performance: [],
            security: [],
            maintainability: [],
            accessibility: [],
        };
        const files = projectState.codebaseAwareness.files;
        // Predict performance issues
        const largeComponents = files.filter((f) => f.complexity > 20);
        if (largeComponents.length > 0) {
            predictions.performance.push({
                issue: "Component Complexity",
                affected: largeComponents.map((f) => f.path),
                severity: "medium",
                prediction: "May cause rendering performance issues",
                confidence: 0.7,
            });
        }
        // Predict security issues
        const formComponents = files.filter((f) => f.patterns.includes("form"));
        if (formComponents.length > 0) {
            predictions.security.push({
                issue: "Input Validation",
                affected: formComponents.map((f) => f.path),
                severity: "high",
                prediction: "Forms need input validation and sanitization",
                confidence: 0.85,
            });
        }
        // Predict maintainability issues
        const outdatedPatterns = projectState.architecturalPatterns.filter((p) => this.isOutdatedPattern(p.name));
        if (outdatedPatterns.length > 0) {
            predictions.maintainability.push({
                issue: "Outdated Patterns",
                patterns: outdatedPatterns.map((p) => p.name),
                severity: "low",
                prediction: "May become harder to maintain as ecosystem evolves",
                confidence: 0.6,
            });
        }
        return predictions;
    }
    async predictOptimizations(projectState, options) {
        const predictions = {
            performance: [],
            bundle: [],
            code_quality: [],
            developer_experience: [],
        };
        // Predict performance optimizations
        const components = await this.getExistingComponents();
        const listComponents = components.filter((c) => c.name.includes("List") ||
            c.name.includes("Table") ||
            c.name.includes("Grid"));
        if (listComponents.length > 0) {
            predictions.performance.push({
                optimization: "Virtualization",
                components: listComponents.map((c) => c.name),
                reason: "Large lists benefit from virtualization",
                confidence: 0.8,
                impact: "Improved rendering performance for large datasets",
            });
        }
        // Predict bundle optimizations
        if (projectState.codebaseAwareness.files.length > 50) {
            predictions.bundle.push({
                optimization: "Code Splitting",
                reason: "Large codebase benefits from route-based code splitting",
                confidence: 0.85,
                impact: "Reduced initial bundle size",
            });
        }
        return predictions;
    }
    async predictGeneral(projectState, options) {
        // Combine all prediction types for general overview
        const nextSteps = await this.predictNextSteps(projectState, options);
        const dependencies = await this.predictDependencies(projectState, options);
        const patterns = await this.predictPatterns(projectState, options);
        const issues = await this.predictIssues(projectState, options);
        const optimizations = await this.predictOptimizations(projectState, options);
        return {
            summary: {
                nextSteps: nextSteps.suggestedComponents.length,
                dependencies: dependencies.needed.length,
                patterns: patterns.recommended.length,
                potential_issues: issues.performance.length + issues.security.length,
                optimizations: optimizations.performance.length + optimizations.bundle.length,
            },
            top_recommendations: [
                ...nextSteps.suggestedComponents.slice(0, 2),
                ...dependencies.needed.slice(0, 2),
                ...patterns.recommended.slice(0, 2),
            ].sort((a, b) => (b.confidence || 0) - (a.confidence || 0)),
        };
    }
    async displayPredictions(action, predictions, options) {
        console.log(chalk_1.default.blue.bold(`\n🔮 Predictions for: ${action}\n`));
        if (action === "next" || action === "general") {
            this.displayNextStepPredictions(predictions);
        }
        if (action === "dependencies") {
            this.displayDependencyPredictions(predictions);
        }
        if (action === "patterns") {
            this.displayPatternPredictions(predictions);
        }
        if (action === "issues") {
            this.displayIssuePredictions(predictions);
        }
        if (action === "optimization") {
            this.displayOptimizationPredictions(predictions);
        }
        if (action === "general") {
            this.displayGeneralSummary(predictions);
        }
        console.log(chalk_1.default.gray(`\n💡 Run 'mycontext predict <specific-type>' for detailed predictions`));
    }
    displayNextStepPredictions(predictions) {
        if (predictions.suggestedComponents?.length > 0) {
            console.log(chalk_1.default.yellow.bold("📦 Suggested Components:"));
            predictions.suggestedComponents.forEach((comp) => {
                const confidence = Math.round(comp.confidence * 100);
                const priority = comp.priority === "high"
                    ? "🔴"
                    : comp.priority === "medium"
                        ? "🟡"
                        : "🟢";
                console.log(`  ${priority} ${chalk_1.default.cyan(comp.name)} (${confidence}% confidence)`);
                console.log(`     ${chalk_1.default.gray(comp.reason)}`);
            });
            console.log();
        }
        if (predictions.immediateActions?.length > 0) {
            console.log(chalk_1.default.red.bold("⚡ Immediate Actions:"));
            predictions.immediateActions.forEach((action) => {
                console.log(`  • ${chalk_1.default.yellow(action.action)}: ${action.target}`);
                console.log(`    ${chalk_1.default.gray(action.reason)}`);
            });
            console.log();
        }
    }
    displayDependencyPredictions(predictions) {
        if (predictions.needed?.length > 0) {
            console.log(chalk_1.default.green.bold("📦 Suggested Dependencies:"));
            predictions.needed.forEach((dep) => {
                const confidence = Math.round(dep.confidence * 100);
                console.log(`  • ${chalk_1.default.cyan(dep.package)} (${confidence}% confidence)`);
                console.log(`    ${chalk_1.default.gray(dep.reason)}`);
                if (dep.alternative) {
                    console.log(`    ${chalk_1.default.gray(`Alternative: ${dep.alternative}`)}`);
                }
            });
            console.log();
        }
    }
    displayPatternPredictions(predictions) {
        if (predictions.recommended?.length > 0) {
            console.log(chalk_1.default.blue.bold("🏗️ Recommended Patterns:"));
            predictions.recommended.forEach((pattern) => {
                console.log(`  • ${chalk_1.default.cyan(pattern.pattern)}`);
                console.log(`    ${chalk_1.default.gray(pattern.reason)}`);
            });
            console.log();
        }
    }
    displayIssuePredictions(predictions) {
        ["performance", "security", "maintainability", "accessibility"].forEach((category) => {
            const issues = predictions[category];
            if (issues?.length > 0) {
                console.log(chalk_1.default.red.bold(`⚠️ Potential ${category.charAt(0).toUpperCase() + category.slice(1)} Issues:`));
                issues.forEach((issue) => {
                    console.log(`  • ${chalk_1.default.yellow(issue.issue)} (${issue.severity})`);
                    console.log(`    ${chalk_1.default.gray(issue.prediction)}`);
                });
                console.log();
            }
        });
    }
    displayOptimizationPredictions(predictions) {
        ["performance", "bundle", "code_quality"].forEach((category) => {
            const opts = predictions[category];
            if (opts?.length > 0) {
                console.log(chalk_1.default.green.bold(`⚡ ${category.charAt(0).toUpperCase() + category.slice(1)} Optimizations:`));
                opts.forEach((opt) => {
                    console.log(`  • ${chalk_1.default.cyan(opt.optimization)}`);
                    console.log(`    ${chalk_1.default.gray(opt.reason)}`);
                    console.log(`    ${chalk_1.default.gray(`Impact: ${opt.impact}`)}`);
                });
                console.log();
            }
        });
    }
    displayGeneralSummary(predictions) {
        console.log(chalk_1.default.blue.bold("📊 Prediction Summary:"));
        console.log(`  Next steps: ${predictions.summary.nextSteps} suggestions`);
        console.log(`  Dependencies: ${predictions.summary.dependencies} recommendations`);
        console.log(`  Patterns: ${predictions.summary.patterns} opportunities`);
        console.log(`  Potential issues: ${predictions.summary.potential_issues} detected`);
        console.log(`  Optimizations: ${predictions.summary.optimizations} available`);
        console.log();
        if (predictions.top_recommendations?.length > 0) {
            console.log(chalk_1.default.yellow.bold("🎯 Top Recommendations:"));
            predictions.top_recommendations
                .slice(0, 3)
                .forEach((rec, idx) => {
                const confidence = rec.confidence
                    ? Math.round(rec.confidence * 100) + "%"
                    : "N/A";
                console.log(`  ${idx + 1}. ${chalk_1.default.cyan(rec.name || rec.package || rec.pattern)} (${confidence})`);
                console.log(`     ${chalk_1.default.gray(rec.reason)}`);
            });
        }
    }
    // Helper methods
    async getExistingComponents() {
        const compListPath = path_1.default.join(process.cwd(), ".mycontext", "04-component-list.json");
        if (await fs_extra_1.default.pathExists(compListPath)) {
            try {
                const compList = await fs_extra_1.default.readJson(compListPath);
                return compList.groups?.flatMap((g) => g.components || []) || [];
            }
            catch {
                return [];
            }
        }
        return [];
    }
    hasComponent(components, name) {
        return components.some((c) => c.name === name);
    }
    hasPattern(patterns, pattern) {
        return patterns.some((p) => p.name.includes(pattern));
    }
    isRecentlyModified(date) {
        const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000);
        return date > threeDaysAgo;
    }
    hasTests(filePath) {
        // Simplified test detection
        return filePath.includes(".test.") || filePath.includes(".spec.");
    }
    async getPackageDependencies() {
        const packagePath = path_1.default.join(process.cwd(), "package.json");
        if (await fs_extra_1.default.pathExists(packagePath)) {
            try {
                const pkg = await fs_extra_1.default.readJson(packagePath);
                return Object.keys({ ...pkg.dependencies, ...pkg.devDependencies });
            }
            catch {
                return [];
            }
        }
        return [];
    }
    isOutdatedPattern(pattern) {
        const outdatedPatterns = ["class-components", "prop-types", "enzyme"];
        return outdatedPatterns.includes(pattern);
    }
    calculateAverageConfidence(items) {
        if (items.length === 0)
            return 0;
        const sum = items.reduce((acc, item) => acc + (item.confidence || 0), 0);
        return sum / items.length;
    }
    async savePredictions(action, predictions) {
        const predictionsPath = path_1.default.join(process.cwd(), ".mycontext", "predictions.json");
        let existingPredictions = {};
        if (await fs_extra_1.default.pathExists(predictionsPath)) {
            try {
                existingPredictions = await fs_extra_1.default.readJson(predictionsPath);
            }
            catch { }
        }
        const newPredictions = {
            ...existingPredictions,
            [action]: {
                timestamp: new Date().toISOString(),
                predictions,
            },
        };
        await fs_extra_1.default.ensureDir(path_1.default.dirname(predictionsPath));
        await fs_extra_1.default.writeJson(predictionsPath, newPredictions, { spaces: 2 });
    }
}
exports.PredictCommand = PredictCommand;
// Command registration
exports.predict = new commander_1.Command("predict")
    .description("🔮 Predict next development steps and opportunities")
    .argument("[action]", "Prediction type: next, dependencies, patterns, issues, optimization", "general")
    .option("--confidence <threshold>", "Minimum confidence threshold (0-1)", "0.5")
    .option("--context <type>", "Context filter (component, api, ui, etc.)")
    .option("--verbose", "Show detailed predictions")
    .action(async (action, options) => {
    try {
        const predictCommand = new PredictCommand();
        await predictCommand.execute(action, options);
    }
    catch (error) {
        console.error(chalk_1.default.red("❌ Prediction failed:"), error.message);
        process.exit(1);
    }
});
//# sourceMappingURL=predict.js.map