// tools/export-audit-trail-handler.ts — Handler for export_audit_trail tool (SPEC-387)
import { readEntries } from '../storage/audit-trail-store.js';
import { verifyChain } from '../engine/audit-trail/hasher.js';
import { formatSuccess, toolResult } from './response-helpers.js';
// ---------------------------------------------------------------------------
// Formatters
// ---------------------------------------------------------------------------
function formatJson(entries) {
    return JSON.stringify(entries, null, 2);
}
function formatJsonLd(entries) {
    const graph = entries.map((e) => ({
        '@type': 'prov:Activity',
        '@id': `urn:planu:audit:${e.id}`,
        'prov:startedAtTime': e.timestamp,
        'prov:endedAtTime': e.timestamp,
        'planu:toolName': e.toolName,
        'planu:inputSummary': e.inputSummary,
        'planu:outputType': e.outputType,
        'planu:durationMs': e.durationMs,
        'planu:hash': e.hash,
        'planu:prevHash': e.prevHash,
        ...(e.specId !== undefined ? { 'planu:specId': e.specId } : {}),
        ...(e.projectPath !== undefined ? { 'planu:projectPath': e.projectPath } : {}),
    }));
    const doc = {
        '@context': {
            prov: 'http://www.w3.org/ns/prov#',
            planu: 'https://planu.dev/vocab#',
        },
        '@graph': graph,
    };
    return JSON.stringify(doc, null, 2);
}
function formatCsv(entries) {
    const header = 'id,timestamp,toolName,outputType,durationMs,specId,projectPath,hash,prevHash,inputSummary';
    const rows = entries.map((e) => {
        const cols = [
            e.id,
            e.timestamp,
            e.toolName,
            e.outputType,
            String(e.durationMs),
            e.specId ?? '',
            e.projectPath ?? '',
            e.hash,
            e.prevHash,
            `"${e.inputSummary.replace(/"/g, '""')}"`,
        ];
        return cols.join(',');
    });
    return [header, ...rows].join('\n');
}
function renderFormat(format, entries) {
    switch (format) {
        case 'json':
            return formatJson(entries);
        case 'json-ld':
            return formatJsonLd(entries);
        case 'csv':
            return formatCsv(entries);
    }
}
// ---------------------------------------------------------------------------
// Handler
// ---------------------------------------------------------------------------
/**
 * Handle export_audit_trail tool invocation.
 * Reads the global audit trail, applies filters, verifies chain integrity,
 * and returns formatted output in the requested format.
 */
export function handleExportAuditTrail(input) {
    const format = input.format ?? 'json';
    const allEntries = readEntries({
        fromDate: input.fromDate,
        toDate: input.toDate,
        specId: input.specId,
        projectPath: input.projectPath,
        limit: input.limit,
    });
    // Verify chain on the full unfiltered set for accurate integrity reporting
    const fullEntries = readEntries();
    const integrityValid = verifyChain(fullEntries);
    const formatted = renderFormat(format, allEntries);
    const exportedAt = new Date().toISOString();
    const result = {
        entries: allEntries,
        totalCount: allEntries.length,
        format,
        exportedAt,
        integrityValid,
    };
    const summary = [
        `Audit Trail Export — SPEC-387 (EU AI Act Article 12)`,
        `Entries: ${String(allEntries.length)} | Format: ${format}`,
        `Chain integrity: ${integrityValid ? 'VALID' : 'BROKEN'}`,
        `Exported at: ${exportedAt}`,
        '',
        formatted,
    ].join('\n');
    return toolResult(formatSuccess('Audit Trail Export', summary), result);
}
//# sourceMappingURL=export-audit-trail-handler.js.map