/**
 * 治理健康报告 — 汇总 audit pool、escape reports、capability action decisions、sample decisions。
 * P2-5+P2-6 范围: 只读报告，不改状态。
 */
import { validateArtifactContracts } from "../contracts/artifact_contract_registry.js";
import { validateConfigPrecedence } from "../config/config_precedence_contract.js";
import { debug } from "../core/logger.js";
function deepCopyRule(rule) {
    return { ...rule };
}
function deepCopyDecision(decision) {
    return {
        ...decision,
        evidence_ids: [...decision.evidence_ids],
        triggered_rules: decision.triggered_rules.map(deepCopyRule),
    };
}
function deepCopySummary(summary) {
    return {
        ...summary,
        action: deepCopyDecision(summary.action),
    };
}
/**
 * 生成治理健康报告。
 * 汇总审计池、逃逸报告、能力决策和抽样决策的统计数据，识别危险策略和降级候选。
 * 支持双层机制、制品契约、配置优先级契约和核心原则的治理检查。
 * @param auditStats - 审计池统计数据
 * @param auditItems - 审计条目列表
 * @param escapeReports - 逃逸报告列表
 * @param escapeStats - 逃逸报告统计数据
 * @param decisions - 能力动作决策列表
 * @param now - 报告生成时间（可选，默认当前时间）
 * @param sampleDecisions - 抽样决策列表（可选）
 * @param dualLayerFindings - 双层机制发现列表（可选）
 * @param dualLayerMechanismCount - 双层机制总数（可选）
 * @param artifacts - 输出制品列表（可选，用于制品契约检查）
 * @param configReports - 配置解析报告列表（可选）
 * @param configEntries - 配置优先级证据条目列表（可选）
 * @param corePrinciples - 核心原则遵循性报告列表（可选）
 * @returns 完整的治理健康报告
 */
/**
 * 生成治理健康报告。
 * @param options - 报告选项，包含审计池和能力状态存储
 * @returns 治理报告，包含任务统计、逃逸分析和降级建议
 */
export function generateReport(auditStats, _auditItems, escapeReports, escapeStats, decisions, now, sampleDecisions, dualLayerFindings, dualLayerMechanismCount, artifacts, configReports, configEntries, corePrinciples, contractFindings, totalRegistryContracts) {
    debug("治理报告", "生成治理健康报告");
    const nonFPReports = escapeReports.filter((r) => r.failure_type !== "false_positive");
    const fpReports = escapeReports.filter((r) => r.failure_type === "false_positive");
    const sampledCount = sampleDecisions
        ? sampleDecisions.filter((d) => d.should_sample).length
        : null;
    // 从决策构建每个策略的汇总
    const policyMap = new Map();
    for (const decision of decisions) {
        const pid = decision.policy_id;
        const policyEscapes = nonFPReports.filter((r) => r.policy_id === pid);
        const policyFP = fpReports.filter((r) => r.policy_id === pid);
        policyMap.set(pid, {
            policy_id: pid,
            escape_count: policyEscapes.length,
            false_positive_count: policyFP.length,
            action: deepCopyDecision(decision),
        });
    }
    // 危险策略: 有逃逸且非 keep 动作的策略
    debug("治理报告", "识别危险策略，总决策数=" + decisions.length);
    const dangerPolicies = [...policyMap.values()]
        .filter((p) => p.escape_count > 0 && p.action.recommended_action !== "keep")
        .sort((a, b) => b.escape_count - a.escape_count)
        .map(deepCopySummary);
    // 降级候选: 动作为 downgrade 或 disable
    debug("治理报告", "识别降级候选策略");
    const downgradeCandidates = [...policyMap.values()]
        .filter((p) => p.action.recommended_action === "downgrade" || p.action.recommended_action === "disable")
        .sort((a, b) => {
        const priority = (d) => (d.recommended_action === "disable" ? 0 : 1);
        return priority(a.action) - priority(b.action);
    })
        .map(deepCopySummary);
    // Top fixes: 非 FP 逃逸报告按 due_date 排序，最多 5 条
    debug("治理报告", "整理 top fixes，非误报逃逸数=" + nonFPReports.length);
    const topFixes = nonFPReports
        .slice()
        .sort((a, b) => a.due_date.localeCompare(b.due_date))
        .slice(0, 5)
        .map((r) => ({
        escape_id: r.escape_id,
        policy_id: r.policy_id,
        failure_type: r.failure_type,
        fix_required: r.fix_required,
        owner: r.owner,
        due_date: r.due_date,
    }));
    // 双层机制汇总
    if (dualLayerFindings)
        debug("治理报告", "双层机制发现数=" + dualLayerFindings.length);
    const dlHardFails = (dualLayerFindings ?? []).filter((f) => f.severity === "hard_fail");
    const dlAdvisory = (dualLayerFindings ?? []).filter((f) => f.severity === "advisory");
    const dlSummary = dualLayerFindings
        ? {
            total_mechanisms: dualLayerMechanismCount ?? 0,
            dual_layer_enforced_count: (dualLayerMechanismCount ?? 0) - dlHardFails.length,
            hard_fail_count: dlHardFails.length,
            advisory_count: dlAdvisory.length,
            findings: [...dualLayerFindings],
        }
        : undefined;
    // 制品治理 
    if (artifacts && artifacts.length > 0)
        debug("治理报告", "检查制品契约，制品数=" + artifacts.length);
    let artifactGovernance;
    if (artifacts && artifacts.length > 0) {
        const findings = validateArtifactContracts(artifacts);
        artifactGovernance = {
            artifact_count: artifacts.length,
            hard_fail_count: findings.filter(f => f.severity === "hard_fail").length,
            advisory_count: findings.filter(f => f.severity === "advisory").length,
            findings,
        };
    }
    // 配置优先级治理 
    if (configReports && configReports.length > 0)
        debug("治理报告", "检查配置优先级契约，报告数=" + configReports.length);
    let configPrecedenceGovernance;
    if (configReports && configReports.length > 0) {
        const cpFindings = validateConfigPrecedence(configReports, configEntries ?? []);
        configPrecedenceGovernance = {
            hard_fail_count: cpFindings.filter(f => f.severity === "hard_fail").length,
            advisory_count: cpFindings.filter(f => f.severity === "advisory").length,
            findings: cpFindings,
        };
    }
    // 核心原则治理
    if (corePrinciples && corePrinciples.length > 0)
        debug("治理报告", "检查核心原则遵循性，报告数=" + corePrinciples.length);
    let corePrinciplesGovernance;
    if (corePrinciples && corePrinciples.length > 0) {
        // 合并所有报告为汇总
        const latestReport = corePrinciples[corePrinciples.length - 1];
        corePrinciplesGovernance = {
            task_level: latestReport.task_level,
            overall_passed: corePrinciples.every(r => r.overall_passed),
            principles: latestReport.principles.map(p => ({
                principle_id: p.principle_id,
                status: p.status,
                findings: p.findings,
            })),
        };
    }
    // 契约治理汇总
    if (contractFindings && contractFindings.length > 0)
        debug("治理报告", "检查契约治理，发现数=" + contractFindings.length);
    let contractGovernance;
    if (contractFindings) {
        contractGovernance = {
            total_contracts: totalRegistryContracts ?? new Set(contractFindings.map((f) => f.contract_id)).size,
            hard_fail_count: contractFindings.filter((f) => f.severity === "hard_fail").length,
            warning_count: contractFindings.filter((f) => f.severity === "warning").length,
            advisory_count: contractFindings.filter((f) => f.severity === "advisory").length,
            findings: [...contractFindings],
        };
    }
    return {
        generated_at: (now ?? new Date()).toISOString(),
        total_tasks: auditStats.total,
        audit_by_risk: { ...auditStats.by_risk },
        sampled_count: sampledCount,
        total_escapes: nonFPReports.length,
        total_false_positives: fpReports.length,
        escape_by_type: { ...escapeStats.by_type },
        danger_policies: dangerPolicies,
        downgrade_candidates: downgradeCandidates,
        top_fixes: topFixes,
        dual_layer_summary: dlSummary,
        artifact_governance: artifactGovernance,
        config_precedence_governance: configPrecedenceGovernance,
        core_principles_governance: corePrinciplesGovernance,
        contract_governance: contractGovernance,
    };
}
//# sourceMappingURL=governance_report.js.map