"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extendEvalJobTTL = exports.getAllEvalJobIds = exports.hasEvalJob = exports.deleteEvalJob = exports.updateEvalJob = exports.getEvalJob = exports.setEvalJob = void 0;
const logger_1 = __importDefault(require("../logger"));
const redisClient_1 = require("./redisClient");
const REDIS_PREFIX = 'eval_job:';
const DEFAULT_TTL = 60 * 60 * 24; // 24 hours in seconds
// In-memory fallback storage when Redis is unavailable
const inMemoryJobs = new Map();
// Track if we've warned about fallback
let hasWarnedAboutFallback = false;
const warnAboutFallback = () => {
    // Warning is now handled in redisClient.ts during initialization
    // This function is kept for backward compatibility but doesn't log
    // to avoid duplicate warnings
    if (!hasWarnedAboutFallback) {
        logger_1.default.debug('Using in-memory job storage (Redis unavailable)');
        hasWarnedAboutFallback = true;
    }
};
/**
 * Set a job in Redis cache (or in-memory fallback)
 */
const setEvalJob = async (jobId, job) => {
    try {
        if (!(0, redisClient_1.isRedisAvailable)()) {
            // Fallback to in-memory storage
            warnAboutFallback();
            inMemoryJobs.set(jobId, job);
            logger_1.default.debug(`Stored job ${jobId} in memory (Redis unavailable)`);
            return;
        }
        const redis = (0, redisClient_1.getRedisClient)();
        const key = `${REDIS_PREFIX}${jobId}`;
        await redis.setex(key, DEFAULT_TTL, JSON.stringify(job));
    }
    catch (error) {
        logger_1.default.warn(`Failed to set eval job ${jobId} in Redis, falling back to memory: ${error}`);
        warnAboutFallback();
        // Fallback to in-memory storage on error
        inMemoryJobs.set(jobId, job);
    }
};
exports.setEvalJob = setEvalJob;
/**
 * Get a job from Redis cache (or in-memory fallback)
 */
const getEvalJob = async (jobId) => {
    try {
        if (!(0, redisClient_1.isRedisAvailable)()) {
            // Fallback to in-memory storage
            return inMemoryJobs.get(jobId) || null;
        }
        const redis = (0, redisClient_1.getRedisClient)();
        const key = `${REDIS_PREFIX}${jobId}`;
        const data = await redis.get(key);
        if (!data) {
            return null;
        }
        return JSON.parse(data);
    }
    catch (error) {
        logger_1.default.warn(`Failed to get eval job ${jobId} from Redis, checking memory: ${error}`);
        // Fallback to in-memory storage on error
        return inMemoryJobs.get(jobId) || null;
    }
};
exports.getEvalJob = getEvalJob;
/**
 * Update a job in Redis cache (or in-memory fallback)
 */
const updateEvalJob = async (jobId, updates) => {
    try {
        if (!(0, redisClient_1.isRedisAvailable)()) {
            // Fallback to in-memory storage
            const existingJob = inMemoryJobs.get(jobId);
            if (existingJob) {
                inMemoryJobs.set(jobId, { ...existingJob, ...updates });
            }
            return;
        }
        const redis = (0, redisClient_1.getRedisClient)();
        const key = `${REDIS_PREFIX}${jobId}`;
        // Get existing job
        const existingData = await redis.get(key);
        if (!existingData) {
            logger_1.default.warn(`Job ${jobId} not found in Redis for update`);
            return;
        }
        const existingJob = JSON.parse(existingData);
        const updatedJob = { ...existingJob, ...updates };
        // Get remaining TTL
        const ttl = await redis.ttl(key);
        const newTtl = ttl > 0 ? ttl : DEFAULT_TTL;
        await redis.setex(key, newTtl, JSON.stringify(updatedJob));
    }
    catch (error) {
        logger_1.default.warn(`Failed to update eval job ${jobId} in Redis, trying memory: ${error}`);
        // Fallback to in-memory storage on error
        const existingJob = inMemoryJobs.get(jobId);
        if (existingJob) {
            inMemoryJobs.set(jobId, { ...existingJob, ...updates });
        }
    }
};
exports.updateEvalJob = updateEvalJob;
/**
 * Delete a job from Redis cache (or in-memory fallback)
 */
const deleteEvalJob = async (jobId) => {
    try {
        if (!(0, redisClient_1.isRedisAvailable)()) {
            // Fallback to in-memory storage
            inMemoryJobs.delete(jobId);
            return;
        }
        const redis = (0, redisClient_1.getRedisClient)();
        const key = `${REDIS_PREFIX}${jobId}`;
        await redis.del(key);
    }
    catch (error) {
        logger_1.default.warn(`Failed to delete eval job ${jobId} from Redis, trying memory: ${error}`);
        // Fallback to in-memory storage on error
        inMemoryJobs.delete(jobId);
    }
};
exports.deleteEvalJob = deleteEvalJob;
/**
 * Check if a job exists in Redis cache (or in-memory fallback)
 */
const hasEvalJob = async (jobId) => {
    try {
        if (!(0, redisClient_1.isRedisAvailable)()) {
            // Fallback to in-memory storage
            return inMemoryJobs.has(jobId);
        }
        const redis = (0, redisClient_1.getRedisClient)();
        const key = `${REDIS_PREFIX}${jobId}`;
        const exists = await redis.exists(key);
        return exists === 1;
    }
    catch (error) {
        logger_1.default.warn(`Failed to check if eval job ${jobId} exists in Redis, checking memory: ${error}`);
        // Fallback to in-memory storage on error
        return inMemoryJobs.has(jobId);
    }
};
exports.hasEvalJob = hasEvalJob;
/**
 * Get all job IDs (useful for debugging/monitoring)
 */
const getAllEvalJobIds = async () => {
    try {
        if (!(0, redisClient_1.isRedisAvailable)()) {
            // Fallback to in-memory storage
            return Array.from(inMemoryJobs.keys());
        }
        const redis = (0, redisClient_1.getRedisClient)();
        const keys = await redis.keys(`${REDIS_PREFIX}*`);
        return keys.map((key) => key.replace(REDIS_PREFIX, ''));
    }
    catch (error) {
        logger_1.default.warn(`Failed to get all eval job IDs from Redis, using memory: ${error}`);
        // Fallback to in-memory storage on error
        return Array.from(inMemoryJobs.keys());
    }
};
exports.getAllEvalJobIds = getAllEvalJobIds;
/**
 * Extend TTL for a job (no-op for in-memory fallback)
 */
const extendEvalJobTTL = async (jobId, additionalSeconds = 3600) => {
    try {
        if (!(0, redisClient_1.isRedisAvailable)()) {
            // No-op for in-memory storage (no TTL)
            return;
        }
        const redis = (0, redisClient_1.getRedisClient)();
        const key = `${REDIS_PREFIX}${jobId}`;
        await redis.expire(key, additionalSeconds);
    }
    catch (error) {
        logger_1.default.warn(`Failed to extend TTL for eval job ${jobId} in Redis: ${error}`);
        // No-op on error (in-memory has no TTL)
    }
};
exports.extendEvalJobTTL = extendEvalJobTTL;
//# sourceMappingURL=evalJobsCache.js.map