"use strict";
/**
 * Token Expiry Checker
 *
 * Inspects token files to determine expiry times and refresh requirements.
 * Supports expiry_date field with fallback to file modification time.
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAllTokenExpiryInfo = exports.getTokenExpiryInfo = exports.FALLBACK_EXPIRY_MINUTES = exports.PREEMPTIVE_REFRESH_MINUTES = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const profile_detector_1 = require("../../auth/profile-detector");
const account_manager_1 = require("../accounts/account-manager");
const provider_refreshers_1 = require("./provider-refreshers");
/** Preemptive refresh time: refresh tokens 45 minutes before expiry */
exports.PREEMPTIVE_REFRESH_MINUTES = 45;
/** Fallback expiry: assume 50 minutes if no expiry_date field */
exports.FALLBACK_EXPIRY_MINUTES = 50;
/** Maximum token file size in bytes (1MB) - prevent DoS from huge files */
const MAX_TOKEN_FILE_SIZE = 1024 * 1024;
/**
 * Get token expiry info for a specific account
 * @returns null if token file doesn't exist or is invalid
 */
function getTokenExpiryInfo(provider, accountId) {
    const account = (0, account_manager_1.getProviderAccounts)(provider).find((a) => a.id === accountId);
    if (!account) {
        return null;
    }
    const tokenPath = (0, account_manager_1.getAccountTokenPath)(account);
    if (!tokenPath || !fs.existsSync(tokenPath)) {
        return null;
    }
    try {
        const stats = fs.statSync(tokenPath);
        // Prevent DoS from huge token files
        if (stats.size > MAX_TOKEN_FILE_SIZE) {
            return null;
        }
        const content = fs.readFileSync(tokenPath, 'utf-8');
        const data = JSON.parse(content);
        // Validate refresh_token exists (required for CCS-managed refresh).
        // CLIProxy-delegated providers may not expose refresh_token in token files —
        // CLIProxyAPIPlus manages refresh internally, so skip this check for them.
        if (!(0, provider_refreshers_1.isRefreshDelegated)(provider)) {
            if (!data.refresh_token || typeof data.refresh_token !== 'string') {
                return null;
            }
        }
        // Calculate expiry time with validation
        let expiresAt;
        if (data.expiry_date &&
            typeof data.expiry_date === 'number' &&
            Number.isFinite(data.expiry_date) &&
            data.expiry_date > 0) {
            // Use expiry_date field if valid
            expiresAt = data.expiry_date;
        }
        else {
            // Fallback: use file mtime + 50 minutes
            expiresAt = stats.mtime.getTime() + exports.FALLBACK_EXPIRY_MINUTES * 60 * 1000;
        }
        // Check if needs refresh (within preemptive window)
        const now = Date.now();
        const timeUntilExpiry = expiresAt - now;
        const preemptiveMs = exports.PREEMPTIVE_REFRESH_MINUTES * 60 * 1000;
        const needsRefresh = timeUntilExpiry < preemptiveMs;
        return {
            provider,
            accountId,
            tokenFile: path.basename(tokenPath),
            expiresAt,
            needsRefresh,
            lastModified: stats.mtime,
        };
    }
    catch {
        return null;
    }
}
exports.getTokenExpiryInfo = getTokenExpiryInfo;
/**
 * Get token expiry info for all accounts across all providers
 * @returns Array of token expiry info, excluding invalid tokens
 */
function getAllTokenExpiryInfo() {
    const providers = [...profile_detector_1.CLIPROXY_PROFILES];
    const results = [];
    for (const provider of providers) {
        const accounts = (0, account_manager_1.getProviderAccounts)(provider);
        for (const account of accounts) {
            const info = getTokenExpiryInfo(provider, account.id);
            if (info) {
                results.push(info);
            }
        }
    }
    return results;
}
exports.getAllTokenExpiryInfo = getAllTokenExpiryInfo;
//# sourceMappingURL=token-expiry-checker.js.map