import { applyReqProcessToolGovernanceWithNative } from '../../../router/virtual-router/engine-selection/native-hub-pipeline-req-process-semantics.js';
import { maybeInjectClockRemindersAndApplyDirectives } from './chat-process-clock-reminders.js';
import { finalizeGovernedRequest } from './chat-process-governance-finalize.js';
import { resolveHasActiveStopMessageForContinueExecution } from './chat-process-continue-execution.js';
function isRecord(value) {
    return !!value && typeof value === 'object' && !Array.isArray(value);
}
function parseGovernedRequest(value) {
    const row = value;
    if (!Array.isArray(row.messages)) {
        throw new Error('native chat governance returned malformed request envelope');
    }
    const normalized = {
        ...row,
        parameters: isRecord(row.parameters) ? row.parameters : {},
        metadata: isRecord(row.metadata) ? row.metadata : {}
    };
    return normalized;
}
function resolveProviderProtocol(context) {
    const metadataProtocol = context.metadata.providerProtocol;
    if (typeof metadataProtocol === 'string' && metadataProtocol) {
        return metadataProtocol;
    }
    return context.entryEndpoint === '/v1/messages' ? 'anthropic-chat' : 'openai-chat';
}
export async function applyRequestToolGovernance(request, context, governanceEngine) {
    if (!isRecord(request) || !Array.isArray(request.messages)) {
        throw new Error('chat governance input request is invalid');
    }
    const nativeResult = applyReqProcessToolGovernanceWithNative({
        request: request,
        rawPayload: context.rawPayload ?? request,
        metadata: context.metadata,
        entryEndpoint: context.entryEndpoint,
        requestId: context.requestId,
        hasActiveStopMessageForContinueExecution: resolveHasActiveStopMessageForContinueExecution(context.metadata)
    });
    const governedRequest = parseGovernedRequest(nativeResult.processedRequest);
    const requestAfterInject = await maybeInjectClockRemindersAndApplyDirectives(governedRequest, context.metadata, context.requestId);
    if (!governanceEngine) {
        return requestAfterInject;
    }
    return finalizeGovernedRequest({
        request: requestAfterInject,
        providerProtocol: resolveProviderProtocol(context),
        governanceEngine
    });
}
