/**
 * Region caching utilities for avoiding repeated API calls
 */
import { join } from 'node:path';
import { mkdir, unlink } from 'node:fs/promises';
import { listRegions } from '@agentuity/server';
import { getDefaultConfigDir } from './config';
const REGIONS_CACHE_MAX_AGE_MS = 5 * 24 * 60 * 60 * 1000; // 5 days
const LEGACY_REGIONS_CACHE_FILE = 'regions.json';
function getRegionsCacheFile(profileName) {
    return `regions-${profileName}.json`;
}
async function removeLegacyRegionsCache(logger) {
    try {
        const legacyPath = join(getDefaultConfigDir(), LEGACY_REGIONS_CACHE_FILE);
        const file = Bun.file(legacyPath);
        if (await file.exists()) {
            await unlink(legacyPath);
            logger.trace('removed legacy regions cache file');
        }
    }
    catch {
        // Ignore errors when removing legacy file
    }
}
async function getCachedRegions(profileName, logger) {
    try {
        // Clean up legacy single-file cache from older versions
        await removeLegacyRegionsCache(logger);
        const cachePath = join(getDefaultConfigDir(), getRegionsCacheFile(profileName));
        const file = Bun.file(cachePath);
        if (!(await file.exists())) {
            return null;
        }
        const data = await file.json();
        const age = Date.now() - data.timestamp;
        if (age > REGIONS_CACHE_MAX_AGE_MS) {
            logger.trace('regions cache expired for profile %s (age: %dms)', profileName, age);
            return null;
        }
        logger.trace('using cached regions for profile %s (age: %dms)', profileName, age);
        return data.regions;
    }
    catch (error) {
        logger.trace('failed to read regions cache for profile %s: %s', profileName, error);
        return null;
    }
}
async function saveRegionsCache(profileName, regions, logger) {
    try {
        const cacheDir = getDefaultConfigDir();
        await mkdir(cacheDir, { recursive: true });
        const cachePath = join(cacheDir, getRegionsCacheFile(profileName));
        const data = {
            timestamp: Date.now(),
            regions,
        };
        await Bun.write(cachePath, JSON.stringify(data));
        logger.trace('saved regions cache for profile %s', profileName);
    }
    catch (error) {
        logger.trace('failed to save regions cache for profile %s: %s', profileName, error);
    }
}
/**
 * Fetch regions from API with caching
 */
export async function fetchRegionsWithCache(profileName, apiClient, logger) {
    const cached = await getCachedRegions(profileName, logger);
    if (cached) {
        return cached;
    }
    const regions = await listRegions(apiClient);
    await saveRegionsCache(profileName, regions, logger);
    return regions;
}
//# sourceMappingURL=regions.js.map