// engine/compliance-reporter.ts — SPEC-371: Compliance & Audit Reports
// ---------------------------------------------------------------------------
// SOC2 controls mapped to Planu features
// ---------------------------------------------------------------------------
function getSoc2Controls() {
    return [
        {
            id: 'CC6',
            name: 'Logical and Physical Access Controls',
            description: 'Access to specs requires approval workflow',
            status: 'satisfied',
            evidence: 'Planu approval workflow enforces review before spec transitions',
        },
        {
            id: 'CC7',
            name: 'System Operations',
            description: 'Audit trail captures all spec operations',
            status: 'satisfied',
            evidence: 'audit_trail tool records create/update/approve/validate events',
        },
        {
            id: 'CC8',
            name: 'Change Management',
            description: 'Spec versioning tracks all changes',
            status: 'satisfied',
            evidence: 'spec_version_history captures diffs for every spec update',
        },
        {
            id: 'A1',
            name: 'Availability',
            description: 'Data stored locally with no single point of failure',
            status: 'satisfied',
            evidence: 'JSON files in data/ directory with atomic writes',
        },
    ];
}
function getIso27001Controls() {
    return [
        {
            id: 'A.8.1',
            name: 'Responsibility for Assets',
            description: 'Specs assigned to owners via role management',
            status: 'partial',
            evidence: 'assign_role tool exists; not always used',
            recommendation: 'Enforce role assignment on spec creation',
        },
        {
            id: 'A.12.4',
            name: 'Logging and Monitoring',
            description: 'Audit trail covers spec lifecycle events',
            status: 'satisfied',
            evidence: 'audit_trail stores immutable event log',
        },
        {
            id: 'A.14.2',
            name: 'Security in Development',
            description: 'Specs validated before implementation',
            status: 'satisfied',
            evidence: 'validate tool enforces acceptance criteria before done status',
        },
    ];
}
function getGdprControls() {
    return [
        {
            id: 'Art.5',
            name: 'Data Minimization',
            description: 'Only spec content stored — no personal data collected',
            status: 'satisfied',
            evidence: 'Planu stores only spec content and project metadata',
        },
        {
            id: 'Art.17',
            name: 'Right to Erasure',
            description: 'delete_spec and delete_project remove all data',
            status: 'satisfied',
            evidence: 'delete_spec tool removes spec files; delete_project removes project dir',
        },
        {
            id: 'Art.32',
            name: 'Security of Processing',
            description: 'Data stored locally; no external transmission',
            status: 'partial',
            evidence: 'Telemetry opt-in sends anonymized data',
            recommendation: 'Document telemetry data types in privacy notice',
        },
    ];
}
function getHipaaControls() {
    return [
        {
            id: '164.312(b)',
            name: 'Audit Controls',
            description: 'Audit trail records all access and modifications',
            status: 'satisfied',
            evidence: 'audit_trail tool available',
        },
        {
            id: '164.312(e)(1)',
            name: 'Transmission Security',
            description: 'MCP transport security',
            status: 'partial',
            evidence: 'MCP uses stdio by default; HTTP transport requires TLS configuration',
            recommendation: 'Enable HTTPS transport with TLS for network deployments',
        },
    ];
}
function getControls(standard) {
    switch (standard) {
        case 'soc2-type2':
            return getSoc2Controls();
        case 'iso27001':
            return getIso27001Controls();
        case 'gdpr':
            return getGdprControls();
        case 'hipaa':
            return getHipaaControls();
        case 'custom':
            return getSoc2Controls();
    }
}
export function generateComplianceReport(_projectPath, standard, format) {
    const controls = getControls(standard);
    const satisfiedCount = controls.filter((c) => c.status === 'satisfied').length;
    const overallStatus = satisfiedCount === controls.length
        ? 'compliant'
        : satisfiedCount > 0
            ? 'partial'
            : 'non-compliant';
    const report = {
        standard,
        generatedAt: new Date().toISOString(),
        controls,
        overallStatus,
        summary: `${standard.toUpperCase()} compliance assessment: ${satisfiedCount}/${controls.length} controls satisfied.`,
    };
    if (format === 'json') {
        return { content: JSON.stringify(report, null, 2), mimeType: 'application/json' };
    }
    // HTML format
    const rows = controls
        .map((c) => `<tr>
          <td>${c.id}</td>
          <td>${c.name}</td>
          <td class="${c.status}">${c.status}</td>
          <td>${c.evidence ?? ''}</td>
          <td>${c.recommendation ?? ''}</td>
        </tr>`)
        .join('\n');
    const html = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>${standard.toUpperCase()} Compliance Report</title>
  <style>
    body { font-family: sans-serif; padding: 2rem; }
    h1 { color: #1a1a2e; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }
    th { background: #f0f0f0; }
    .satisfied { color: green; font-weight: bold; }
    .partial { color: orange; }
    .gap { color: red; font-weight: bold; }
  </style>
</head>
<body>
  <h1>${standard.toUpperCase()} Compliance Report</h1>
  <p>Generated: ${report.generatedAt}</p>
  <p>Status: <strong>${overallStatus}</strong> — ${report.summary}</p>
  <table>
    <thead><tr><th>Control</th><th>Name</th><th>Status</th><th>Evidence</th><th>Recommendation</th></tr></thead>
    <tbody>${rows}</tbody>
  </table>
</body>
</html>`;
    return { content: html, mimeType: 'text/html' };
}
export function exportAuditLog(specs, format, dateRange) {
    // Build synthetic audit entries from spec history
    const entries = specs.map((s) => ({
        timestamp: s.updatedAt,
        specId: s.id,
        title: s.title,
        status: s.status,
        action: 'status-change',
        actor: 'system',
    }));
    // Apply date filter
    const filtered = entries.filter((e) => {
        const ts = new Date(e.timestamp).getTime();
        if (dateRange?.from && ts < new Date(dateRange.from).getTime()) {
            return false;
        }
        if (dateRange?.to && ts > new Date(dateRange.to).getTime()) {
            return false;
        }
        return true;
    });
    if (format === 'csv') {
        const header = 'timestamp,specId,title,status,action,actor';
        const rows = filtered.map((e) => `"${e.timestamp}","${e.specId}","${e.title}","${e.status}","${e.action}","${e.actor}"`);
        return [header, ...rows].join('\n');
    }
    if (format === 'json-ld') {
        return JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'ItemList',
            items: filtered,
        }, null, 2);
    }
    return JSON.stringify(filtered, null, 2);
}
export function analyzeComplianceGaps(standard) {
    const controls = getControls(standard);
    const gaps = [];
    for (const control of controls) {
        if (control.status === 'gap' || control.status === 'partial') {
            gaps.push({
                controlId: control.id,
                controlName: control.name,
                gap: control.recommendation ?? 'Not fully implemented',
                recommendation: control.recommendation ?? 'Review and implement missing controls',
                severity: control.status === 'gap' ? 'critical' : 'medium',
            });
        }
    }
    // Standard-specific known gaps
    if (standard === 'soc2-type2' || standard === 'iso27001') {
        gaps.push({
            controlId: 'AUTH',
            controlName: 'Multi-Factor Authentication',
            gap: 'No MFA configured for Planu server access',
            recommendation: 'Implement MFA for HTTP transport endpoints',
            severity: 'high',
        }, {
            controlId: 'ENC',
            controlName: 'Encryption at Rest',
            gap: 'Audit logs not encrypted at rest',
            recommendation: 'Enable filesystem-level encryption or use encrypted storage',
            severity: 'high',
        });
    }
    return gaps;
}
//# sourceMappingURL=compliance-reporter.js.map