import { A as AuthToken } from './types-BxggH0Yh.js';

/**
 * Automatic background token refresh manager.
 *
 * Schedules token refresh at a configurable threshold before expiry
 * (default 80% of token lifetime). Emits events on refresh, failure,
 * and token expiry. Handles retry on failure and clean disposal.
 *
 * When all retries are exhausted but the token hasn't expired yet,
 * the manager waits until the token's expiry time and then starts
 * a fresh retry cycle. This continues until refresh succeeds or
 * the token expires.
 *
 * @example Basic usage
 * ```ts
 * import { TokenRefreshManager } from "@witqq/agent-sdk/auth";
 *
 * const manager = new TokenRefreshManager({
 *   token: claudeToken,
 *   refresh: (rt) => claudeAuth.refreshToken(rt),
 * });
 * manager.on("refreshed", (newToken) => { tokenStore.save("claude", newToken); });
 * manager.on("error", (err) => { console.error("Refresh failed:", err); });
 * manager.start();
 * // ...later
 * manager.dispose();
 * ```
 *
 * @example Integration with createAuthHandler
 * ```ts
 * import { TokenRefreshManager } from "@witqq/agent-sdk/auth";
 * import { createAuthHandler } from "@witqq/agent-sdk/chat/server";
 * import type { ClaudeAuthToken } from "@witqq/agent-sdk/auth";
 *
 * let refreshManager: TokenRefreshManager | undefined;
 *
 * const authHandler = createAuthHandler({
 *   tokenStore,
 *   onAuth: (provider, token) => {
 *     // Clean up previous manager
 *     refreshManager?.dispose();
 *     refreshManager = undefined;
 *
 *     if (provider === "claude" && token.expiresIn) {
 *       refreshManager = new TokenRefreshManager({
 *         token,
 *         refresh: (t) =>
 *           claudeAuth.refreshToken((t as ClaudeAuthToken).refreshToken),
 *       });
 *       refreshManager.on("refreshed", (newToken) => {
 *         tokenStore.save("claude", newToken);
 *       });
 *       refreshManager.on("expired", () => {
 *         console.warn("Claude token expired — re-authentication required");
 *       });
 *       refreshManager.start();
 *     }
 *   },
 * });
 * ```
 */

/** Events emitted by TokenRefreshManager */
interface TokenRefreshEvents {
    /** Emitted when token was successfully refreshed */
    refreshed: (token: AuthToken) => void;
    /** Emitted when refresh attempt failed (may retry) */
    error: (error: Error, attempt: number) => void;
    /** Emitted when token expired and could not be refreshed */
    expired: () => void;
    /** Emitted when manager is disposed */
    disposed: () => void;
}
/** Configuration for TokenRefreshManager */
interface TokenRefreshOptions {
    /** Current token with expiresIn and obtainedAt */
    token: AuthToken;
    /**
     * Function that performs the actual token refresh.
     * Receives the current token and returns a new one.
     */
    refresh: (token: AuthToken) => Promise<AuthToken>;
    /**
     * Fraction of token lifetime at which to trigger refresh (0-1).
     * Default: 0.8 (refresh at 80% of lifetime, i.e. with 20% remaining)
     */
    refreshThreshold?: number;
    /**
     * Maximum retry attempts on refresh failure. Default: 3
     */
    maxRetries?: number;
    /**
     * Base delay between retries in ms. Exponential backoff applied. Default: 1000
     */
    retryDelayMs?: number;
    /**
     * Minimum schedule delay in ms (prevents scheduling in the past). Default: 1000
     */
    minDelayMs?: number;
}
type EventName = keyof TokenRefreshEvents;
/**
 * Background token refresh manager with event emission and retry logic.
 *
 * Lifecycle: `new` → `start()` → (auto-refreshes) → `stop()` or `dispose()`
 */
declare class TokenRefreshManager {
    private currentToken;
    private readonly refreshFn;
    private readonly threshold;
    private readonly maxRetries;
    private readonly retryDelayMs;
    private readonly minDelayMs;
    private timerId;
    private running;
    private disposed;
    private readonly listeners;
    constructor(options: TokenRefreshOptions);
    /** Register an event listener */
    on<K extends EventName>(event: K, listener: TokenRefreshEvents[K]): this;
    /** Remove an event listener */
    off<K extends EventName>(event: K, listener: TokenRefreshEvents[K]): this;
    /** Current token managed by this instance */
    get token(): AuthToken;
    /** Whether the manager is currently running */
    get isRunning(): boolean;
    /** Whether the manager has been disposed */
    get isDisposed(): boolean;
    /**
     * Start automatic refresh scheduling.
     * If the token is already expired, emits "expired" immediately.
     * If the token has no expiresIn, does nothing (long-lived token).
     */
    start(): void;
    /** Stop automatic refresh (can be restarted with start()) */
    stop(): void;
    /**
     * Update the managed token (e.g. after manual refresh).
     * Reschedules automatic refresh if running.
     */
    updateToken(token: AuthToken): void;
    /** Stop and clean up all resources */
    dispose(): void;
    private schedule;
    private performRefresh;
    private computeRefreshDelay;
    private isTokenExpired;
    private clearTimer;
    private emit;
}

export { type TokenRefreshEvents as T, TokenRefreshManager as a, type TokenRefreshOptions as b };
