"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderArchitecturePrReviewMarkdown = renderArchitecturePrReviewMarkdown;
const architectureReviewReporter_1 = require("./architectureReviewReporter");
function sortUnique(values) {
    return [...new Set(values)].sort((left, right) => left.localeCompare(right));
}
function severityRank(severity) {
    if (severity === 'error') {
        return 1;
    }
    if (severity === 'warning') {
        return 2;
    }
    return 3;
}
function renderList(values) {
    if (values.length === 0) {
        return '- (none)';
    }
    return values.map((value) => `- ${value}`).join('\n');
}
function renderStatusLine(input) {
    const validationHasIssues = input.validation.kind === 'ok' &&
        (input.validation.data.counts.errors > 0 ||
            input.validation.data.counts.warnings > 0 ||
            input.validation.data.counts.info > 0);
    const driftHasChanges = input.drift.kind === 'ok' &&
        (input.drift.data.summaryCounts.totalChanges ??
            input.drift.data.summaryCounts.modulesAdded +
                input.drift.data.summaryCounts.modulesRemoved +
                input.drift.data.summaryCounts.dependenciesAdded +
                input.drift.data.summaryCounts.dependenciesRemoved +
                input.drift.data.summaryCounts.cyclesAdded +
                input.drift.data.summaryCounts.cyclesRemoved) > 0;
    if (validationHasIssues && driftHasChanges) {
        return 'Validation issues and drift detected';
    }
    if (validationHasIssues) {
        return 'Architecture validation issues detected';
    }
    if (driftHasChanges) {
        return 'Architecture drift detected';
    }
    if (input.validation.kind === 'ok' || input.drift.kind === 'ok') {
        return 'No architecture issues detected';
    }
    return 'No architecture review data available';
}
function renderArchitecturePrReviewMarkdown(input) {
    const lines = [];
    lines.push('# ArchPilot Architecture Review');
    lines.push('');
    lines.push(`**Status:** ${renderStatusLine(input)}`);
    lines.push('');
    lines.push('## Summary');
    if (input.validation.kind === 'ok') {
        lines.push(`- Validation health score: ${input.validation.data.healthScore}/100`);
        lines.push(`- Validation counts: errors=${input.validation.data.counts.errors}, warnings=${input.validation.data.counts.warnings}, info=${input.validation.data.counts.info}, passed=${input.validation.data.counts.passed}`);
        if ((input.validation.data.counts.exceptions ?? 0) > 0) {
            lines.push(`- Approved exceptions: ${input.validation.data.counts.exceptions}`);
        }
    }
    else if (input.validation.kind === 'excluded') {
        lines.push('- Validation: excluded by --drift-only');
    }
    else if (input.validation.kind === 'missing') {
        lines.push('- Validation: not available (.archpilot/reports/architecture-summary.json missing)');
    }
    else {
        lines.push(`- Validation: invalid report (${input.validation.details})`);
    }
    if (input.drift.kind === 'ok') {
        const totalChanges = input.drift.data.summaryCounts.totalChanges ??
            input.drift.data.summaryCounts.modulesAdded +
                input.drift.data.summaryCounts.modulesRemoved +
                input.drift.data.summaryCounts.dependenciesAdded +
                input.drift.data.summaryCounts.dependenciesRemoved +
                input.drift.data.summaryCounts.cyclesAdded +
                input.drift.data.summaryCounts.cyclesRemoved;
        lines.push(`- Drift counts: modulesAdded=${input.drift.data.summaryCounts.modulesAdded}, modulesRemoved=${input.drift.data.summaryCounts.modulesRemoved}, dependenciesAdded=${input.drift.data.summaryCounts.dependenciesAdded}, dependenciesRemoved=${input.drift.data.summaryCounts.dependenciesRemoved}, cyclesAdded=${input.drift.data.summaryCounts.cyclesAdded}, cyclesRemoved=${input.drift.data.summaryCounts.cyclesRemoved}, totalChanges=${totalChanges}`);
    }
    else if (input.drift.kind === 'excluded') {
        lines.push('- Drift: excluded by --validation-only');
    }
    else if (input.drift.kind === 'missing') {
        lines.push('- Drift: not available (.archpilot/reports/architecture-drift.json missing)');
    }
    else {
        lines.push(`- Drift: invalid report (${input.drift.details})`);
    }
    lines.push('');
    if (input.validation.kind === 'ok' && input.validation.data.changeRisk) {
        const changeRisk = input.validation.data.changeRisk;
        const changedModulesCount = changeRisk.signals?.changedModulesCount;
        const affectedDependentsCount = changeRisk.signals?.affectedDependentsCount;
        lines.push('## Change Risk (Diff-Aware PR Impact)');
        lines.push('- Purpose: blast radius and PR impact context.');
        lines.push(`- Risk Level: ${changeRisk.riskLevel.toUpperCase()}`);
        lines.push(`- Compact: Change Risk (Diff-Aware PR Impact): ${changeRisk.riskLevel.toUpperCase()} (modules: ${changedModulesCount ?? 0}, dependents: ${affectedDependentsCount ?? 0})`);
        if (changeRisk.summary) {
            lines.push(`- Summary: ${changeRisk.summary}`);
        }
        if (typeof changeRisk.score === 'number') {
            lines.push(`- Score: ${changeRisk.score}`);
        }
        lines.push('- Reasons:');
        lines.push(changeRisk.reasons.length === 0
            ? '  - (none)'
            : changeRisk.reasons.map((reason) => `  - ${reason}`).join('\n'));
        if (changedModulesCount !== undefined) {
            lines.push(`- Changed modules: ${changedModulesCount}`);
        }
        if (affectedDependentsCount !== undefined) {
            lines.push(`- Affected dependents: ${affectedDependentsCount}`);
        }
        if ((changeRisk.factors?.length ?? 0) > 0) {
            lines.push('- Triggered factors:');
            lines.push(changeRisk.factors.map((factor) => `  - ${factor.id} | ${factor.label} | ${factor.evidence}`).join('\n'));
        }
        lines.push('');
    }
    if (input.validation.kind === 'ok' && input.validation.data.impactAnalysis) {
        const impact = input.validation.data.impactAnalysis;
        lines.push('## Impact Analysis');
        lines.push(`- Changed Modules: ${impact.changedModules.length > 0 ? impact.changedModules.join(', ') : '(none)'}`);
        lines.push(`- Direct Dependents: ${impact.directDependents.length > 0 ? impact.directDependents.join(', ') : '(none)'}`);
        lines.push(`- Transitive Dependents: ${impact.transitiveDependents.length > 0
            ? impact.transitiveDependents.join(', ')
            : '(none)'}`);
        lines.push(`- Total Affected Modules: ${impact.totalAffectedModules}`);
        lines.push(`- Impact Radius Score: ${impact.impactRadiusScore}`);
        lines.push(`- Impact Level: ${impact.impactLevel}`);
        if (impact.summary) {
            lines.push(`- Summary: ${impact.summary}`);
        }
        const affectedSurface = impact.affectedSurface;
        if (affectedSurface) {
            lines.push('- Affected Surface:');
            lines.push(`  - Changed modules: ${(affectedSurface.changedModules ?? []).length > 0
                ? (affectedSurface.changedModules ?? []).join(', ')
                : '(none)'}`);
            lines.push(`  - Directly affected modules: ${(affectedSurface.directlyAffectedModules ?? []).length > 0
                ? (affectedSurface.directlyAffectedModules ?? []).join(', ')
                : '(none)'}`);
            lines.push(`  - Transitively affected modules: ${(affectedSurface.transitivelyAffectedModules ?? []).length > 0
                ? (affectedSurface.transitivelyAffectedModules ?? []).join(', ')
                : '(none)'}`);
            lines.push(`  - Impacted contracts: ${(affectedSurface.impactedContracts ?? []).length > 0
                ? (affectedSurface.impactedContracts ?? []).join(', ')
                : '(none)'}`);
            lines.push(`  - Impacted public entrypoints: ${(affectedSurface.impactedPublicEntrypoints ?? []).length > 0
                ? (affectedSurface.impactedPublicEntrypoints ?? []).join(', ')
                : '(none)'}`);
            lines.push(`  - Impacted ADRs: ${(affectedSurface.impactedAdrs ?? []).length > 0
                ? (affectedSurface.impactedAdrs ?? []).join(', ')
                : '(none)'}`);
            lines.push(`  - Impacted architecture artifacts: ${(affectedSurface.impactedArchitectureArtifacts ?? []).length > 0
                ? (affectedSurface.impactedArchitectureArtifacts ?? []).join(', ')
                : '(none)'}`);
        }
        if ((impact.directDependencyChains?.length ?? 0) > 0) {
            lines.push('- Direct dependency chains:');
            lines.push(impact.directDependencyChains
                .map((entry) => `  - ${entry.chain.join(' -> ')}`)
                .join('\n'));
        }
        if ((impact.transitiveDependencyChains?.length ?? 0) > 0) {
            lines.push('- Transitive dependency chains:');
            lines.push(impact.transitiveDependencyChains
                .map((entry) => `  - ${entry.chain.join(' -> ')}`)
                .join('\n'));
        }
        if ((impact.factors?.length ?? 0) > 0) {
            lines.push('- Impact factors:');
            lines.push(impact.factors
                .map((factor) => `  - ${factor.id} | ${factor.label} | weight=${factor.weight}`)
                .join('\n'));
        }
        lines.push('');
    }
    if (input.validation.kind === 'ok' && input.validation.data.baselineComparison) {
        const baseline = input.validation.data.baselineComparison;
        lines.push('## Baseline Comparison');
        lines.push(`- Baseline status: ${baseline.status}`);
        lines.push(`- Health score delta: ${baseline.deltas.healthScoreDelta}`);
        lines.push(`- Readiness score delta: ${baseline.deltas.readinessScoreDelta}`);
        lines.push(`- New findings: ${baseline.newlyIntroducedFindings.length}`);
        lines.push(`- Resolved findings: ${baseline.resolvedFindings.length}`);
        lines.push(`- Summary: ${baseline.summary}`);
        lines.push('');
    }
    if (input.validation.kind === 'ok' && input.validation.data.risk) {
        const governanceRisk = input.validation.data.risk;
        lines.push('## Architecture Review Level');
        lines.push('- Purpose: governance severity derived from validation results.');
        lines.push(`- Architecture Review Level: ${governanceRisk.level.toUpperCase()}`);
        lines.push('- Reasons:');
        lines.push(governanceRisk.reasons.length === 0
            ? '  - (none)'
            : governanceRisk.reasons.map((reason) => `  - ${reason}`).join('\n'));
        lines.push('');
    }
    if (input.validation.kind === 'ok' && input.validation.data.enforcement) {
        const enforcement = input.validation.data.enforcement;
        lines.push('## Enforcement (Policy Outcome)');
        lines.push('- Purpose: policy decision derived from governance risk.');
        lines.push(`- Action: ${enforcement.action.toUpperCase()}`);
        if (enforcement.policyLevel) {
            lines.push(`- Policy level: ${enforcement.policyLevel.toUpperCase()}`);
        }
        if (enforcement.enforcementDecision) {
            lines.push(`- Enforcement decision: ${enforcement.enforcementDecision}`);
        }
        if (enforcement.matchedThreshold) {
            lines.push(`- Matched threshold: ${enforcement.matchedThreshold.id ?? '(unknown)'} (configured=${enforcement.matchedThreshold.configuredValue ?? 'n/a'}, matched=${enforcement.matchedThreshold.matchedValue ?? 'n/a'}, source=${enforcement.matchedThreshold.source ?? enforcement.thresholdSource ?? 'n/a'})`);
        }
        if (enforcement.baselineContribution) {
            lines.push(`- Baseline contribution: ${enforcement.baselineContribution.elevated ? 'ELEVATED' : 'NOT_ELEVATED'} (${enforcement.baselineContribution.reason ?? 'n/a'})`);
        }
        if (enforcement.ciExitBehavior) {
            lines.push(`- CI exit behavior: exitCode=${enforcement.ciExitBehavior.exitCode ?? 0}, blocking=${enforcement.ciExitBehavior.blocking ? 'yes' : 'no'}`);
        }
        lines.push('- Reasons:');
        lines.push(enforcement.reasons.length === 0
            ? '  - (none)'
            : enforcement.reasons.map((reason) => `  - ${reason}`).join('\n'));
        lines.push('- Required Actions:');
        lines.push((enforcement.requiredActions ?? []).length === 0
            ? '  - (none)'
            : (enforcement.requiredActions ?? []).map((action) => `  - ${action}`).join('\n'));
        lines.push('');
    }
    if (input.validation.kind === 'ok' && input.validation.data.adrRequirement) {
        const adrRequirement = input.validation.data.adrRequirement;
        const adrDisplay = (0, architectureReviewReporter_1.resolveAdrRequirementDisplay)({
            enforcementAction: input.validation.data.enforcement?.action ?? 'pass',
            adrRequirement,
            findings: input.validation.data.findings,
        });
        lines.push('## ADR Requirement');
        lines.push(`- Required: ${adrDisplay.requiredLabel}`);
        lines.push(`- Satisfied: ${adrDisplay.satisfiedLabel}`);
        lines.push('- Reasons:');
        lines.push(adrDisplay.reasons.length === 0
            ? '  - (none)'
            : adrDisplay.reasons.map((reason) => `  - ${reason}`).join('\n'));
        lines.push('- Suggested command:');
        lines.push(adrDisplay.state === 'required' && adrRequirement.suggestedCommand
            ? `  - ${adrRequirement.suggestedCommand}`
            : '  - (none)');
        lines.push('- Suggested filename hint:');
        lines.push(adrDisplay.state === 'required' && adrRequirement.suggestedFilenameHint
            ? `  - ${adrRequirement.suggestedFilenameHint}`
            : '  - (none)');
        lines.push('');
    }
    if (input.validation.kind === 'ok' && input.validation.data.safetyControls) {
        const safety = input.validation.data.safetyControls;
        if (safety.triggered && (safety.findings?.length ?? 0) > 0) {
            lines.push('## Recommended Deployment Safety Controls');
            lines.push(`- Summary: ${safety.summary ?? 'Missing safety controls detected.'}`);
            lines.push(`- Missing controls: ${(safety.missingControls ?? []).length > 0
                ? (safety.missingControls ?? []).join(', ')
                : '(none)'}`);
            lines.push('- Findings:');
            lines.push((safety.findings ?? [])
                .map((finding) => `  - [${finding.ruleId}] ${finding.message}${finding.evidencePath ? ` (${finding.evidencePath})` : ''}`)
                .join('\n'));
            lines.push('');
        }
    }
    if (input.validation.kind === 'ok') {
        const topFindings = [...input.validation.data.findings]
            .sort((left, right) => {
            const severityCompare = severityRank(left.severity) - severityRank(right.severity);
            if (severityCompare !== 0) {
                return severityCompare;
            }
            const idCompare = left.id.localeCompare(right.id);
            if (idCompare !== 0) {
                return idCompare;
            }
            return left.message.localeCompare(right.message);
        })
            .slice(0, 8);
        lines.push('## Validation Findings');
        lines.push(topFindings.length === 0
            ? '- (none)'
            : topFindings
                .map((finding) => `- [${finding.id}] (${finding.severity}) ${finding.title} | ${finding.message}`)
                .join('\n'));
        lines.push('');
    }
    if (input.drift.kind === 'ok') {
        const modulesAdded = sortUnique(input.drift.data.modulesAdded);
        const modulesRemoved = sortUnique(input.drift.data.modulesRemoved);
        const dependenciesAdded = [...input.drift.data.dependenciesAdded].sort((left, right) => {
            const sourceCompare = left.source.localeCompare(right.source);
            if (sourceCompare !== 0) {
                return sourceCompare;
            }
            return left.target.localeCompare(right.target);
        });
        const dependenciesRemoved = [...input.drift.data.dependenciesRemoved].sort((left, right) => {
            const sourceCompare = left.source.localeCompare(right.source);
            if (sourceCompare !== 0) {
                return sourceCompare;
            }
            return left.target.localeCompare(right.target);
        });
        const cyclesAdded = sortUnique(input.drift.data.cyclesAdded);
        const cyclesRemoved = sortUnique(input.drift.data.cyclesRemoved);
        const topDriftChanges = [];
        for (const cycle of cyclesAdded.slice(0, 3)) {
            topDriftChanges.push(`cycle added: ${cycle}`);
        }
        for (const entry of dependenciesAdded.slice(0, 4)) {
            topDriftChanges.push(`dependency added: ${entry.source} -> ${entry.target}`);
        }
        for (const entry of dependenciesRemoved.slice(0, 4)) {
            topDriftChanges.push(`dependency removed: ${entry.source} -> ${entry.target}`);
        }
        for (const moduleName of modulesAdded.slice(0, 3)) {
            topDriftChanges.push(`module added: ${moduleName}`);
        }
        for (const moduleName of modulesRemoved.slice(0, 3)) {
            topDriftChanges.push(`module removed: ${moduleName}`);
        }
        lines.push('## Architecture Drift');
        lines.push('### Top Drift Changes');
        lines.push(topDriftChanges.length === 0 ? '- (none)' : topDriftChanges.map((entry) => `- ${entry}`).join('\n'));
        lines.push('');
        lines.push('### Drift Details');
        lines.push('- New Modules:');
        lines.push(renderList(modulesAdded));
        lines.push('- Removed Modules:');
        lines.push(renderList(modulesRemoved));
        lines.push('- New Dependencies:');
        lines.push(dependenciesAdded.length === 0
            ? '- (none)'
            : dependenciesAdded
                .map((entry) => `- ${entry.source} -> ${entry.target}`)
                .join('\n'));
        lines.push('- Removed Dependencies:');
        lines.push(dependenciesRemoved.length === 0
            ? '- (none)'
            : dependenciesRemoved
                .map((entry) => `- ${entry.source} -> ${entry.target}`)
                .join('\n'));
        lines.push('- New Cycles:');
        lines.push(renderList(cyclesAdded));
        lines.push('- Removed Cycles:');
        lines.push(renderList(cyclesRemoved));
        lines.push('');
    }
    lines.push('## Recommended Attention');
    const attention = [];
    if (input.validation.kind === 'ok' && input.validation.data.counts.errors > 0) {
        attention.push('- Resolve validation errors first.');
    }
    if (input.validation.kind === 'ok' && input.validation.data.counts.warnings > 0) {
        attention.push('- Review validation warnings before merge.');
    }
    if (input.drift.kind === 'ok' && input.drift.data.summaryCounts.cyclesAdded > 0) {
        attention.push('- Review newly introduced dependency cycles.');
    }
    if (input.drift.kind === 'ok' &&
        (input.drift.data.summaryCounts.dependenciesAdded > 0 ||
            input.drift.data.summaryCounts.dependenciesRemoved > 0)) {
        attention.push('- Validate module dependency changes against intended architecture boundaries.');
    }
    if (input.drift.kind === 'ok' &&
        (input.drift.data.summaryCounts.modulesAdded > 0 ||
            input.drift.data.summaryCounts.modulesRemoved > 0)) {
        attention.push('- Review module additions/removals for architecture baseline alignment.');
    }
    if (attention.length === 0) {
        attention.push('- No immediate architecture risks detected.');
    }
    lines.push(attention.join('\n'));
    if ((input.validation.kind === 'missing' || input.validation.kind === 'excluded') &&
        (input.drift.kind === 'missing' || input.drift.kind === 'excluded')) {
        lines.push('');
        lines.push('Run `archpilot validate --ci` and `archpilot baseline check` to populate PR review data.');
    }
    return `${lines.join('\n').trimEnd()}\n`;
}
//# sourceMappingURL=architecturePrReviewReporter.js.map