export const DEFAULT_TTL_MS = 1000 * 60 * 60 * 24 * 7;
export const NEGATIVE_TTL_MS = 1000 * 60 * 60 * 6;
export const readTranscriptCache = async ({ url, cacheMode, transcriptCache, transcriptTimestamps = false, transcriptDiarization = null, fileMtime, }) => {
    const cached = transcriptCache
        ? await transcriptCache.get({ url, fileMtime: fileMtime ?? null })
        : null;
    const diagnostics = buildBaseDiagnostics(cacheMode);
    if (!cached) {
        return { cached: null, resolution: null, diagnostics };
    }
    const provider = mapCachedSource(cached.source);
    diagnostics.provider = provider;
    diagnostics.attemptedProviders = provider ? [provider] : [];
    diagnostics.textProvided = Boolean(cached.content && cached.content.length > 0);
    if (cacheMode === "bypass") {
        diagnostics.notes = appendNote(diagnostics.notes, "Cached transcript ignored due to bypass request");
        return { cached, resolution: null, diagnostics };
    }
    if (cached.expired) {
        diagnostics.cacheStatus = "expired";
        diagnostics.notes = appendNote(diagnostics.notes, "Cached transcript expired; fetching fresh copy");
        return { cached, resolution: null, diagnostics };
    }
    diagnostics.cacheStatus = "hit";
    diagnostics.notes = appendNote(diagnostics.notes, "Served transcript from cache");
    const cachedSegments = extractSegments(cached.metadata);
    const hasSegments = Boolean(cachedSegments && cachedSegments.length > 0);
    const hasSpeakerLabels = cached.metadata?.speakerLabels === true;
    if (!transcriptDiarization && hasSpeakerLabels) {
        diagnostics.notes = appendNote(diagnostics.notes, "Cached transcript includes speaker labels; fetching fresh copy");
        return { cached, resolution: null, diagnostics };
    }
    const timestampsFlag = cached.metadata?.timestamps;
    if (transcriptTimestamps &&
        timestampsFlag !== false &&
        (cachedSegments == null || cachedSegments.length === 0)) {
        diagnostics.notes = appendNote(diagnostics.notes, "Cached transcript missing timestamps; fetching fresh copy");
        return { cached, resolution: null, diagnostics };
    }
    if (transcriptTimestamps && timestampsFlag === false) {
        diagnostics.notes = appendNote(diagnostics.notes, "Transcript timestamps unavailable");
    }
    if (transcriptDiarization) {
        if (!isCachedDiarizationCompatible(cached.metadata, transcriptDiarization)) {
            diagnostics.notes = appendNote(diagnostics.notes, "Cached transcript missing requested speaker labels; fetching fresh copy");
            return { cached, resolution: null, diagnostics };
        }
    }
    const resolution = {
        text: cached.content,
        source: provider,
        metadata: cached.metadata ?? null,
        segments: transcriptTimestamps && hasSegments ? cachedSegments : null,
    };
    return { cached, resolution, diagnostics };
};
export function isCachedDiarizationCompatible(metadata, preference) {
    const hasSpeakerLabels = metadata?.speakerLabels === true;
    if (!preference)
        return !hasSpeakerLabels;
    const provider = metadata?.diarizationProvider;
    return hasSpeakerLabels && (preference === "auto" || provider === preference);
}
const buildBaseDiagnostics = (cacheMode) => ({
    cacheMode,
    cacheStatus: cacheMode === "bypass" ? "bypassed" : "miss",
    provider: null,
    attemptedProviders: [],
    textProvided: false,
    notes: cacheMode === "bypass" ? "Cache bypass requested" : null,
});
const appendNote = (existing, next) => {
    if (!existing) {
        return next;
    }
    return `${existing}; ${next}`;
};
export const mapCachedSource = (source) => {
    if (source === null)
        return null;
    if (source === "youtubei" ||
        source === "captionTracks" ||
        source === "embedded" ||
        source === "yt-dlp" ||
        source === "podcastTranscript" ||
        source === "whisper" ||
        source === "apify" ||
        source === "html" ||
        source === "unavailable") {
        return source;
    }
    return "unknown";
};
export const writeTranscriptCache = async ({ url, service, resourceKey, result, transcriptCache, fileMtime, }) => {
    if (!transcriptCache) {
        return;
    }
    if (result.source === null && result.text === null) {
        return;
    }
    const ttlMs = result.text ? DEFAULT_TTL_MS : NEGATIVE_TTL_MS;
    const resolvedSource = result.source ?? (result.text ? "unknown" : "unavailable");
    await transcriptCache.set({
        url,
        service,
        resourceKey,
        ttlMs,
        content: result.text,
        source: resolvedSource,
        metadata: result.metadata ?? null,
        fileMtime,
    });
};
function extractSegments(metadata) {
    if (!metadata)
        return null;
    const segments = metadata.segments;
    if (!Array.isArray(segments))
        return null;
    const normalized = segments.filter((segment) => segment && typeof segment === "object");
    return normalized.length > 0 ? normalized : null;
}
//# sourceMappingURL=cache.js.map