// testing/cassette/intercept.ts — Anthropic SDK shimming for cassette replay (SPEC-743)
import { computeRequestSha } from './signature.js';
import { loadCassetteFromDisk, upsertCassetteEntry } from './store.js';
/**
 * Whether we're in recording mode.
 * Set via PLANU_RECORD_CASSETTES=1 env var.
 */
export function isRecordingMode() {
    return process.env.PLANU_RECORD_CASSETTES === '1';
}
/**
 * Error thrown when a cassette entry is not found (hash mismatch).
 */
export class CassetteMissError extends Error {
    cassetteName;
    expectedSha;
    actualSha;
    constructor(cassetteName, expectedSha, actualSha) {
        super(`Cassette miss: expected sha ${expectedSha}, got ${actualSha}. ` +
            `Re-record with PLANU_RECORD_CASSETTES=1. ` +
            `Cassette: tests/cassettes/${cassetteName}.json`);
        this.cassetteName = cassetteName;
        this.expectedSha = expectedSha;
        this.actualSha = actualSha;
        this.name = 'CassetteMissError';
    }
}
/**
 * Creates an interceptor function for a specific cassette.
 *
 * @param cassetteName - Name of the cassette file (without .json)
 * @param realImplementation - The real Anthropic messages.create (used in record mode)
 */
export function createInterceptor(cassetteName, realImplementation) {
    return async (request) => {
        const sha = computeRequestSha(request);
        if (isRecordingMode()) {
            if (realImplementation === undefined) {
                throw new Error('Recording mode requires a real Anthropic client implementation. ' +
                    'Pass the real messages.create function to createInterceptor().');
            }
            // Call real implementation and record result
            const response = await realImplementation(request);
            const entry = {
                requestSha: sha,
                request,
                response,
            };
            upsertCassetteEntry(cassetteName, entry);
            return response;
        }
        // Replay mode: look up in cassette
        const cassette = loadCassetteFromDisk(cassetteName);
        const entry = cassette.entries.find((e) => e.requestSha === sha);
        if (entry === undefined) {
            // Find the first entry's sha for a better error message
            const firstSha = cassette.entries[0]?.requestSha ?? 'no-entries';
            throw new CassetteMissError(cassetteName, firstSha, sha);
        }
        return entry.response;
    };
}
//# sourceMappingURL=intercept.js.map