// tools/license-gate.ts — Runtime license enforcement for MCP tool handlers.
// Provides getCurrentTier() with in-memory cache and withLicenseGate() wrapper.
import { licenseStore } from '../storage/index.js';
import { resolveCurrentTier, checkToolAccess, isValidationFresh, } from '../engine/license-validator.js';
// ---------------------------------------------------------------------------
// In-memory tier cache (avoids disk read on every tool call)
// ---------------------------------------------------------------------------
const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
let cachedTier = null;
let cacheTimestamp = 0;
export async function getCurrentTier() {
    const now = Date.now();
    if (cachedTier !== null && now - cacheTimestamp < CACHE_TTL_MS) {
        return cachedTier;
    }
    const state = await licenseStore.getLicenseState();
    cachedTier = resolveCurrentTier(state);
    cacheTimestamp = now;
    // Schedule background re-validation if cached license is stale (>30 days)
    if (state && !isValidationFresh(state)) {
        void scheduleBackgroundRevalidation(state.licenseKey, state.instanceId);
    }
    return cachedTier;
}
export function invalidateTierCache() {
    cachedTier = null;
    cacheTimestamp = 0;
}
// ---------------------------------------------------------------------------
// License gate wrapper
// ---------------------------------------------------------------------------
export function withLicenseGate(toolName, handler) {
    return async (args) => {
        const tier = await getCurrentTier();
        const check = checkToolAccess(toolName, tier);
        if (!check.allowed) {
            return { content: [{ type: 'text', text: check.message }], isError: true };
        }
        return handler(args);
    };
}
// ---------------------------------------------------------------------------
// Background re-validation (fire-and-forget, grace period on failure)
// ---------------------------------------------------------------------------
async function scheduleBackgroundRevalidation(licenseKey, instanceId) {
    try {
        const { validateLicense } = await import('../engine/license-validator.js');
        const result = await validateLicense(licenseKey, instanceId);
        if (result.valid) {
            const state = await licenseStore.getLicenseState();
            if (state) {
                await licenseStore.saveLicenseState({
                    ...state,
                    lastValidatedAt: new Date().toISOString(),
                });
                invalidateTierCache();
            }
        }
    }
    catch {
        // Grace period: if API is unreachable, keep using cached state
    }
}
//# sourceMappingURL=license-gate.js.map