/**
 * Loads the consumer's verifier module via the same jiti mechanism as the
 * config layer, so a TypeScript verifier needs no build step. Each call is
 * timeout-guarded and verdict-validated — it is arbitrary consumer code.
 *
 * @see docs/decisions/D0047-deterministic-symbol-preflight-lane-separation.md
 */
import { fileURLToPath } from "node:url";
import { ConsumerVerificationVerdictSchema, DEFAULT_CONSUMER_VERIFICATION_TIMEOUT_MS, } from "../../_vendor/ailf-core/index.js";
import { loadTsConfig } from "../../adapters/config-sources/ts-config-loader.js";
/**
 * Load the module named by {@link ConsumerVerificationConfig.module}, wrapped
 * with per-call timeout + verdict validation. Throws on load failure or a
 * non-function default export — the caller decides how to degrade.
 */
export async function loadVerifier(config) {
    const modulePath = config.module.startsWith("file://")
        ? fileURLToPath(config.module)
        : config.module;
    const result = await loadTsConfig(modulePath);
    if (!result.ok) {
        throw new Error(result.error);
    }
    if (typeof result.value !== "function") {
        throw new Error(`Verifier module must default-export a function, got ${typeof result.value}: ${config.module}`);
    }
    const verify = result.value;
    const timeoutMs = config.timeoutMs ?? DEFAULT_CONSUMER_VERIFICATION_TIMEOUT_MS;
    return async (output, context) => {
        const raw = await withTimeout(Promise.resolve(verify(output, context)), timeoutMs);
        const parsed = ConsumerVerificationVerdictSchema.safeParse(raw);
        if (!parsed.success) {
            throw new Error(`Verifier returned an invalid verdict: ${parsed.error.message}`);
        }
        return parsed.data;
    };
}
/**
 * Thrown when a verifier call exceeds its per-call timeout. A distinct
 * class (rather than message matching) lets `emitConsumerVerification` tell
 * timeouts apart from other verifier failures for its circuit breaker.
 */
export class VerifierTimeoutError extends Error {
    constructor(ms) {
        super(`verifier timed out after ${ms}ms`);
        this.name = "VerifierTimeoutError";
    }
}
async function withTimeout(promise, ms) {
    let timer;
    const timeout = new Promise((_, reject) => {
        timer = setTimeout(() => reject(new VerifierTimeoutError(ms)), ms);
    });
    try {
        return await Promise.race([promise, timeout]);
    }
    finally {
        clearTimeout(timer);
    }
}
