/**
 * Facade for audit chain verification and trust evaluation.
 *
 * Composes AuditChainVerifier (chain walking) and TrustEvaluationService
 * (signed evidence evaluation) into a single service interface consumed
 * by WarpRuntime.
 *
 * @module domain/services/audit/AuditVerifierService
 */
import { buildAuditPrefix } from "../../utils/RefLayout.js";
import AuditChainVerifier from "./AuditChainVerifier.js";
import TrustEvaluationService from "./TrustEvaluationService.js";
export default class AuditVerifierService {
    _chainVerifier;
    _trustService;
    _persistence;
    logger;
    constructor(opts) {
        this._persistence = opts.persistence;
        this.logger = opts.logger ?? null;
        this._chainVerifier = new AuditChainVerifier(opts.persistence, opts.codec);
        this._trustService = new TrustEvaluationService({
            listWriterIds: (graphName) => this._listWriterIds(graphName),
            ...(opts.trustChain !== undefined ? { trustChain: opts.trustChain } : {}),
            ...(opts.trustCrypto !== undefined ? { trustCrypto: opts.trustCrypto } : {}),
        });
    }
    /** Verifies all audit chains for a graph. */
    async verifyAll(graphName, options = {}) {
        const chains = await this._verifyAllChains(graphName, options.since);
        return this._buildVerifyResult(graphName, chains, options);
    }
    async _verifyAllChains(graphName, since) {
        const writerIds = await this._listWriterIds(graphName);
        const chains = [];
        for (const writerId of writerIds.sort()) {
            const result = await this._chainVerifier.verifyChain(graphName, writerId, since !== undefined ? { since } : {});
            chains.push(result);
        }
        return chains;
    }
    _buildVerifyResult(graphName, chains, options) {
        const valid = chains.filter((c) => c.status === 'VALID').length;
        const partial = chains.filter((c) => c.status === 'PARTIAL').length;
        return {
            graph: graphName,
            verifiedAt: options.verifiedAt ?? '',
            summary: { total: chains.length, valid, partial, invalid: chains.length - valid - partial },
            chains,
            trustWarning: options.trustWarning ?? null,
        };
    }
    /** Verifies a single writer's audit chain. */
    async verifyChain(graphName, writerId, options) {
        return await this._chainVerifier.verifyChain(graphName, writerId, options);
    }
    /** Evaluates trust for all writers of a graph using signed evidence. */
    async evaluateTrust(graphName, options) {
        return await this._trustService.evaluateTrust(graphName, options);
    }
    async _listWriterIds(graphName) {
        const prefix = buildAuditPrefix(graphName);
        const refs = await this._persistence.listRefs(prefix);
        return refs
            .map((ref) => ref.slice(prefix.length))
            .filter((id) => id.length > 0);
    }
}
