import { recordStage } from '../../../stages/utils.js';
import { captureApplyPatchExecutionFailuresFromProcessedRequest } from '../../../../../../tools/apply-patch/execution-capturer.js';
import { applyReqProcessToolGovernanceWithNative } from '../../../../../../router/virtual-router/engine-selection/native-hub-pipeline-req-process-semantics.js';
import { maybeInjectClockRemindersAndApplyDirectives } from '../../../../process/chat-process-clock-reminders.js';
function isRecord(value) {
    return !!value && typeof value === 'object' && !Array.isArray(value);
}
function parseProcessedRequest(value) {
    if (!isRecord(value)) {
        throw new Error('native req_process_stage1_tool_governance returned invalid processedRequest');
    }
    if (typeof value.model !== 'string' || !Array.isArray(value.messages) || !isRecord(value.parameters) || !isRecord(value.metadata)) {
        throw new Error('native req_process_stage1_tool_governance returned malformed processedRequest envelope');
    }
    if (!isRecord(value.processed) || !isRecord(value.processingMetadata)) {
        throw new Error('native req_process_stage1_tool_governance missing processed/processingMetadata');
    }
    return value;
}
function parseNodeResult(value) {
    if (!isRecord(value) || typeof value.success !== 'boolean' || !isRecord(value.metadata)) {
        throw new Error('native req_process_stage1_tool_governance returned invalid nodeResult');
    }
    const errorValue = value.error;
    if (errorValue !== undefined && (!isRecord(errorValue) || typeof errorValue.message !== 'string')) {
        throw new Error('native req_process_stage1_tool_governance returned invalid nodeResult.error');
    }
    return value;
}
export async function runReqProcessStage1ToolGovernance(options) {
    const nativeResult = applyReqProcessToolGovernanceWithNative({
        request: options.request,
        rawPayload: options.rawPayload,
        metadata: options.metadata,
        entryEndpoint: options.entryEndpoint,
        requestId: options.requestId
    });
    let processedRequest = parseProcessedRequest(nativeResult.processedRequest);
    const nodeResult = parseNodeResult(nativeResult.nodeResult);
    processedRequest = await maybeInjectClockRemindersAndApplyDirectives(processedRequest, options.metadata, options.requestId);
    const nodeResultMetadata = nodeResult.metadata && typeof nodeResult.metadata === 'object'
        ? nodeResult.metadata
        : null;
    const dataProcessed = nodeResultMetadata?.dataProcessed && typeof nodeResultMetadata.dataProcessed === 'object'
        ? nodeResultMetadata.dataProcessed
        : null;
    if (dataProcessed) {
        dataProcessed.messages = Array.isArray(processedRequest.messages) ? processedRequest.messages.length : 0;
        dataProcessed.tools = Array.isArray(processedRequest.tools) ? processedRequest.tools.length : 0;
    }
    recordStage(options.stageRecorder, 'chat_process.req.stage4.tool_governance', processedRequest);
    // Best-effort: capture apply_patch execution failures reported by tool role messages.
    // This is for errorsamples collection only and must not affect runtime behavior.
    captureApplyPatchExecutionFailuresFromProcessedRequest(processedRequest);
    return {
        processedRequest,
        nodeResult
    };
}
