import { resolveRoutingMode } from '../engine/routing-state/metadata.js';
import { buildHitReason, createVirtualRouterHitRecord, formatVirtualRouterHit, toVirtualRouterHitEvent } from '../engine-logging.js';
import { recordAntigravitySessionLease } from '../engine/antigravity/alias-lease.js';
export function finalizeRoutingDecision(engine, metadata, routingState, metadataInstructions, instructions, selectionResult) {
    const { selection, classification, requestedRoute, features } = selectionResult;
    const baseTarget = engine.providerRegistry.buildTarget(selection.providerKey);
    const forceVision = selection.routeUsed === 'vision' && engine.routeHasForceFlag('vision');
    const target = {
        ...baseTarget,
        ...(engine.webSearchForce ? { forceWebSearch: true } : {}),
        ...(forceVision ? { forceVision: true } : {})
    };
    const instructionProcessMode = engine.resolveInstructionProcessModeForSelection(selection.providerKey, routingState);
    if (instructionProcessMode) {
        target.processMode = instructionProcessMode;
    }
    recordAntigravitySessionLease({
        metadata: features.metadata,
        providerKey: selection.providerKey,
        sessionKey: engine.resolveSessionScope(features.metadata),
        providerRegistry: engine.providerRegistry,
        leaseStore: engine.stickySessionManager.getAllStores().aliasLeaseStore,
        sessionAliasStore: engine.stickySessionManager.getAllStores().sessionAliasStore,
        persistence: engine.antigravityLeasePersistence,
        aliasReuseCooldownMs: engine.stickySessionManager.getAliasReuseCooldownMs(),
        commitSessionBinding: false,
        debug: engine.debug
    });
    const routingMode = resolveRoutingMode([...metadataInstructions, ...instructions], routingState);
    const hitReason = buildHitReason(selection.routeUsed, selection.providerKey, classification, features, routingMode, { providerRegistry: engine.providerRegistry, contextRouting: engine.contextRouting });
    const stickyScope = routingMode !== 'none' ? engine.resolveSessionScope(metadata) : undefined;
    const routeForLog = routingMode === 'sticky' ? 'sticky' : selection.routeUsed;
    const hitRecord = createVirtualRouterHitRecord({
        requestId: metadata.requestId,
        routeName: routeForLog,
        poolId: selection.poolId,
        providerKey: selection.providerKey,
        modelId: target.modelId || undefined,
        hitReason,
        stickyScope,
        routingState,
        requestTokens: features.estimatedTokens,
        selectionPenalty: engine.resolveSelectionPenalty(selection.providerKey)
    });
    engine.routeAnalytics.incrementRouteStat(selection.routeUsed, selection.providerKey, hitRecord);
    try {
        engine.statsCenter.recordVirtualRouterHit(toVirtualRouterHitEvent(hitRecord, {
            requestId: metadata.requestId,
            entryEndpoint: metadata.entryEndpoint || '/v1/chat/completions'
        }));
    }
    catch {
        // stats must never break routing
    }
    const formatted = formatVirtualRouterHit(hitRecord);
    if (formatted) {
        engine.debug?.log?.(formatted);
    }
    else {
        engine.debug?.log?.(formatVirtualRouterHit(hitRecord));
    }
    const didFallback = selection.routeUsed !== requestedRoute;
    return {
        target,
        decision: {
            routeName: selection.routeUsed,
            providerKey: selection.providerKey,
            pool: selection.pool,
            poolId: selection.poolId,
            confidence: classification.confidence,
            reasoning: classification.reasoning,
            fallback: didFallback
        },
        diagnostics: {
            routeName: selection.routeUsed,
            providerKey: selection.providerKey,
            pool: selection.pool,
            poolId: selection.poolId,
            reasoning: classification.reasoning,
            fallback: didFallback,
            confidence: classification.confidence
        }
    };
}
