"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setToolAvailabilityBroadcaster = setToolAvailabilityBroadcaster;
exports.clearToolAvailabilityBroadcaster = clearToolAvailabilityBroadcaster;
exports.notifyToolAvailabilityBindingChanged = notifyToolAvailabilityBindingChanged;
exports.notifyToolAvailabilityRuntimeLeaseChanged = notifyToolAvailabilityRuntimeLeaseChanged;
exports.notifyToolAvailabilityRegistryMaybeChanged = notifyToolAvailabilityRegistryMaybeChanged;
const time_1 = require("@longrun-ai/kernel/utils/time");
const log_1 = require("./log");
const tool_availability_1 = require("./tool-availability");
const log = (0, log_1.createLogger)('tool-availability-updates');
let broadcastToClients;
let lastRegistryRevision;
function setToolAvailabilityBroadcaster(fn) {
    broadcastToClients = fn;
    lastRegistryRevision = (0, tool_availability_1.computeGlobalToolRegistryRevision)();
}
function clearToolAvailabilityBroadcaster() {
    broadcastToClients = undefined;
    lastRegistryRevision = undefined;
}
function broadcast(msg) {
    const fn = broadcastToClients;
    if (!fn) {
        return;
    }
    try {
        fn(msg);
    }
    catch (error) {
        log.warn('Failed to broadcast tool-availability update', error);
    }
}
function notifyToolAvailabilityBindingChanged(trigger) {
    broadcast({
        type: 'tool_availability_updated',
        reason: 'member_binding_changed',
        timestamp: (0, time_1.formatUnifiedTimestamp)(new Date()),
        trigger,
    });
}
function notifyToolAvailabilityRuntimeLeaseChanged(trigger) {
    broadcast({
        type: 'tool_availability_updated',
        reason: 'runtime_lease_changed',
        timestamp: (0, time_1.formatUnifiedTimestamp)(new Date()),
        trigger,
    });
}
function notifyToolAvailabilityRegistryMaybeChanged(args) {
    const nextRevision = (0, tool_availability_1.computeGlobalToolRegistryRevision)();
    if (lastRegistryRevision === nextRevision) {
        return;
    }
    lastRegistryRevision = nextRevision;
    broadcast({
        type: 'tool_availability_updated',
        reason: args.reason,
        timestamp: (0, time_1.formatUnifiedTimestamp)(new Date()),
        trigger: args.trigger,
    });
}
