export function createRuntimeRegistry() {
    const adapters = new Map();
    const listeners = new Set();
    function notify() {
        const runtimes = list();
        for (const listener of listeners)
            listener(runtimes);
    }
    function register(runtime) {
        adapters.set(runtime.id, {
            runtime,
            registeredAt: new Date().toISOString(),
            enabled: true,
        });
        notify();
    }
    function unregister(runtimeId) {
        const removed = adapters.delete(runtimeId);
        if (removed)
            notify();
        return removed;
    }
    function get(runtimeId) {
        return adapters.get(runtimeId)?.runtime;
    }
    function list() {
        return [...adapters.values()]
            .filter((e) => e.enabled)
            .map((e) => e.runtime)
            .sort((a, b) => b.priority - a.priority);
    }
    function disable(runtimeId) {
        const entry = adapters.get(runtimeId);
        if (entry) {
            entry.enabled = false;
            notify();
        }
    }
    function enable(runtimeId) {
        const entry = adapters.get(runtimeId);
        if (entry) {
            entry.enabled = true;
            notify();
        }
    }
    function onChange(listener) {
        listeners.add(listener);
        return () => listeners.delete(listener);
    }
    async function healthCheck() {
        const results = [];
        for (const entry of adapters.values()) {
            if (entry.runtime.health) {
                results.push(await entry.runtime.health());
            }
            else {
                results.push({
                    runtimeId: entry.runtime.id,
                    available: true,
                    checkedAt: new Date().toISOString(),
                    reason: "no health check available",
                });
            }
        }
        return results;
    }
    function findCompatible(capsule, requiredAuthority) {
        return list().filter((r) => {
            if (!r.capabilities)
                return true;
            if (requiredAuthority) {
                return requiredAuthority.every((auth) => {
                    const key = auth;
                    return r.capabilities[key] === true;
                });
            }
            if (capsule.role) {
                const roleKey = capsule.role;
                return r.capabilities[roleKey] === true;
            }
            return true;
        });
    }
    return {
        register,
        unregister,
        get,
        list,
        disable,
        enable,
        onChange,
        healthCheck,
        findCompatible,
    };
}
