"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GlobalValidationSettings = exports.PreCommandValidator = void 0;
exports.withValidation = withValidation;
const ProjectStructureValidator_1 = require("./ProjectStructureValidator");
const chalk_1 = __importDefault(require("chalk"));
class PreCommandValidator {
    constructor(projectRoot, options) {
        this.autoFixEnabled = true;
        this.strictMode = false;
        this.validator = new ProjectStructureValidator_1.ProjectStructureValidator(projectRoot);
        this.autoFixEnabled = options?.autoFix ?? true;
        this.strictMode = options?.strict ?? false;
    }
    /**
     * Validate project structure before running any command
     */
    async validateBeforeCommand(command) {
        console.log(chalk_1.default.blue(`🔍 Validating project structure before: ${command}`));
        const report = await this.validator.validate();
        if (report.isValid) {
            console.log(chalk_1.default.green("✅ Project structure is healthy"));
            return { passed: true, report, autoFixed: false };
        }
        console.log(chalk_1.default.yellow(`⚠️  Found ${report.issues.length} project structure issues`));
        // Show critical issues immediately
        const criticalIssues = report.issues.filter(issue => issue.severity === "critical");
        if (criticalIssues.length > 0) {
            console.log(chalk_1.default.red("\n🚨 Critical Issues Found:"));
            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}`));
            });
        }
        // Attempt auto-fix if enabled
        let autoFixed = false;
        if (this.autoFixEnabled && report.autoFixable) {
            console.log(chalk_1.default.blue("\n🔧 Attempting to auto-fix issues..."));
            const fixResult = await this.validator.autoFix();
            if (fixResult.fixed > 0) {
                console.log(chalk_1.default.green(`✅ Auto-fixed ${fixResult.fixed} issues`));
                autoFixed = true;
                // Re-validate after fixes
                const newReport = await this.validator.validate();
                if (newReport.isValid) {
                    console.log(chalk_1.default.green("✅ All issues resolved!"));
                    return { passed: true, report: newReport, autoFixed: true };
                }
            }
            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}`));
                });
            }
        }
        // Handle remaining issues based on strict mode
        if (this.strictMode) {
            console.log(chalk_1.default.red("\n🚫 Strict mode enabled - blocking command execution"));
            console.log(chalk_1.default.yellow("Run 'mycontext health-check --fix' to resolve issues"));
            return { passed: false, report, autoFixed };
        }
        else {
            console.log(chalk_1.default.yellow("\n⚠️  Continuing with warnings..."));
            console.log(chalk_1.default.yellow("Run 'mycontext health-check' for detailed report"));
            return { passed: true, report, autoFixed };
        }
    }
    /**
     * Add validation hooks to a Commander command
     */
    static addValidationHook(command, options) {
        const validator = new PreCommandValidator(undefined, options);
        command.hook('preAction', async (thisCommand, actionCommand) => {
            const commandName = `${actionCommand.name()} ${actionCommand.args.join(' ')}`.trim();
            try {
                const result = await validator.validateBeforeCommand(commandName);
                if (!result.passed) {
                    console.log(chalk_1.default.red("\n❌ Command blocked due to project structure issues"));
                    process.exit(1);
                }
                if (result.autoFixed) {
                    console.log(chalk_1.default.green("\n✅ Project structure issues auto-fixed, continuing..."));
                }
            }
            catch (error) {
                console.log(chalk_1.default.red(`❌ Validation failed: ${error}`));
                if (options?.strict) {
                    process.exit(1);
                }
            }
        });
    }
    /**
     * Validate specific command types with custom rules
     */
    async validateForCommandType(commandType) {
        const report = await this.validator.validate();
        // Add command-specific validation rules
        switch (commandType) {
            case "generate":
                return this.validateForGenerate(report);
            case "build":
                return this.validateForBuild(report);
            case "test":
                return this.validateForTest(report);
            case "deploy":
                return this.validateForDeploy(report);
            default:
                return this.validateBeforeCommand(commandType);
        }
    }
    async validateForGenerate(report) {
        // For generate commands, we need a clean structure
        const criticalIssues = report.issues.filter(issue => issue.severity === "critical");
        if (criticalIssues.length > 0) {
            console.log(chalk_1.default.red("🚫 Cannot generate components with critical project structure issues"));
            return { passed: false, report, autoFixed: false };
        }
        return this.validateBeforeCommand("generate");
    }
    async validateForBuild(report) {
        // For build commands, we need proper configuration
        const configIssues = report.issues.filter(issue => issue.message.includes("configuration") ||
            issue.message.includes("package.json") ||
            issue.message.includes("lock file"));
        if (configIssues.length > 0) {
            console.log(chalk_1.default.red("🚫 Cannot build with configuration issues"));
            return { passed: false, report, autoFixed: false };
        }
        return this.validateBeforeCommand("build");
    }
    async validateForTest(report) {
        // For test commands, we need dependencies installed
        const dependencyIssues = report.issues.filter(issue => issue.message.includes("node_modules") ||
            issue.message.includes("dependencies"));
        if (dependencyIssues.length > 0) {
            console.log(chalk_1.default.red("🚫 Cannot run tests with dependency issues"));
            return { passed: false, report, autoFixed: false };
        }
        return this.validateBeforeCommand("test");
    }
    async validateForDeploy(report) {
        // For deploy commands, we need a completely clean structure
        if (!report.isValid) {
            console.log(chalk_1.default.red("🚫 Cannot deploy with project structure issues"));
            console.log(chalk_1.default.yellow("Run 'mycontext health-check --fix' to resolve issues"));
            return { passed: false, report, autoFixed: false };
        }
        return this.validateBeforeCommand("deploy");
    }
    /**
     * Enable/disable auto-fix
     */
    setAutoFix(enabled) {
        this.autoFixEnabled = enabled;
    }
    /**
     * Enable/disable strict mode
     */
    setStrictMode(enabled) {
        this.strictMode = enabled;
    }
    /**
     * Get current validation settings
     */
    getSettings() {
        return {
            autoFix: this.autoFixEnabled,
            strict: this.strictMode
        };
    }
}
exports.PreCommandValidator = PreCommandValidator;
/**
 * Decorator function to add validation to commands
 */
function withValidation(options) {
    return function (target, propertyKey, descriptor) {
        const originalMethod = descriptor.value;
        descriptor.value = async function (...args) {
            const validator = new PreCommandValidator(undefined, options);
            const commandName = `${target.constructor.name}.${propertyKey}`;
            try {
                const result = await validator.validateBeforeCommand(commandName);
                if (!result.passed) {
                    console.log(chalk_1.default.red("\n❌ Command blocked due to project structure issues"));
                    return;
                }
                if (result.autoFixed) {
                    console.log(chalk_1.default.green("\n✅ Project structure issues auto-fixed, continuing..."));
                }
                return originalMethod.apply(this, args);
            }
            catch (error) {
                console.log(chalk_1.default.red(`❌ Validation failed: ${error}`));
                if (options?.strict) {
                    return;
                }
                return originalMethod.apply(this, args);
            }
        };
        return descriptor;
    };
}
/**
 * Global validation settings
 */
class GlobalValidationSettings {
    constructor() {
        this.autoFixEnabled = true;
        this.strictMode = false;
        this.validationEnabled = true;
    }
    static getInstance() {
        if (!GlobalValidationSettings.instance) {
            GlobalValidationSettings.instance = new GlobalValidationSettings();
        }
        return GlobalValidationSettings.instance;
    }
    setAutoFix(enabled) {
        this.autoFixEnabled = enabled;
    }
    setStrictMode(enabled) {
        this.strictMode = enabled;
    }
    setValidationEnabled(enabled) {
        this.validationEnabled = enabled;
    }
    getSettings() {
        return {
            autoFix: this.autoFixEnabled,
            strict: this.strictMode,
            enabled: this.validationEnabled
        };
    }
    createValidator(projectRoot) {
        return new PreCommandValidator(projectRoot, {
            autoFix: this.autoFixEnabled,
            strict: this.strictMode
        });
    }
}
exports.GlobalValidationSettings = GlobalValidationSettings;
//# sourceMappingURL=PreCommandValidator.js.map