"use strict";
// Project State Analyzer
// Analyzes current project state and suggests optimal next steps
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProjectStateAnalyzer = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const chalk_1 = __importDefault(require("chalk"));
class ProjectStateAnalyzer {
    constructor(projectRoot = process.cwd()) {
        this.projectRoot = projectRoot;
    }
    /**
     * Analyze the current project state
     */
    async analyzeProjectState() {
        const myContextPath = path_1.default.join(this.projectRoot, ".mycontext");
        const state = {
            hasMyContext: await fs_extra_1.default.pathExists(myContextPath),
            hasPackageJson: await fs_extra_1.default.pathExists(path_1.default.join(this.projectRoot, "package.json")),
            hasContextFiles: false,
            hasArchitecture: false,
            hasComponents: false,
            hasTests: false,
            hasBuildConfig: false,
            techStack: [],
            completionPercentage: 0,
            nextRecommendedSteps: [],
        };
        if (state.hasMyContext) {
            // Check for context files
            state.hasContextFiles = await this.checkContextFiles(myContextPath);
            // Check for architecture files
            state.hasArchitecture = await this.checkArchitectureFiles(myContextPath);
            // Check for components
            state.hasComponents = await this.checkComponentFiles();
            // Check for tests
            state.hasTests = await this.checkTestFiles();
            // Detect project type and tech stack
            const projectInfo = await this.detectProjectInfo(myContextPath);
            state.projectType = projectInfo.type;
            state.techStack = projectInfo.techStack;
            // Calculate completion percentage
            state.completionPercentage = this.calculateCompletionPercentage(state);
            // Generate next steps
            state.nextRecommendedSteps = await this.generateNextSteps(state);
        }
        return state;
    }
    /**
     * Get workflow suggestions based on current state
     */
    async getWorkflowSuggestions() {
        const state = await this.analyzeProjectState();
        const suggestions = [];
        if (!state.hasMyContext) {
            suggestions.push({
                command: "mycontext setup-complete --interactive",
                description: "Complete guided project setup with AI assistance",
                priority: "high",
                estimatedTime: "~5 minutes",
                reason: "No MyContext configuration found - project needs initial setup",
            });
            return suggestions;
        }
        if (!state.hasContextFiles) {
            suggestions.push({
                command: "mycontext generate-context-files",
                description: "Generate PRD and feature specifications",
                priority: "high",
                estimatedTime: "~2 minutes",
                reason: "Missing project context and requirements documentation",
            });
        }
        if (!state.hasArchitecture && state.hasContextFiles) {
            suggestions.push({
                command: "mycontext generate architecture --auto-continue",
                description: "Generate complete project architecture",
                priority: "high",
                estimatedTime: "~3 minutes",
                reason: "Project has context but needs technical architecture",
            });
        }
        if (!state.hasComponents && state.hasArchitecture) {
            suggestions.push({
                command: "mycontext generate components",
                description: "Generate component implementations",
                priority: "medium",
                estimatedTime: "~4 minutes",
                reason: "Architecture defined but components need implementation",
            });
        }
        if (!state.hasTests && state.hasComponents) {
            suggestions.push({
                command: "mycontext generate tests",
                description: "Generate comprehensive test suite",
                priority: "medium",
                estimatedTime: "~2 minutes",
                reason: "Components implemented but lack test coverage",
            });
        }
        if (!state.hasBuildConfig) {
            suggestions.push({
                command: "mycontext build-app",
                description: "Build complete application",
                priority: "medium",
                estimatedTime: "~5 minutes",
                reason: "Project ready for final build and deployment preparation",
            });
        }
        // Always suggest help for new users
        if (state.completionPercentage < 50) {
            suggestions.push({
                command: "mycontext --help",
                description: "View all available commands",
                priority: "low",
                estimatedTime: "< 1 minute",
                reason: "Learn about additional available commands",
            });
        }
        return suggestions;
    }
    /**
     * Display project status in a user-friendly format
     */
    async displayProjectStatus() {
        const state = await this.analyzeProjectState();
        console.log(chalk_1.default.blue.bold("\n📊 Project Status Analysis\n"));
        // Overall completion
        const completionBar = this.createProgressBar(state.completionPercentage, 30);
        console.log(`Completion: ${completionBar} ${state.completionPercentage}%`);
        // Project details
        if (state.projectType) {
            console.log(`Type: ${chalk_1.default.white(state.projectType)} project`);
        }
        if (state.techStack.length > 0) {
            console.log(`Tech Stack: ${chalk_1.default.white(state.techStack.join(", "))}`);
        }
        console.log("");
        // Status checklist
        console.log(chalk_1.default.cyan("📋 Current Status:"));
        this.displayChecklistItem("MyContext setup", state.hasMyContext);
        this.displayChecklistItem("Package.json", state.hasPackageJson);
        this.displayChecklistItem("Context files (PRD, features)", state.hasContextFiles);
        this.displayChecklistItem("Project architecture", state.hasArchitecture);
        this.displayChecklistItem("Component implementations", state.hasComponents);
        this.displayChecklistItem("Test coverage", state.hasTests);
        this.displayChecklistItem("Build configuration", state.hasBuildConfig);
        // Next steps
        if (state.nextRecommendedSteps.length > 0) {
            console.log(chalk_1.default.cyan("\n🎯 Recommended Next Steps:"));
            for (const step of state.nextRecommendedSteps.slice(0, 3)) {
                console.log(`   • ${chalk_1.default.yellow(step)}`);
            }
            if (state.nextRecommendedSteps.length > 3) {
                console.log(`   • ... and ${state.nextRecommendedSteps.length - 3} more suggestions`);
            }
        }
        console.log("");
    }
    async checkContextFiles(myContextPath) {
        const contextFiles = ["01-prd.md", "01a-features.md", "02-types.ts"];
        for (const file of contextFiles) {
            if (await fs_extra_1.default.pathExists(path_1.default.join(myContextPath, file))) {
                return true;
            }
        }
        return false;
    }
    async checkArchitectureFiles(myContextPath) {
        const archFiles = [
            "03-branding.md",
            "04-component-list.json",
            "05-project-structure.md",
        ];
        for (const file of archFiles) {
            if (await fs_extra_1.default.pathExists(path_1.default.join(myContextPath, file))) {
                return true;
            }
        }
        return false;
    }
    async checkComponentFiles() {
        try {
            const componentsPath = path_1.default.join(this.projectRoot, "components");
            return ((await fs_extra_1.default.pathExists(componentsPath)) &&
                (await fs_extra_1.default.readdir(componentsPath)).length > 0);
        }
        catch {
            return false;
        }
    }
    async checkTestFiles() {
        try {
            const testPath = path_1.default.join(this.projectRoot, "__tests__");
            const hasTests = (await fs_extra_1.default.pathExists(testPath)) &&
                (await fs_extra_1.default.readdir(testPath)).length > 0;
            // Also check for test files in components
            const componentsPath = path_1.default.join(this.projectRoot, "components");
            if (await fs_extra_1.default.pathExists(componentsPath)) {
                const componentFiles = await fs_extra_1.default.readdir(componentsPath);
                const hasTestFiles = componentFiles.some((file) => file.includes(".test.") || file.includes(".spec."));
                return hasTests || hasTestFiles;
            }
            return hasTests;
        }
        catch {
            return false;
        }
    }
    async detectProjectInfo(myContextPath) {
        const result = {
            type: undefined,
            techStack: [],
        };
        try {
            // Try to detect from PRD or features
            const prdPath = path_1.default.join(myContextPath, "01-prd.md");
            if (await fs_extra_1.default.pathExists(prdPath)) {
                const content = await fs_extra_1.default.readFile(prdPath, "utf-8");
                // Detect tech stack mentions
                const techStackKeywords = [
                    "Next.js",
                    "React",
                    "TypeScript",
                    "Tailwind",
                    "Prisma",
                    "Supabase",
                    "PostgreSQL",
                    "MongoDB",
                    "Express",
                    "Node.js",
                    "Vue",
                    "Angular",
                ];
                for (const tech of techStackKeywords) {
                    if (content.toLowerCase().includes(tech.toLowerCase())) {
                        result.techStack.push(tech);
                    }
                }
                // Detect project complexity
                if (content.toLowerCase().includes("complex") ||
                    content.toLowerCase().includes("advanced")) {
                    result.type = "complex";
                }
                else if (content.toLowerCase().includes("dashboard") ||
                    content.toLowerCase().includes("application")) {
                    result.type = "moderate";
                }
                else if (content.toLowerCase().includes("landing") ||
                    content.toLowerCase().includes("portfolio")) {
                    result.type = "simple";
                }
            }
        }
        catch (error) {
            // Ignore errors in detection
        }
        return result;
    }
    calculateCompletionPercentage(state) {
        const checks = [
            state.hasMyContext,
            state.hasPackageJson,
            state.hasContextFiles,
            state.hasArchitecture,
            state.hasComponents,
            state.hasTests,
            state.hasBuildConfig,
        ];
        const completed = checks.filter(Boolean).length;
        return Math.round((completed / checks.length) * 100);
    }
    async generateNextSteps(state) {
        const steps = [];
        if (!state.hasContextFiles) {
            steps.push("Generate project context and requirements");
        }
        if (!state.hasArchitecture && state.hasContextFiles) {
            steps.push("Create technical architecture and component specifications");
        }
        if (!state.hasComponents && state.hasArchitecture) {
            steps.push("Implement component library");
        }
        if (!state.hasTests && state.hasComponents) {
            steps.push("Add comprehensive test coverage");
        }
        if (!state.hasBuildConfig) {
            steps.push("Configure build and deployment settings");
        }
        if (state.completionPercentage === 100) {
            steps.push("Project is complete! Ready for deployment");
        }
        return steps;
    }
    createProgressBar(percentage, width = 20) {
        const filled = Math.round((percentage / 100) * width);
        const empty = width - filled;
        const bar = "█".repeat(filled) + "░".repeat(empty);
        return `[${bar}] ${percentage}%`;
    }
    displayChecklistItem(label, completed) {
        const check = completed ? chalk_1.default.green("✅") : chalk_1.default.gray("⬜");
        console.log(`   ${check} ${label}`);
    }
}
exports.ProjectStateAnalyzer = ProjectStateAnalyzer;
//# sourceMappingURL=ProjectStateAnalyzer.js.map