import { DetourRegistry } from './detour-registry.js';
import { jsonClone } from '../types/json.js';
import { normalizeProviderProtocolTokenWithNative } from '../../../router/virtual-router/engine-selection/native-hub-pipeline-req-inbound-semantics.js';
function recordSnapshot(recorder, stage, ctx, payload) {
    if (!recorder)
        return;
    recorder.record({
        stage,
        protocol: ctx.protocol,
        direction: ctx.direction,
        payload: jsonClone(payload)
    });
}
export async function runHubPlan(options) {
    const { plan, context, initialInput, recorder } = options;
    normalizeProviderProtocolTokenWithNative(plan.protocol || context.protocol);
    if (!plan.stages?.length && !plan.passthrough) {
        throw new Error(`Hub plan for ${plan.protocol} has neither stages nor passthrough`);
    }
    const detours = options.detours ?? new DetourRegistry();
    if (plan.passthrough) {
        const payload = plan.passthrough.mode === 'clone' ? jsonClone(initialInput) : initialInput;
        recordSnapshot(recorder, 'passthrough', context, payload);
        return payload;
    }
    let cursor = initialInput;
    const runtime = { context, detours };
    for (const stage of plan.stages) {
        cursor = await stage.execute(cursor, runtime);
        recordSnapshot(recorder, stage.name, context, cursor);
    }
    return cursor;
}
