/**
 * Compliance Report Generator
 *
 * Generates markdown and JSON reports for compliance assessments.
 *
 * @module compliance/report
 */
import { formatAttestationAsMarkdown, formatMultiFrameworkAttestationAsMarkdown } from "./attestation.js";
/**
 * Format compliance report as markdown
 *
 * @param report - The compliance report to format
 * @param options - Optional audit-defensibility options (evidence, audit verification, attestation)
 */
export function formatComplianceReportAsMarkdown(report, options) {
    const lines = [];
    const { evidenceBundle, auditVerification, includeAttestation } = options || {};
    // Header
    lines.push(`# ${report.framework} Compliance Report`);
    lines.push("");
    lines.push(`**Generated:** ${new Date(report.generatedAt).toLocaleString()}`);
    lines.push(`**Project:** ${report.projectPath}`);
    if (report.certificationId) {
        lines.push(`**Certification:** ${report.certificationId}`);
    }
    lines.push("");
    // Status summary
    lines.push("## Compliance Status");
    lines.push("");
    lines.push(generateStatusBadge(report.status.complianceScore));
    lines.push("");
    lines.push("| Metric | Value |");
    lines.push("|--------|-------|");
    lines.push(`| **Compliance Score** | ${report.status.complianceScore}% |`);
    lines.push(`| **Risk Score** | ${report.status.riskScore}% |`);
    lines.push(`| Total Controls | ${report.status.totalControls} |`);
    lines.push(`| Compliant | ${report.status.controlsCovered} |`);
    lines.push(`| At Risk | ${report.status.controlsAtRisk} |`);
    lines.push(`| Non-Compliant | ${report.status.controlsNonCompliant} |`);
    lines.push("");
    // Audit Trail Integrity (if provided)
    if (auditVerification) {
        lines.push(formatAuditTrailSection(auditVerification));
    }
    // Evidence Bundle (if provided)
    if (evidenceBundle) {
        lines.push(formatEvidenceBundleSection(evidenceBundle));
    }
    // Non-compliant controls
    if (report.nonCompliantControls.length > 0) {
        lines.push("## Non-Compliant Controls");
        lines.push("");
        lines.push("These controls have critical or high severity findings that must be addressed.");
        lines.push("");
        for (const ctrl of report.nonCompliantControls) {
            lines.push(formatControlSection(ctrl));
        }
    }
    // At-risk controls
    if (report.atRiskControls.length > 0) {
        lines.push("## At-Risk Controls");
        lines.push("");
        lines.push("These controls have findings that should be reviewed.");
        lines.push("");
        lines.push("<details>");
        lines.push("<summary>Click to expand at-risk controls</summary>");
        lines.push("");
        for (const ctrl of report.atRiskControls) {
            lines.push(formatControlSection(ctrl));
        }
        lines.push("</details>");
        lines.push("");
    }
    // Compliant controls
    if (report.compliantControls.length > 0) {
        lines.push("## Compliant Controls");
        lines.push("");
        lines.push("<details>");
        lines.push(`<summary>${report.compliantControls.length} controls passing</summary>`);
        lines.push("");
        lines.push("| Control | Title |");
        lines.push("|---------|-------|");
        for (const ctrl of report.compliantControls) {
            lines.push(`| ${ctrl.id} | ${ctrl.title} |`);
        }
        lines.push("");
        lines.push("</details>");
        lines.push("");
    }
    // Recommendations
    if (report.recommendations.length > 0) {
        lines.push("## Recommendations");
        lines.push("");
        lines.push(formatRecommendations(report.recommendations));
    }
    // Attestation section (if requested)
    if (includeAttestation) {
        lines.push(formatAttestationAsMarkdown(report.framework));
    }
    // Footer
    lines.push("---");
    lines.push("");
    const auditLabel = evidenceBundle || auditVerification ? " | Audit-Defensible" : "";
    lines.push(`_Generated by [Vaspera Hardening](https://github.com/RCOLKITT/hardening-mcp)${auditLabel}_`);
    return lines.join("\n");
}
/**
 * Format multi-framework report as markdown
 *
 * @param report - The multi-framework compliance report to format
 * @param options - Optional audit-defensibility options (evidence, audit verification, attestation)
 */
export function formatMultiFrameworkReportAsMarkdown(report, options) {
    const lines = [];
    const { evidenceBundle, auditVerification, includeAttestation } = options || {};
    lines.push("# Multi-Framework Compliance Report");
    lines.push("");
    lines.push(`**Generated:** ${new Date(report.generatedAt).toLocaleString()}`);
    lines.push(`**Project:** ${report.projectPath}`);
    if (report.certificationId) {
        lines.push(`**Certification:** ${report.certificationId}`);
    }
    lines.push("");
    // Framework summary table
    lines.push("## Framework Summary");
    lines.push("");
    lines.push("| Framework | Compliance | Risk | Compliant | At Risk | Non-Compliant |");
    lines.push("|-----------|------------|------|-----------|---------|---------------|");
    for (const [framework, status] of Object.entries(report.frameworks)) {
        if (status) {
            const icon = status.complianceScore >= 90 ? "✅" : status.complianceScore >= 70 ? "⚠️" : "❌";
            lines.push(`| ${icon} ${framework} | ${status.complianceScore}% | ${status.riskScore}% | ${status.controlsCovered} | ${status.controlsAtRisk} | ${status.controlsNonCompliant} |`);
        }
    }
    lines.push("");
    // Audit Trail Integrity (if provided)
    if (auditVerification) {
        lines.push(formatAuditTrailSection(auditVerification));
    }
    // Evidence Bundle (if provided)
    if (evidenceBundle) {
        lines.push(formatEvidenceBundleSection(evidenceBundle));
    }
    // Prioritized recommendations
    if (report.prioritizedRecommendations.length > 0) {
        lines.push("## Prioritized Recommendations");
        lines.push("");
        lines.push("Actions prioritized by impact across all frameworks:");
        lines.push("");
        lines.push(formatRecommendations(report.prioritizedRecommendations.slice(0, 10)));
        if (report.prioritizedRecommendations.length > 10) {
            lines.push(`_...and ${report.prioritizedRecommendations.length - 10} more recommendations_`);
            lines.push("");
        }
    }
    // Attestation section (if requested)
    if (includeAttestation) {
        const frameworks = Object.keys(report.frameworks);
        lines.push(formatMultiFrameworkAttestationAsMarkdown(frameworks));
    }
    // Footer
    lines.push("---");
    lines.push("");
    const auditLabel = evidenceBundle || auditVerification ? " | Audit-Defensible" : "";
    lines.push(`_Generated by [Vaspera Hardening](https://github.com/RCOLKITT/hardening-mcp)${auditLabel}_`);
    return lines.join("\n");
}
/**
 * Format audit trail verification section as markdown
 */
function formatAuditTrailSection(auditVerification) {
    const lines = [];
    lines.push("## Audit Trail Integrity");
    lines.push("");
    const auditIcon = auditVerification.verified ? "✅" : "❌";
    lines.push(`${auditIcon} **Audit Trail Status:** ${auditVerification.verified ? "Verified" : "INTEGRITY FAILURE"}`);
    lines.push("");
    lines.push("| Metric | Value |");
    lines.push("|--------|-------|");
    lines.push(`| Total Entries | ${auditVerification.totalEntries} |`);
    lines.push(`| Entries Verified | ${auditVerification.entriesVerified} |`);
    lines.push(`| Chain Integrity | ${auditVerification.chainIntegrity ? "Intact" : "Broken"} |`);
    if (auditVerification.genesisHash) {
        lines.push(`| Genesis Hash | \`${auditVerification.genesisHash.slice(0, 16)}...\` |`);
    }
    if (auditVerification.headHash) {
        lines.push(`| Head Hash | \`${auditVerification.headHash.slice(0, 16)}...\` |`);
    }
    lines.push("");
    if (!auditVerification.verified && auditVerification.firstFailure) {
        lines.push("⚠️ **Warning:** Audit trail integrity compromised. Evidence may not be defensible.");
        lines.push("");
    }
    return lines.join("\n");
}
/**
 * Format evidence bundle section as markdown
 */
function formatEvidenceBundleSection(evidenceBundle) {
    const lines = [];
    lines.push("## Evidence Bundle");
    lines.push("");
    lines.push(`**Bundle ID:** ${evidenceBundle.id}`);
    lines.push(`**Created:** ${evidenceBundle.createdAt}`);
    lines.push(`**Bundle Digest:** \`${evidenceBundle.bundleDigest}\``);
    lines.push("");
    if (evidenceBundle.signature) {
        lines.push("✅ **Signed:** Yes (Sigstore)");
        if (evidenceBundle.signature.rekorLogIndex) {
            lines.push(`**Transparency Log Index:** ${evidenceBundle.signature.rekorLogIndex}`);
        }
    }
    else {
        lines.push("⚠️ **Signed:** No");
    }
    lines.push("");
    lines.push("### Collected Artifacts");
    lines.push("");
    lines.push("| Type | Name | Size | Digest |");
    lines.push("|------|------|------|--------|");
    for (const artifact of evidenceBundle.artifacts) {
        const sizeKB = (artifact.sizeBytes / 1024).toFixed(1);
        lines.push(`| ${artifact.type} | ${artifact.name} | ${sizeKB}KB | \`${artifact.contentDigest.slice(0, 12)}...\` |`);
    }
    lines.push("");
    // Environment
    lines.push("### Collection Environment");
    lines.push("");
    lines.push("| Property | Value |");
    lines.push("|----------|-------|");
    lines.push(`| OS | ${evidenceBundle.environment.os} ${evidenceBundle.environment.osVersion} |`);
    lines.push(`| Node.js | ${evidenceBundle.environment.nodeVersion} |`);
    lines.push(`| Vaspera | ${evidenceBundle.environment.vasperaVersion} |`);
    if (evidenceBundle.environment.ci) {
        lines.push(`| CI Provider | ${evidenceBundle.environment.ci.provider} |`);
        lines.push(`| Build ID | ${evidenceBundle.environment.ci.buildId} |`);
        lines.push(`| Commit SHA | \`${evidenceBundle.environment.ci.commitSha.slice(0, 8)}\` |`);
    }
    lines.push("");
    return lines.join("\n");
}
/**
 * Generate status badge based on score
 */
function generateStatusBadge(score) {
    let color;
    let status;
    if (score >= 90) {
        color = "brightgreen";
        status = "Compliant";
    }
    else if (score >= 70) {
        color = "yellow";
        status = "Partially Compliant";
    }
    else if (score >= 50) {
        color = "orange";
        status = "At Risk";
    }
    else {
        color = "red";
        status = "Non-Compliant";
    }
    return `![Compliance Status](https://img.shields.io/badge/Status-${encodeURIComponent(status)}-${color}) ![Score](https://img.shields.io/badge/Score-${score}%25-${color})`;
}
/**
 * Format a control section
 */
function formatControlSection(ctrl) {
    const lines = [];
    const riskIcon = ctrl.riskLevel === "critical"
        ? "🔴"
        : ctrl.riskLevel === "high"
            ? "🟠"
            : ctrl.riskLevel === "medium"
                ? "🟡"
                : "🔵";
    lines.push(`### ${riskIcon} ${ctrl.control.id}: ${ctrl.control.title}`);
    lines.push("");
    lines.push(`> ${ctrl.control.description}`);
    lines.push("");
    lines.push(`**Category:** ${ctrl.control.category}`);
    lines.push(`**Status:** ${ctrl.status}`);
    lines.push(`**Risk Level:** ${ctrl.riskLevel}`);
    lines.push(`**Findings:** ${ctrl.findings.length}`);
    lines.push("");
    if (ctrl.findings.length > 0) {
        lines.push("| Severity | Category | File | Description |");
        lines.push("|----------|----------|------|-------------|");
        for (const finding of ctrl.findings.slice(0, 5)) {
            const sevIcon = finding.severity === "critical"
                ? "🔴"
                : finding.severity === "high"
                    ? "🟠"
                    : finding.severity === "medium"
                        ? "🟡"
                        : "🔵";
            const shortDesc = finding.description.length > 50
                ? finding.description.slice(0, 47) + "..."
                : finding.description;
            const file = finding.file || "-";
            lines.push(`| ${sevIcon} ${finding.severity} | ${finding.category} | \`${file}\` | ${shortDesc} |`);
        }
        if (ctrl.findings.length > 5) {
            lines.push(`| ... | | | _${ctrl.findings.length - 5} more findings_ |`);
        }
        lines.push("");
    }
    return lines.join("\n");
}
/**
 * Format recommendations
 */
function formatRecommendations(recommendations) {
    const lines = [];
    for (let i = 0; i < recommendations.length; i++) {
        const rec = recommendations[i];
        const priorityIcon = rec.priority === "critical"
            ? "🔴"
            : rec.priority === "high"
                ? "🟠"
                : rec.priority === "medium"
                    ? "🟡"
                    : "🔵";
        lines.push(`### ${i + 1}. ${priorityIcon} ${rec.title}`);
        lines.push("");
        lines.push(`**Control:** ${rec.controlId}`);
        lines.push(`**Priority:** ${rec.priority}`);
        lines.push(`**Estimated Effort:** ${rec.estimatedEffort}`);
        lines.push("");
        lines.push(rec.description);
        lines.push("");
        lines.push("**Remediation Steps:**");
        for (const step of rec.remediationSteps) {
            lines.push(`- ${step}`);
        }
        lines.push("");
    }
    return lines.join("\n");
}
/**
 * Generate JSON report
 */
export function formatComplianceReportAsJson(report) {
    return JSON.stringify(report, null, 2);
}
/**
 * Generate compact summary for CI
 */
export function generateCompactComplianceSummary(report) {
    const status = report.status.complianceScore >= 90
        ? "COMPLIANT"
        : report.status.complianceScore >= 70
            ? "AT_RISK"
            : "NON_COMPLIANT";
    return [
        `${report.framework} Compliance: ${status}`,
        `Score: ${report.status.complianceScore}%`,
        `Risk: ${report.status.riskScore}%`,
        `Controls: ${report.status.controlsCovered}/${report.status.totalControls} compliant`,
        `Non-Compliant: ${report.status.controlsNonCompliant}`,
    ].join(" | ");
}
/**
 * Healthcare-specific compliance report for HIPAA and 42 CFR Part 2
 *
 * This format is designed for audit defensibility, including:
 * - Combined HIPAA and 42 CFR Part 2 assessment
 * - Evidence bundle attestation
 * - Audit trail verification
 * - Cross-mapped controls
 */
export function formatHealthcareComplianceReportAsMarkdown(hipaaReport, cfr42Report, evidenceBundle, auditVerification) {
    const lines = [];
    // Header
    lines.push("# Healthcare Compliance Assessment Report");
    lines.push("");
    lines.push("## Assessment Overview");
    lines.push("");
    lines.push(`**Generated:** ${new Date().toLocaleString()}`);
    lines.push(`**Project:** ${hipaaReport.projectPath}`);
    if (hipaaReport.certificationId) {
        lines.push(`**Certification ID:** ${hipaaReport.certificationId}`);
    }
    lines.push("");
    lines.push("### Applicable Regulations");
    lines.push("");
    lines.push("| Regulation | Description |");
    lines.push("|------------|-------------|");
    lines.push("| **HIPAA** | Health Insurance Portability and Accountability Act - Security Rule |");
    lines.push("| **42 CFR Part 2** | Confidentiality of Substance Use Disorder Patient Records |");
    lines.push("");
    // Executive Summary
    lines.push("## Executive Summary");
    lines.push("");
    const overallHipaa = hipaaReport.status.complianceScore >= 90 ? "Compliant" :
        hipaaReport.status.complianceScore >= 70 ? "At Risk" : "Non-Compliant";
    const overallCfr42 = cfr42Report.status.complianceScore >= 90 ? "Compliant" :
        cfr42Report.status.complianceScore >= 70 ? "At Risk" : "Non-Compliant";
    const hipaaIcon = overallHipaa === "Compliant" ? "✅" : overallHipaa === "At Risk" ? "⚠️" : "❌";
    const cfr42Icon = overallCfr42 === "Compliant" ? "✅" : overallCfr42 === "At Risk" ? "⚠️" : "❌";
    lines.push("| Framework | Status | Score | Risk Score | Non-Compliant Controls |");
    lines.push("|-----------|--------|-------|------------|------------------------|");
    lines.push(`| ${hipaaIcon} HIPAA Security Rule | ${overallHipaa} | ${hipaaReport.status.complianceScore}% | ${hipaaReport.status.riskScore}% | ${hipaaReport.status.controlsNonCompliant} |`);
    lines.push(`| ${cfr42Icon} 42 CFR Part 2 | ${overallCfr42} | ${cfr42Report.status.complianceScore}% | ${cfr42Report.status.riskScore}% | ${cfr42Report.status.controlsNonCompliant} |`);
    lines.push("");
    // Audit Trail Verification (using helper function)
    if (auditVerification) {
        lines.push(formatAuditTrailSection(auditVerification));
    }
    // Evidence Bundle (using helper function)
    if (evidenceBundle) {
        lines.push(formatEvidenceBundleSection(evidenceBundle));
    }
    // HIPAA Findings
    lines.push("## HIPAA Security Rule Assessment");
    lines.push("");
    lines.push(generateStatusBadge(hipaaReport.status.complianceScore));
    lines.push("");
    if (hipaaReport.nonCompliantControls.length > 0) {
        lines.push("### Non-Compliant Controls");
        lines.push("");
        for (const ctrl of hipaaReport.nonCompliantControls) {
            lines.push(formatControlSection(ctrl));
        }
    }
    if (hipaaReport.atRiskControls.length > 0) {
        lines.push("### At-Risk Controls");
        lines.push("");
        lines.push("<details>");
        lines.push(`<summary>${hipaaReport.atRiskControls.length} controls at risk</summary>`);
        lines.push("");
        for (const ctrl of hipaaReport.atRiskControls) {
            lines.push(formatControlSection(ctrl));
        }
        lines.push("</details>");
        lines.push("");
    }
    // 42 CFR Part 2 Findings
    lines.push("## 42 CFR Part 2 Assessment");
    lines.push("");
    lines.push(generateStatusBadge(cfr42Report.status.complianceScore));
    lines.push("");
    if (cfr42Report.nonCompliantControls.length > 0) {
        lines.push("### Non-Compliant Controls");
        lines.push("");
        for (const ctrl of cfr42Report.nonCompliantControls) {
            lines.push(formatControlSection(ctrl));
        }
    }
    if (cfr42Report.atRiskControls.length > 0) {
        lines.push("### At-Risk Controls");
        lines.push("");
        lines.push("<details>");
        lines.push(`<summary>${cfr42Report.atRiskControls.length} controls at risk</summary>`);
        lines.push("");
        for (const ctrl of cfr42Report.atRiskControls) {
            lines.push(formatControlSection(ctrl));
        }
        lines.push("</details>");
        lines.push("");
    }
    // Combined Recommendations
    const allRecs = [
        ...hipaaReport.recommendations.map(r => ({ ...r, framework: "HIPAA" })),
        ...cfr42Report.recommendations.map(r => ({ ...r, framework: "42 CFR Part 2" })),
    ].sort((a, b) => {
        const priority = { critical: 4, high: 3, medium: 2, low: 1 };
        return (priority[b.priority] || 0) - (priority[a.priority] || 0);
    });
    if (allRecs.length > 0) {
        lines.push("## Prioritized Recommendations");
        lines.push("");
        lines.push("Actions prioritized by risk across both frameworks:");
        lines.push("");
        lines.push(formatRecommendations(allRecs.slice(0, 10)));
    }
    // Attestation
    lines.push("## Attestation");
    lines.push("");
    lines.push("This report was generated through automated security scanning and compliance mapping.");
    lines.push("The assessment methodology includes:");
    lines.push("");
    lines.push("1. **Deterministic Scanning:** Pattern-based detection of PHI exposure, consent validation gaps, and audit trail deficiencies");
    lines.push("2. **Finding-to-Control Mapping:** Automated mapping of security findings to compliance framework controls");
    lines.push("3. **Tamper-Evident Logging:** Hash-chained audit trail with optional Sigstore signing");
    lines.push("4. **Evidence Collection:** Cryptographically attested artifacts for audit defensibility");
    lines.push("");
    lines.push("### Scope Limitations");
    lines.push("");
    lines.push("This automated assessment does **NOT** replace:");
    lines.push("- Formal SOC 2 or HIPAA auditor review");
    lines.push("- Organizational policies and procedures documentation");
    lines.push("- Physical security controls assessment");
    lines.push("- Employee training verification");
    lines.push("- Business Associate Agreement review");
    lines.push("- Incident response procedure verification");
    lines.push("");
    // Footer
    lines.push("---");
    lines.push("");
    lines.push(`_Generated by [Vaspera Hardening](https://github.com/RCOLKITT/hardening-mcp) | Healthcare Compliance Module_`);
    return lines.join("\n");
}
//# sourceMappingURL=report.js.map