"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ServerTypeCacheService = void 0;
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const os = __importStar(require("node:os"));
class ServerTypeCacheService {
    constructor() {
        this.defaultTtlHours = 12;
        const homeDir = os.homedir();
        this.cacheDir = path.join(homeDir, '.flui', 'cache');
        this.ensureCacheDir();
    }
    ensureCacheDir() {
        if (!fs.existsSync(this.cacheDir)) {
            fs.mkdirSync(this.cacheDir, { recursive: true });
        }
    }
    getCacheFilePath(provider) {
        return path.join(this.cacheDir, `server-types-${provider}.json`);
    }
    /**
     * Get cached server types if available and not expired
     */
    async get(provider) {
        try {
            const filePath = this.getCacheFilePath(provider);
            if (!fs.existsSync(filePath)) {
                return null;
            }
            const fileContent = fs.readFileSync(filePath, 'utf-8');
            const cacheData = JSON.parse(fileContent);
            // Check if cache is expired
            if (this.isCacheExpired(cacheData)) {
                return null;
            }
            return cacheData.serverTypes;
        }
        catch {
            // If there's any error reading/parsing cache, treat as cache miss
            return null;
        }
    }
    /**
     * Save server types to cache
     */
    async set(provider, serverTypes) {
        try {
            const cacheData = {
                provider,
                timestamp: new Date().toISOString(),
                ttlHours: this.defaultTtlHours,
                serverTypes,
            };
            const filePath = this.getCacheFilePath(provider);
            fs.writeFileSync(filePath, JSON.stringify(cacheData, null, 2), 'utf-8');
        }
        catch (error) {
            // Silently fail - cache is not critical
            console.warn(`Failed to write server types cache: ${error.message}`);
        }
    }
    /**
     * Clear cache for a specific provider
     */
    async clear(provider) {
        try {
            const filePath = this.getCacheFilePath(provider);
            if (fs.existsSync(filePath)) {
                fs.unlinkSync(filePath);
            }
        }
        catch (error) {
            console.warn(`Failed to clear cache: ${error.message}`);
        }
    }
    /**
     * Clear all server type caches
     */
    async clearAll() {
        try {
            const files = fs.readdirSync(this.cacheDir);
            for (const file of files) {
                if (file.startsWith('server-types-') && file.endsWith('.json')) {
                    fs.unlinkSync(path.join(this.cacheDir, file));
                }
            }
        }
        catch (error) {
            console.warn(`Failed to clear all caches: ${error.message}`);
        }
    }
    /**
     * Get cache metadata (timestamp, TTL)
     */
    async getCacheInfo(provider) {
        try {
            const filePath = this.getCacheFilePath(provider);
            if (!fs.existsSync(filePath)) {
                return { exists: false };
            }
            const fileContent = fs.readFileSync(filePath, 'utf-8');
            const cacheData = JSON.parse(fileContent);
            const timestamp = new Date(cacheData.timestamp);
            const expiresAt = new Date(timestamp.getTime() + cacheData.ttlHours * 60 * 60 * 1000);
            return {
                exists: true,
                timestamp,
                expiresAt,
                isExpired: this.isCacheExpired(cacheData),
            };
        }
        catch {
            return { exists: false };
        }
    }
    isCacheExpired(cacheData) {
        const timestamp = new Date(cacheData.timestamp);
        const expiresAt = new Date(timestamp.getTime() + cacheData.ttlHours * 60 * 60 * 1000);
        return new Date() > expiresAt;
    }
}
exports.ServerTypeCacheService = ServerTypeCacheService;
