"use strict";
/**
 * EvidenceCollector -- Collects and exports audit evidence packages.
 *
 * Gathers audit log entries, configuration snapshots, governance file
 * hashes, and compliance reports into a structured evidence package
 * suitable for auditor consumption.
 *
 * GATE 11: Compliance Audit Bot System (T-157)
 *
 * @connexum/ai-governance
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EvidenceCollector = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const crypto = __importStar(require("crypto"));
class EvidenceCollector {
    logDir;
    governanceDir;
    outputDir;
    constructor(config) {
        this.logDir = config.logDir;
        this.governanceDir = config.governanceDir;
        this.outputDir = config.outputDir;
        if (!fs.existsSync(this.outputDir)) {
            fs.mkdirSync(this.outputDir, { recursive: true });
        }
    }
    /**
     * Collect evidence for a given audit result.
     */
    collect(auditResult) {
        const now = new Date().toISOString();
        const artifacts = [];
        // 1. Audit report itself as a report artifact
        artifacts.push({
            type: 'report',
            name: `audit-result-${auditResult.packId}`,
            content: JSON.stringify(auditResult, null, 2),
            timestamp: now,
        });
        // 2. Collect audit log entries
        const logArtifacts = this.collectLogs();
        artifacts.push(...logArtifacts);
        // 3. Collect configuration snapshots from governance dir
        const configArtifacts = this.collectConfigs();
        artifacts.push(...configArtifacts);
        // 4. Collect governance file hashes
        const hashArtifacts = this.collectHashes();
        artifacts.push(...hashArtifacts);
        // Build summary
        const summary = this.buildSummary(auditResult, artifacts);
        return {
            auditId: auditResult.auditId,
            collectedAt: now,
            artifacts,
            summary,
        };
    }
    /**
     * Export an evidence package to a JSON file. Returns the file path.
     */
    export(pkg) {
        const filename = `evidence-${pkg.auditId || 'unscheduled'}-${Date.now()}.json`;
        const filePath = path.join(this.outputDir, filename);
        fs.writeFileSync(filePath, JSON.stringify(pkg, null, 2));
        return filePath;
    }
    // --- Collection helpers ---
    collectLogs() {
        const artifacts = [];
        if (!fs.existsSync(this.logDir))
            return artifacts;
        const logFiles = fs.readdirSync(this.logDir).filter((f) => f.endsWith('.jsonl'));
        for (const file of logFiles.slice(0, 10)) {
            // Cap at 10 log files
            try {
                const content = fs.readFileSync(path.join(this.logDir, file), 'utf-8');
                artifacts.push({
                    type: 'log',
                    name: file,
                    content,
                    timestamp: new Date().toISOString(),
                });
            }
            catch {
                // Skip unreadable files
            }
        }
        return artifacts;
    }
    collectConfigs() {
        const artifacts = [];
        if (!fs.existsSync(this.governanceDir))
            return artifacts;
        const configFiles = fs
            .readdirSync(this.governanceDir)
            .filter((f) => f.endsWith('.json') || f.endsWith('.md'));
        for (const file of configFiles) {
            try {
                const content = fs.readFileSync(path.join(this.governanceDir, file), 'utf-8');
                artifacts.push({
                    type: 'config',
                    name: file,
                    content,
                    timestamp: new Date().toISOString(),
                });
            }
            catch {
                // Skip unreadable files
            }
        }
        return artifacts;
    }
    collectHashes() {
        const artifacts = [];
        if (!fs.existsSync(this.governanceDir))
            return artifacts;
        const files = fs.readdirSync(this.governanceDir);
        const hashes = {};
        for (const file of files) {
            try {
                const fullPath = path.join(this.governanceDir, file);
                const stat = fs.statSync(fullPath);
                if (!stat.isFile())
                    continue;
                const content = fs.readFileSync(fullPath);
                const hash = crypto.createHash('sha256').update(content).digest('hex');
                hashes[file] = hash;
            }
            catch {
                // Skip unreadable files
            }
        }
        if (Object.keys(hashes).length > 0) {
            artifacts.push({
                type: 'hash',
                name: 'governance-file-hashes',
                content: JSON.stringify(hashes, null, 2),
                timestamp: new Date().toISOString(),
            });
        }
        return artifacts;
    }
    buildSummary(result, artifacts) {
        const logCount = artifacts.filter((a) => a.type === 'log').length;
        const configCount = artifacts.filter((a) => a.type === 'config').length;
        const reportCount = artifacts.filter((a) => a.type === 'report').length;
        const hashCount = artifacts.filter((a) => a.type === 'hash').length;
        return (`Evidence package for ${result.packId} audit (${result.auditId || 'unscheduled'}). ` +
            `Audit score: ${result.score}/100 (${result.passed} passed, ${result.failed} failed, ${result.warnings} warnings). ` +
            `Collected ${artifacts.length} artifacts: ${logCount} logs, ${configCount} configs, ${reportCount} reports, ${hashCount} hash records.`);
    }
}
exports.EvidenceCollector = EvidenceCollector;
//# sourceMappingURL=evidence.js.map