"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assessArchitectureRisk = assessArchitectureRisk;
const architectureValidation_1 = require("../architectureValidation");
const crossModuleContractViolationRuleIds = new Set(['AP-DEP-004', 'AP-DEP-005']);
const circularDependencyRuleId = 'AP-DEP-008';
function extractTouchedModules(results) {
    const modules = new Set();
    for (const result of results) {
        const sourceFile = (result.sourceFile ?? '').replace(/\\/g, '/').toLowerCase();
        const message = result.message.toLowerCase();
        const sourceModuleMatches = [...sourceFile.matchAll(/\/modules\/([^/]+)/gu)];
        for (const match of sourceModuleMatches) {
            modules.add(match[1]);
        }
        const contractModuleMatches = [...sourceFile.matchAll(/\.archpilot\/contracts\/([^/]+)\.contract\.json/gu)];
        for (const match of contractModuleMatches) {
            modules.add(match[1]);
        }
        const messageModuleMatches = [...message.matchAll(/module\s+'([^']+)'/gu)];
        for (const match of messageModuleMatches) {
            modules.add(match[1]);
        }
    }
    return [...modules].sort((left, right) => left.localeCompare(right));
}
function deriveRiskFactors(validationResults, violationResults, suppressedFindingsCount) {
    const failingResults = validationResults.filter((result) => !result.passed);
    const touchedModules = extractTouchedModules(violationResults);
    return {
        hasArchitectureViolation: violationResults.some((result) => (0, architectureValidation_1.getValidationRuleMetadataById)(result.id).category === 'architecture'),
        hasDependencyViolation: violationResults.some((result) => (0, architectureValidation_1.getValidationRuleMetadataById)(result.id).category === 'dependency'),
        hasCircularDependency: violationResults.some((result) => result.id === circularDependencyRuleId),
        touchesMultipleModules: touchedModules.length > 1,
        missingADR: failingResults.some((result) => result.id === 'AP-ADR-004'),
        hasSuppression: suppressedFindingsCount > 0,
    };
}
function assessArchitectureRisk(validationResults, options) {
    const failingResults = validationResults.filter((result) => !result.passed);
    const violationResults = failingResults.filter((result) => (0, architectureValidation_1.classifyValidationResult)(result).kind === 'violation');
    const suppressedFindingsCount = options?.suppressedResults?.length ?? 0;
    const factors = deriveRiskFactors(validationResults, violationResults, suppressedFindingsCount);
    const violationCount = violationResults.length;
    const hasCrossModuleContractViolation = violationResults.some((result) => crossModuleContractViolationRuleIds.has(result.id));
    const criticalReasons = [];
    if (factors.hasCircularDependency) {
        criticalReasons.push('Transitive circular dependency detected (AP-DEP-008).');
    }
    if (hasCrossModuleContractViolation) {
        criticalReasons.push('Cross-module contract violation detected (AP-DEP-004/AP-DEP-005).');
    }
    if (criticalReasons.length > 0) {
        return {
            level: 'critical',
            reasons: criticalReasons,
        };
    }
    const highReasons = [];
    if (violationCount > 1) {
        highReasons.push('Multiple architecture violations are present.');
    }
    if (factors.touchesMultipleModules && violationCount > 0) {
        highReasons.push('Violations span multiple modules.');
    }
    if (factors.missingADR && (factors.hasArchitectureViolation || factors.hasDependencyViolation)) {
        highReasons.push('Missing ADR coverage for structural architecture changes.');
    }
    if (highReasons.length > 0) {
        return {
            level: 'high',
            reasons: highReasons,
        };
    }
    const moderateReasons = [];
    if (violationCount === 1) {
        moderateReasons.push('Single architecture violation detected.');
    }
    if (factors.hasSuppression) {
        moderateReasons.push('Suppressed violations are present.');
    }
    if (moderateReasons.length > 0) {
        return {
            level: 'moderate',
            reasons: moderateReasons,
        };
    }
    const hasOnlySetupOrGuidanceFindings = failingResults.length === 0 ||
        failingResults.every((result) => (0, architectureValidation_1.classifyValidationResult)(result).kind !== 'violation');
    if (hasOnlySetupOrGuidanceFindings) {
        return {
            level: 'low',
            reasons: ['Only setup-gap or guidance findings detected.'],
        };
    }
    return {
        level: 'low',
        reasons: ['No elevated architecture risk signals detected.'],
    };
}
//# sourceMappingURL=architectureRiskAssessment.js.map