// testing/cassette/store.ts — Cassette file I/O (SPEC-743)
import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
/**
 * Base directory for cassette files.
 * Cassettes live at tests/cassettes/<name>.json.
 */
const CASSETTES_BASE = resolve('tests', 'cassettes');
/**
 * Resolve full path to a cassette file.
 */
export function getCassettePath(name) {
    // Ensure .json extension
    const file = name.endsWith('.json') ? name : `${name}.json`;
    return join(CASSETTES_BASE, file);
}
/**
 * Load a cassette from disk.
 * Throws if file does not exist.
 */
export function loadCassetteFromDisk(name) {
    const path = getCassettePath(name);
    try {
        const raw = readFileSync(path, 'utf-8');
        return JSON.parse(raw);
    }
    catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        throw new Error(`Cassette not found: ${path}. ${msg}`, { cause: err });
    }
}
/**
 * Write a cassette to disk (record mode).
 * Creates parent directories as needed.
 */
export function saveCassetteToDisk(name, cassette) {
    const path = getCassettePath(name);
    mkdirSync(dirname(path), { recursive: true });
    writeFileSync(path, JSON.stringify(cassette, null, 2) + '\n', 'utf-8');
}
/**
 * Add or update an entry in an existing cassette (by sha).
 * Creates a new cassette if none exists.
 */
export function upsertCassetteEntry(name, entry) {
    let cassette;
    try {
        cassette = loadCassetteFromDisk(name);
    }
    catch {
        cassette = {
            version: 1,
            createdAt: new Date().toISOString(),
            entries: [],
        };
    }
    const idx = cassette.entries.findIndex((e) => e.requestSha === entry.requestSha);
    if (idx >= 0) {
        cassette.entries[idx] = entry;
    }
    else {
        cassette.entries.push(entry);
    }
    saveCassetteToDisk(name, cassette);
}
//# sourceMappingURL=store.js.map