"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.HealthCheckCommand = void 0;
exports.quickHealthCheck = quickHealthCheck;
exports.healthCheckWithFix = healthCheckWithFix;
const chalk_1 = __importDefault(require("chalk"));
const ProjectStructureValidator_1 = require("../utils/ProjectStructureValidator");
const PreCommandValidator_1 = require("../utils/PreCommandValidator");
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
class HealthCheckCommand {
    constructor() {
        this.validator = new ProjectStructureValidator_1.ProjectStructureValidator();
    }
    register(program) {
        const healthCheckCommand = program
            .command("health-check")
            .description("Check and fix project structure issues")
            .option("-f, --fix", "Automatically fix issues where possible")
            .option("-r, --report", "Generate detailed health report")
            .option("-s, --strict", "Enable strict mode (block commands on issues)")
            .option("-o, --output <file>", "Output report to file")
            .option("--no-auto-fix", "Disable automatic fixing")
            .action(async (options) => {
            await this.run(options);
        });
        // Add validation hook to this command itself
        PreCommandValidator_1.PreCommandValidator.addValidationHook(healthCheckCommand, {
            autoFix: false,
            strict: false,
        });
    }
    async run(options) {
        console.log(chalk_1.default.blue("🏥 MyContext Project Health Check"));
        console.log(chalk_1.default.blue("================================\n"));
        try {
            // Run validation
            const report = await this.validator.validate();
            // Display results
            this.displayResults(report, options);
            // Auto-fix if requested
            if (options.fix || options.autoFix !== false) {
                await this.handleAutoFix(report, options);
            }
            // Generate report if requested
            if (options.report || options.output) {
                await this.generateReport(report, options);
            }
            // Set global validation settings
            if (options.strict !== undefined) {
                const { GlobalValidationSettings } = await Promise.resolve().then(() => __importStar(require("../utils/PreCommandValidator")));
                const settings = GlobalValidationSettings.getInstance();
                settings.setStrictMode(options.strict);
                console.log(chalk_1.default.blue(`\n🔧 Global strict mode: ${options.strict ? "enabled" : "disabled"}`));
            }
            // Exit with appropriate code
            if (!report.isValid && options.strict) {
                console.log(chalk_1.default.red("\n❌ Health check failed in strict mode"));
                process.exit(1);
            }
            else if (!report.isValid) {
                console.log(chalk_1.default.yellow("\n⚠️  Health check completed with warnings"));
                process.exit(0);
            }
            else {
                console.log(chalk_1.default.green("\n✅ Health check passed"));
                process.exit(0);
            }
        }
        catch (error) {
            console.log(chalk_1.default.red(`❌ Health check failed: ${error}`));
            process.exit(1);
        }
    }
    displayResults(report, options) {
        console.log(chalk_1.default.blue("📊 Project Metrics:"));
        console.log(`   Package files: ${report.metrics.packageJsonCount}`);
        console.log(`   Node modules: ${report.metrics.nodeModulesCount}`);
        console.log(`   Lock files: ${report.metrics.lockFileCount}`);
        console.log(`   TypeScript configs: ${report.metrics.tsConfigCount}`);
        console.log(`   Build configs: ${report.metrics.buildConfigCount}`);
        console.log(`   Project depth: ${report.metrics.projectDepth}`);
        // Next.js specific metrics
        if (report.nextjsCompliant !== undefined) {
            console.log(`   Next.js App Router: ${report.nextjsCompliant ? chalk_1.default.green("✅ Compliant") : chalk_1.default.red("❌ Issues")}`);
        }
        if (report.shadcnCompliant !== undefined) {
            console.log(`   shadcn/ui Integration: ${report.shadcnCompliant ? chalk_1.default.green("✅ Compliant") : chalk_1.default.red("❌ Issues")}`);
        }
        console.log();
        console.log(chalk_1.default.blue("🏥 Health Status:"));
        if (report.isValid) {
            console.log(chalk_1.default.green("   ✅ HEALTHY - No issues found"));
        }
        else {
            console.log(chalk_1.default.red(`   ❌ NEEDS ATTENTION - ${report.issues.length} issues found`));
        }
        if (report.issues.length > 0) {
            console.log(chalk_1.default.blue("\n🚨 Issues Found:"));
            const criticalIssues = report.issues.filter((issue) => issue.severity === "critical");
            const highIssues = report.issues.filter((issue) => issue.severity === "high");
            const mediumIssues = report.issues.filter((issue) => issue.severity === "medium");
            const lowIssues = report.issues.filter((issue) => issue.severity === "low");
            if (criticalIssues.length > 0) {
                console.log(chalk_1.default.red("\n   Critical Issues:"));
                criticalIssues.forEach((issue) => {
                    console.log(chalk_1.default.red(`   ❌ ${issue.message}`));
                    if (issue.file)
                        console.log(chalk_1.default.gray(`      File: ${issue.file}`));
                    if (issue.fix)
                        console.log(chalk_1.default.gray(`      Fix: ${issue.fix}`));
                });
            }
            if (highIssues.length > 0) {
                console.log(chalk_1.default.red("\n   High Priority Issues:"));
                highIssues.forEach((issue) => {
                    console.log(chalk_1.default.red(`   ⚠️  ${issue.message}`));
                    if (issue.file)
                        console.log(chalk_1.default.gray(`      File: ${issue.file}`));
                    if (issue.fix)
                        console.log(chalk_1.default.gray(`      Fix: ${issue.fix}`));
                });
            }
            if (mediumIssues.length > 0) {
                console.log(chalk_1.default.yellow("\n   Medium Priority Issues:"));
                mediumIssues.forEach((issue) => {
                    console.log(chalk_1.default.yellow(`   ⚠️  ${issue.message}`));
                    if (issue.file)
                        console.log(chalk_1.default.gray(`      File: ${issue.file}`));
                    if (issue.fix)
                        console.log(chalk_1.default.gray(`      Fix: ${issue.fix}`));
                });
            }
            if (lowIssues.length > 0) {
                console.log(chalk_1.default.blue("\n   Low Priority Issues:"));
                lowIssues.forEach((issue) => {
                    console.log(chalk_1.default.blue(`   ℹ️  ${issue.message}`));
                    if (issue.file)
                        console.log(chalk_1.default.gray(`      File: ${issue.file}`));
                    if (issue.fix)
                        console.log(chalk_1.default.gray(`      Fix: ${issue.fix}`));
                });
            }
        }
        if (report.recommendations.length > 0) {
            console.log(chalk_1.default.blue("\n💡 Recommendations:"));
            report.recommendations.forEach((rec) => {
                console.log(chalk_1.default.blue(`   • ${rec}`));
            });
        }
        console.log(chalk_1.default.blue(`\n🔧 Auto-fix available: ${report.autoFixable ? "Yes" : "No"}`));
    }
    async handleAutoFix(report, options) {
        if (!report.autoFixable) {
            console.log(chalk_1.default.yellow("\n⚠️  No auto-fixable issues found"));
            return;
        }
        console.log(chalk_1.default.blue("\n🔧 Attempting to auto-fix issues..."));
        try {
            const fixResult = await this.validator.autoFix();
            if (fixResult.fixed > 0) {
                console.log(chalk_1.default.green(`✅ Successfully fixed ${fixResult.fixed} issues`));
            }
            if (fixResult.failed > 0) {
                console.log(chalk_1.default.red(`❌ Failed to fix ${fixResult.failed} issues:`));
                fixResult.errors.forEach((error) => {
                    console.log(chalk_1.default.red(`   ${error}`));
                });
            }
            if (fixResult.fixed === 0 && fixResult.failed === 0) {
                console.log(chalk_1.default.yellow("ℹ️  No issues were auto-fixable"));
            }
        }
        catch (error) {
            console.log(chalk_1.default.red(`❌ Auto-fix failed: ${error}`));
        }
    }
    async generateReport(report, options) {
        try {
            const reportContent = await this.validator.generateHealthReport();
            if (options.output) {
                const outputPath = path.resolve(options.output);
                await fs.writeFile(outputPath, reportContent);
                console.log(chalk_1.default.green(`\n📄 Health report saved to: ${outputPath}`));
            }
            else {
                const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
                const reportPath = path.join(process.cwd(), `health-report-${timestamp}.md`);
                await fs.writeFile(reportPath, reportContent);
                console.log(chalk_1.default.green(`\n📄 Health report saved to: ${reportPath}`));
            }
        }
        catch (error) {
            console.log(chalk_1.default.red(`❌ Failed to generate report: ${error}`));
        }
    }
}
exports.HealthCheckCommand = HealthCheckCommand;
/**
 * Quick health check function for programmatic use
 */
async function quickHealthCheck(projectRoot) {
    try {
        const validator = new ProjectStructureValidator_1.ProjectStructureValidator(projectRoot);
        const report = await validator.validate();
        return report.isValid;
    }
    catch (error) {
        console.error(`Health check failed: ${error}`);
        return false;
    }
}
/**
 * Health check with auto-fix
 */
async function healthCheckWithFix(projectRoot) {
    try {
        const validator = new ProjectStructureValidator_1.ProjectStructureValidator(projectRoot);
        const report = await validator.validate();
        if (report.isValid) {
            return { healthy: true, fixed: 0 };
        }
        if (report.autoFixable) {
            const fixResult = await validator.autoFix();
            const newReport = await validator.validate();
            return { healthy: newReport.isValid, fixed: fixResult.fixed };
        }
        return { healthy: false, fixed: 0 };
    }
    catch (error) {
        console.error(`Health check with fix failed: ${error}`);
        return { healthy: false, fixed: 0 };
    }
}
//# sourceMappingURL=health-check.js.map