import { runBridgeActionPipelineWithNative } from '../router/virtual-router/engine-selection/native-hub-bridge-action-semantics.js';
const registry = new Map();
export function registerBridgeAction(name, action) {
    registry.set(name, action);
}
export function createBridgeActionState(seed) {
    const state = {
        messages: Array.isArray(seed?.messages) ? seed.messages : []
    };
    if (seed?.requiredAction)
        state.requiredAction = seed.requiredAction;
    if (seed?.capturedToolResults)
        state.capturedToolResults = seed.capturedToolResults;
    if (seed?.rawRequest)
        state.rawRequest = seed.rawRequest;
    if (seed?.rawResponse)
        state.rawResponse = seed.rawResponse;
    if (seed?.metadata)
        state.metadata = seed.metadata;
    return state;
}
export function runBridgeActionPipeline(options) {
    const { stage, actions, protocol, moduleType, requestId, state } = options;
    if (!actions?.length)
        return;
    const output = runBridgeActionPipelineWithNative({
        stage,
        actions: actions.map((entry) => ({
            name: entry.name,
            options: entry.options
        })),
        protocol,
        moduleType,
        requestId,
        state: state
    });
    if (!output) {
        return;
    }
    if (output && typeof output === 'object') {
        const next = output;
        const patch = {
            messages: Array.isArray(next.messages) ? next.messages : state.messages,
            ...(next.requiredAction && typeof next.requiredAction === 'object' && !Array.isArray(next.requiredAction)
                ? { requiredAction: next.requiredAction }
                : {}),
            ...(Array.isArray(next.capturedToolResults)
                ? { capturedToolResults: next.capturedToolResults }
                : {}),
            ...(next.rawRequest && typeof next.rawRequest === 'object' && !Array.isArray(next.rawRequest)
                ? { rawRequest: next.rawRequest }
                : {}),
            ...(next.rawResponse && typeof next.rawResponse === 'object' && !Array.isArray(next.rawResponse)
                ? { rawResponse: next.rawResponse }
                : {}),
            ...(next.metadata && typeof next.metadata === 'object' && !Array.isArray(next.metadata)
                ? { metadata: next.metadata }
                : {})
        };
        Object.assign(state, patch);
    }
    for (const descriptor of actions) {
        if (!descriptor || typeof descriptor !== 'object')
            continue;
        const action = registry.get(descriptor.name);
        if (!action)
            continue;
        try {
            action({
                stage,
                protocol,
                moduleType,
                requestId,
                descriptor,
                state
            });
        }
        catch {
            // Ignore action failures to preserve core flow; telemetry hooks can be added later.
        }
    }
}
