/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
export class ProactiveScheduler {
    refreshFn;
    leadTimeSec;
    maxJitterSec;
    timers = new Map();
    constructor(options) {
        this.refreshFn = options.refreshFn;
        this.leadTimeSec = options.leadTimeSec ?? 300;
        this.maxJitterSec = options.maxJitterSec ?? 60;
    }
    schedule(provider, bucket, expiryEpochSec) {
        const key = `${provider}:${bucket}`;
        // Cancel any existing timer for this key
        this.cancel(provider, bucket);
        const now = Date.now() / 1000;
        const jitter = Math.random() * this.maxJitterSec;
        const fireAt = expiryEpochSec - this.leadTimeSec - jitter;
        const delayMs = (fireAt - now) * 1000;
        if (delayMs <= 0) {
            return;
        }
        const timer = setTimeout(() => {
            this.timers.delete(key);
            this.refreshFn(provider, bucket).catch((err) => {
                // Log error to prevent unhandled rejection; refresh will be retried on next schedule
                console.error(`Proactive refresh failed for ${provider}:${bucket}:`, err);
            });
        }, delayMs);
        timer.unref();
        this.timers.set(key, timer);
    }
    cancel(provider, bucket) {
        const key = `${provider}:${bucket}`;
        const timer = this.timers.get(key);
        if (timer) {
            clearTimeout(timer);
            this.timers.delete(key);
        }
    }
    cancelAll() {
        for (const timer of this.timers.values()) {
            clearTimeout(timer);
        }
        this.timers.clear();
    }
    get activeCount() {
        return this.timers.size;
    }
}
//# sourceMappingURL=proactive-scheduler.js.map