import { jsx as _jsx } from "react/jsx-runtime";
/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { createContext, useContext, useEffect, useMemo, } from 'react';
import { clearActiveModelParam, deleteProfileByName, getActiveModelName, getActiveModelParams, getActiveProviderMetrics, getActiveProviderName, getActiveProviderStatus, getActiveToolFormatState, getCliOAuthManager, getCliProviderManager, getCliRuntimeContext, getCliRuntimeServices, getEphemeralSetting, getEphemeralSettings, getRuntimeDiagnosticsSnapshot, listAvailableModels, listProviders, listSavedProfiles, loadProfileByName, registerCliProviderInfrastructure, saveProfileSnapshot, saveLoadBalancerProfile, setActiveModel, setActiveModelParam, setActiveToolFormatOverride, setDefaultProfileName, setEphemeralSetting, switchActiveProvider, updateActiveProviderApiKey, updateActiveProviderBaseUrl, getSessionTokenUsage, getLoadBalancerStats, getLoadBalancerLastSelected, getAllLoadBalancerStats, } from '../../runtime/runtimeSettings.js';
import { enterRuntimeScope, runWithRuntimeScope, } from '../../runtime/runtimeContextFactory.js';
/**
 * @plan PLAN-20251018-STATELESSPROVIDER2.P15
 * @requirement REQ-SP2-003
 * @pseudocode cli-runtime-isolation.md lines 4-10
 * React bridge that binds CLI runtime helpers to the active runtime scope so UI commands remain isolated.
 */
const runtimeFunctions = {
    switchActiveProvider,
    listProviders,
    getActiveProviderName,
    setActiveModel,
    listAvailableModels,
    getActiveModelName,
    getActiveProviderStatus,
    getActiveModelParams,
    getEphemeralSettings,
    setEphemeralSetting,
    setActiveModelParam,
    clearActiveModelParam,
    saveProfileSnapshot,
    saveLoadBalancerProfile,
    loadProfileByName,
    deleteProfileByName,
    listSavedProfiles,
    setDefaultProfileName,
    updateActiveProviderBaseUrl,
    updateActiveProviderApiKey,
    getCliProviderManager,
    getCliOAuthManager,
    registerCliProviderInfrastructure,
    getRuntimeDiagnosticsSnapshot,
    getActiveToolFormatState,
    setActiveToolFormatOverride,
    getActiveProviderMetrics,
    getSessionTokenUsage,
    getCliRuntimeServices,
    getEphemeralSetting,
    getLoadBalancerStats,
    getLoadBalancerLastSelected,
    getAllLoadBalancerStats,
};
const RuntimeContext = createContext(null);
function makeRuntimeApi(runtimeId, metadata) {
    const scope = { runtimeId, metadata };
    const boundEntries = Object.entries(runtimeFunctions).map(([key, fn]) => {
        if (typeof fn !== 'function') {
            return [key, fn];
        }
        const wrapped = (...args) => runWithRuntimeScope(scope, () => fn(...args));
        return [key, wrapped];
    });
    return Object.fromEntries(boundEntries);
}
function createBridge(runtimeId, metadata) {
    const scope = { runtimeId, metadata };
    const api = makeRuntimeApi(runtimeId, metadata);
    return {
        runtimeId,
        metadata,
        api,
        runWithScope: (callback) => runWithRuntimeScope(scope, callback),
        enterScope: () => enterRuntimeScope(scope),
    };
}
let latestBridge = null;
export const RuntimeContextProvider = ({ children, }) => {
    const runtime = getCliRuntimeContext();
    const runtimeId = (typeof runtime.runtimeId === 'string' && runtime.runtimeId.trim() !== ''
        ? runtime.runtimeId
        : 'legacy-singleton') ?? 'legacy-singleton';
    const bridge = useMemo(() => {
        const normalizedMetadata = runtime.metadata ?? {};
        return createBridge(runtimeId, normalizedMetadata);
    }, [runtimeId, runtime]);
    useEffect(() => {
        bridge.enterScope();
        latestBridge = bridge;
        return () => {
            if (latestBridge?.runtimeId === bridge.runtimeId) {
                latestBridge = null;
            }
        };
    }, [bridge]);
    return (_jsx(RuntimeContext.Provider, { value: bridge, children: children }));
};
export function useRuntimeBridge() {
    const context = useContext(RuntimeContext);
    if (!context) {
        throw new Error('RuntimeContextProvider is missing from the component tree.');
    }
    return context;
}
export function useRuntimeApi() {
    return useRuntimeBridge().api;
}
export function getRuntimeBridge() {
    if (latestBridge) {
        return latestBridge;
    }
    const runtime = getCliRuntimeContext();
    const runtimeId = (typeof runtime.runtimeId === 'string' && runtime.runtimeId.trim() !== ''
        ? runtime.runtimeId
        : 'legacy-singleton') ?? 'legacy-singleton';
    const metadata = runtime.metadata ?? {};
    const bridge = createBridge(runtimeId, metadata);
    bridge.enterScope();
    latestBridge = bridge;
    return bridge;
}
export function getRuntimeApi() {
    return getRuntimeBridge().api;
}
//# sourceMappingURL=RuntimeContext.js.map