// tools/audit-trail-handler.ts — Handlers for audit_trail and generate_attestation tools (SPEC-167)
import { queryAuditLog, verifyChainIntegrity, generateAttestation, } from '../engine/audit-trail/index.js';
import { projectDataDir } from '../storage/base-store.js';
import { formatSuccess, formatError, toolResult } from './response-helpers.js';
import { resolveProjectId } from './resolve-project-id.js';
/** Build the path to a project's audit log file. */
function auditLogPath(projectId) {
    return `${projectDataDir(projectId)}/audit-log.jsonl`;
}
// ---------------------------------------------------------------------------
// audit_trail handler
// ---------------------------------------------------------------------------
export async function handleAuditTrail(args) {
    const projectId = resolveProjectId(args);
    if (!projectId) {
        return toolResult(formatError('projectId is required', 'Provide projectId or projectPath.'), undefined, true);
    }
    const filePath = auditLogPath(projectId);
    const [queryResult, chainResult] = await Promise.all([
        queryAuditLog(filePath, {
            projectId,
            specId: args.specId,
            eventType: args.eventType,
            from: args.from,
            to: args.to,
            limit: args.limit,
        }),
        verifyChainIntegrity(filePath),
    ]);
    const integrityLabel = chainResult.valid
        ? 'Chain: INTACT'
        : `Chain: BROKEN (${chainResult.message})`;
    const lines = [
        `Audit Log — ${projectId}`,
        `${String(queryResult.total)} events found | ${integrityLabel}`,
        queryResult.truncated
            ? `(Showing first ${String(queryResult.events.length)} of ${String(queryResult.total)})`
            : '',
        '',
    ].filter((l) => l !== '');
    if (queryResult.events.length === 0) {
        lines.push('No events match the specified filters.');
    }
    else {
        for (const ev of queryResult.events) {
            const specLabel = ev.specId ? ` [${ev.specId}]` : '';
            const userLabel = ev.userId ? ` by ${ev.userId}` : '';
            lines.push(`• ${ev.timestamp}${specLabel}${userLabel} — ${ev.eventType}: ${ev.action}`);
        }
    }
    const body = lines.join('\n');
    return toolResult(formatSuccess('Audit Trail', body), {
        events: queryResult.events,
        total: queryResult.total,
        truncated: queryResult.truncated,
        chainIntegrity: chainResult,
    });
}
// ---------------------------------------------------------------------------
// generate_attestation handler
// ---------------------------------------------------------------------------
export async function handleGenerateAttestation(args) {
    const projectId = resolveProjectId(args);
    if (!projectId) {
        return toolResult(formatError('projectId is required', 'Provide projectId or projectPath.'), undefined, true);
    }
    if (!args.specId || args.specId.trim().length === 0) {
        return toolResult(formatError('specId is required', 'Provide a spec ID to generate attestation for.'), undefined, true);
    }
    const filePath = auditLogPath(projectId);
    const attestation = await generateAttestation(filePath, projectId, args.specId);
    const { summary } = attestation;
    const chainLabel = attestation.chainValid ? 'INTACT' : 'BROKEN';
    const typeLines = Object.entries(summary.eventTypes)
        .map(([type, count]) => `  • ${type}: ${String(count)}`)
        .join('\n');
    const body = [
        `Attestation ID: ${attestation.attestationId}`,
        `Generated: ${attestation.generatedAt}`,
        `Spec: ${attestation.specId}`,
        `Chain integrity: ${chainLabel}`,
        `Total events: ${String(summary.totalEvents)}`,
        summary.firstEvent ? `First event: ${summary.firstEvent}` : '',
        summary.lastEvent ? `Last event: ${summary.lastEvent}` : '',
        typeLines.length > 0 ? `\nEvent breakdown:\n${typeLines}` : '',
    ]
        .filter(Boolean)
        .join('\n');
    return toolResult(formatSuccess('Attestation Generated', body, [
        'Export this attestation JSON for compliance audits (SOC2/HIPAA/ISO27001).',
        'Verify chain integrity regularly to detect tampering.',
    ]), attestation);
}
//# sourceMappingURL=audit-trail-handler.js.map