/**
 * Compliance Assessment Bundle
 *
 * Orchestrates compliance assessment with evidence collection and audit
 * trail verification for any combination of frameworks.
 *
 * @module compliance/compliance-bundle
 */
import { generateComplianceReport, generateMultiFrameworkReport } from "./mapper.js";
import { formatComplianceReportAsMarkdown, formatMultiFrameworkReportAsMarkdown, } from "./report.js";
import { collectEvidence, storeEvidenceBundle } from "../evidence/index.js";
import { verifyHistoryIntegrity } from "../history/verify.js";
/**
 * Run a compliance assessment for a single framework
 *
 * This function orchestrates:
 * 1. Compliance control mapping for the framework
 * 2. Audit trail integrity verification (optional)
 * 3. Evidence bundle collection (optional)
 * 4. Audit-defensible report generation
 */
export async function runSingleFrameworkAssessment(options) {
    const { projectPath, findings, framework, certificationId, collectEvidence: shouldCollectEvidence = false, sign = false, verifyAuditTrail = false, storeEvidence = true, includeAttestation = true, } = options;
    // Generate compliance report
    const report = generateComplianceReport(findings, framework, projectPath, certificationId);
    // Determine status
    let status;
    if (report.status.complianceScore >= 90 && report.status.controlsNonCompliant === 0) {
        status = "compliant";
    }
    else if (report.status.complianceScore >= 70) {
        status = "at_risk";
    }
    else {
        status = "non_compliant";
    }
    // Verify audit trail if requested
    let auditVerification;
    if (verifyAuditTrail) {
        auditVerification = await verifyHistoryIntegrity(projectPath);
    }
    // Collect evidence if requested
    let evidenceBundle;
    let evidencePath;
    if (shouldCollectEvidence) {
        const evidenceResult = await collectEvidence({
            projectPath,
            certificationId,
            frameworks: [framework],
            includeSbom: true,
            includeHistory: true,
            includeScanResults: true,
            includeConfig: true,
            sign,
        });
        if (evidenceResult.success && evidenceResult.bundle) {
            evidenceBundle = evidenceResult.bundle;
            // Store evidence if requested
            if (storeEvidence) {
                evidencePath = await storeEvidenceBundle(projectPath, evidenceBundle);
            }
        }
    }
    // Generate markdown report with audit-defensibility options
    const reportOptions = {
        evidenceBundle,
        auditVerification,
        includeAttestation,
    };
    const markdownReport = formatComplianceReportAsMarkdown(report, reportOptions);
    return {
        report,
        markdownReport,
        evidenceBundle,
        auditVerification,
        evidencePath,
        status,
    };
}
/**
 * Run a compliance assessment for multiple frameworks
 *
 * This function orchestrates:
 * 1. Compliance control mapping for all frameworks
 * 2. Audit trail integrity verification (optional)
 * 3. Evidence bundle collection (optional)
 * 4. Unified audit-defensible report generation
 */
export async function runComplianceAssessment(options) {
    const { projectPath, findings, frameworks, certificationId, collectEvidence: shouldCollectEvidence = false, sign = false, verifyAuditTrail = false, storeEvidence = true, includeAttestation = true, } = options;
    // Handle single framework case
    if (frameworks.length === 1) {
        const singleResult = await runSingleFrameworkAssessment({
            ...options,
            framework: frameworks[0],
        });
        // Convert to multi-framework result format
        const multiReport = generateMultiFrameworkReport(findings, frameworks, projectPath, certificationId);
        return {
            reports: { [frameworks[0]]: singleResult.report },
            multiFrameworkReport: multiReport,
            markdownReport: singleResult.markdownReport,
            evidenceBundle: singleResult.evidenceBundle,
            auditVerification: singleResult.auditVerification,
            evidencePath: singleResult.evidencePath,
            status: singleResult.status,
            combinedScore: singleResult.report.status.complianceScore,
        };
    }
    // Generate reports for all frameworks
    const reports = {};
    for (const framework of frameworks) {
        reports[framework] = generateComplianceReport(findings, framework, projectPath, certificationId);
    }
    // Generate multi-framework report
    const multiFrameworkReport = generateMultiFrameworkReport(findings, frameworks, projectPath, certificationId);
    // Calculate combined score
    const scores = Object.values(reports)
        .filter((r) => r !== undefined)
        .map(r => r.status.complianceScore);
    const combinedScore = scores.length > 0
        ? Math.round(scores.reduce((a, b) => a + b, 0) / scores.length)
        : 0;
    // Count non-compliant controls across all frameworks
    const totalNonCompliant = Object.values(reports)
        .filter((r) => r !== undefined)
        .reduce((sum, r) => sum + r.status.controlsNonCompliant, 0);
    // Determine overall status
    let status;
    if (combinedScore >= 90 && totalNonCompliant === 0) {
        status = "compliant";
    }
    else if (combinedScore >= 70) {
        status = "at_risk";
    }
    else {
        status = "non_compliant";
    }
    // Verify audit trail if requested
    let auditVerification;
    if (verifyAuditTrail) {
        auditVerification = await verifyHistoryIntegrity(projectPath);
    }
    // Collect evidence if requested
    let evidenceBundle;
    let evidencePath;
    if (shouldCollectEvidence) {
        const evidenceResult = await collectEvidence({
            projectPath,
            certificationId,
            frameworks,
            includeSbom: true,
            includeHistory: true,
            includeScanResults: true,
            includeConfig: true,
            sign,
        });
        if (evidenceResult.success && evidenceResult.bundle) {
            evidenceBundle = evidenceResult.bundle;
            // Store evidence if requested
            if (storeEvidence) {
                evidencePath = await storeEvidenceBundle(projectPath, evidenceBundle);
            }
        }
    }
    // Generate markdown report with audit-defensibility options
    const reportOptions = {
        evidenceBundle,
        auditVerification,
        includeAttestation,
    };
    const markdownReport = formatMultiFrameworkReportAsMarkdown(multiFrameworkReport, reportOptions);
    return {
        reports,
        multiFrameworkReport,
        markdownReport,
        evidenceBundle,
        auditVerification,
        evidencePath,
        status,
        combinedScore,
    };
}
/**
 * Generate a quick compliance summary
 */
export function generateComplianceSummary(result) {
    const statusIcon = result.status === "compliant" ? "✅" :
        result.status === "at_risk" ? "⚠️" : "❌";
    const frameworkNames = Object.keys(result.reports).join(", ");
    const lines = [
        `${statusIcon} Compliance: ${result.status.toUpperCase()}`,
        `Frameworks: ${frameworkNames}`,
        `Combined Score: ${result.combinedScore}%`,
    ];
    // Add individual framework scores
    for (const [framework, report] of Object.entries(result.reports)) {
        if (report) {
            lines.push(`${framework}: ${report.status.complianceScore}%`);
        }
    }
    if (result.auditVerification) {
        lines.push(`Audit Trail: ${result.auditVerification.verified ? "Verified" : "FAILED"}`);
    }
    if (result.evidenceBundle) {
        lines.push(`Evidence: ${result.evidenceBundle.id}`);
    }
    return lines.join(" | ");
}
//# sourceMappingURL=compliance-bundle.js.map