// storage/token-cache-store.ts — Persistent token cache (SPEC-082 AC-13)
import { existsSync, mkdirSync, readFileSync, writeFileSync, statSync } from 'node:fs';
import { join, dirname } from 'node:path';
const DEFAULT_MAX_SIZE_MB = 5;
/**
 * Persists cache entries to JSON files in the project data directory.
 */
export function loadTokenCache(projectHash, dataDir) {
    const filePath = getTokenCachePath(projectHash, dataDir);
    if (!existsSync(filePath)) {
        return [];
    }
    try {
        // Check file size
        const stat = statSync(filePath);
        const sizeMb = stat.size / (1024 * 1024);
        if (sizeMb > DEFAULT_MAX_SIZE_MB) {
            return [];
        }
        const raw = readFileSync(filePath, 'utf-8');
        const parsed = JSON.parse(raw);
        if (!Array.isArray(parsed)) {
            return [];
        }
        const now = Date.now();
        return parsed.filter((entry) => typeof entry.expiresAt === 'number' && entry.expiresAt > now);
    }
    catch {
        return [];
    }
}
/**
 * Save cache entries to disk.
 */
export function saveTokenCache(projectHash, dataDir, entries) {
    const filePath = getTokenCachePath(projectHash, dataDir);
    const dir = dirname(filePath);
    if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
    }
    const json = JSON.stringify(entries, null, 2);
    const sizeMb = Buffer.byteLength(json, 'utf-8') / (1024 * 1024);
    if (sizeMb > DEFAULT_MAX_SIZE_MB) {
        const sorted = [...entries].sort((a, b) => b.createdAt - a.createdAt);
        const trimmed = [];
        let totalSize = 0;
        const maxBytes = DEFAULT_MAX_SIZE_MB * 1024 * 1024;
        for (const entry of sorted) {
            const entrySize = Buffer.byteLength(JSON.stringify(entry), 'utf-8');
            if (totalSize + entrySize > maxBytes) {
                break;
            }
            trimmed.push(entry);
            totalSize += entrySize;
        }
        writeFileSync(filePath, JSON.stringify(trimmed, null, 2), 'utf-8');
        return;
    }
    writeFileSync(filePath, json, 'utf-8');
}
/**
 * Get the file path for the token cache.
 */
function getTokenCachePath(projectHash, dataDir) {
    return join(dataDir, 'projects', projectHash, 'cache', 'token-cache.json');
}
//# sourceMappingURL=token-cache-store.js.map