import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createRequire } from 'node:module';
import { hasCompleteNativeBinding } from './native-router-hotpath-policy.js';
const require = createRequire(import.meta.url);
const workspaceRoot = resolvePackageRoot(path.dirname(fileURLToPath(import.meta.url)));
let cachedBinding;
let cachedBindingCacheKey;
const REQUIRED_NATIVE_EXPORTS = [
    'analyzeChatProcessMediaJson',
    'analyzeChatWebSearchIntentJson',
    'extractWebSearchSemanticsHintJson',
    'extractOutputSegmentsJson',
    'analyzeContinueExecutionInjectionJson',
    'analyzePendingToolSyncJson',
    'appendToolParseDiagnosticTextJson',
    'injectToolParseDiagnosticsJson',
    'applyReqProcessToolGovernanceJson',
    'applyHubOperationsJson',
    'applyReqProcessRouteSelectionJson',
    'applyReqOutboundContextSnapshotJson',
    'applyClaudeThinkingToolSchemaCompatJson',
    'applyOutboundStreamPreferenceJson',
    'applyTargetMetadataJson',
    'applyTargetToSubjectJson',
    'applyStopMessageInstructionJson',
    'attachPassthroughProviderInputAuditJson',
    'augmentContextSnapshotJson',
    'annotatePassthroughGovernanceSkipJson',
    'buildAnthropicToolAliasMapJson',
    'buildAnthropicResponseFromChatJson',
    'buildChatNodeResultMetadataJson',
    'buildProcessedRequestFromChatResponseJson',
    'applyChatProcessedRequestJson',
    'buildChatProcessContextMetadataJson',
    'buildChatProcessedDescriptorJson',
    'applyClientPassthroughPatchJson',
    'applyGovernedControlOperationsJson',
    'applyGovernedMergeRequestJson',
    'buildClockMarkerScheduleMessagesJson',
    'buildClockReminderMessagesJson',
    'buildClockReminderMetadataJson',
    'buildProviderProtocolErrorJson',
    'buildFormatRequestJson',
    'buildClockStandardToolAppendOperationsJson',
    'buildClockToolAppendOperationsJson',
    'buildResponsesPayloadFromChatJson',
    'buildBridgeHistoryJson',
    'applyBridgeNormalizeHistoryJson',
    'applyBridgeCaptureToolResultsJson',
    'applyBridgeNormalizeToolIdentifiersJson',
    'applyBridgeEnsureToolPlaceholdersJson',
    'convertBridgeInputToChatMessagesJson',
    'coerceBridgeRoleJson',
    'harvestToolsJson',
    'serializeToolArgumentsJson',
    'pruneChatRequestPayloadJson',
    'enforceToolCallIdStyleJson',
    'transformToolCallIdJson',
    'createToolCallIdTransformerJson',
    'extractToolCallIdJson',
    'normalizeIdValueJson',
    'extractStreamingToolCallsJson',
    'chunkStringJson',
    'flattenByCommaJson',
    'packShellArgsJson',
    'splitCommandStringJson',
    'repairFindMetaJson',
    'removeTrailingUnsignedThinkingBlocksJson',
    'filterInvalidThinkingBlocksJson',
    'sanitizeThinkingBlockJson',
    'hasValidThoughtSignatureJson',
    'serializeToolOutputJson',
    'ensureMessagesArrayJson',
    'normalizeReasoningInChatPayloadJson',
    'normalizeReasoningInResponsesPayloadJson',
    'normalizeReasoningInGeminiPayloadJson',
    'normalizeReasoningInAnthropicPayloadJson',
    'normalizeReasoningInOpenAIPayloadJson',
    'buildContinueExecutionOperationsJson',
    'buildDueReminderUserMessageJson',
    'buildGovernedFilterPayloadJson',
    'buildPassthroughAuditJson',
    'buildGuardedClockScheduleItemJson',
    'buildImageAttachmentMetadataJson',
    'buildReviewOperationsJson',
    'buildWebSearchToolAppendOperationsJson',
    'clampResponsesInputItemIdJson',
    'castGovernedToolsJson',
    'collectToolOutputsJson',
    'buildReqInboundToolOutputSnapshotJson',
    'mapBridgeToolsToChatJson',
    'mapOpenaiChatToChatJson',
    'mapOpenaiChatFromChatJson',
    'mapChatToolsToBridgeJson',
    'bridgeToolToChatDefinitionJson',
    'chatToolToBridgeDefinitionJson',
    'mapBridgeToolsToChatWithOptionsJson',
    'mapChatToolsToBridgeWithOptionsJson',
    'captureReqInboundResponsesContextSnapshotJson',
    'computeQuotaBucketsJson',
    'extractReasoningSegmentsJson',
    'deserializeStopMessageStateJson',
    'detectProviderResponseShapeJson',
    'extractClockReminderDirectivesJson',
    'extractContextLengthDiagnosticsJson',
    'encodeMetadataPassthroughJson',
    'prepareGeminiToolsForBridgeJson',
    'buildGeminiToolsFromBridgeJson',
    'pickResponsesPersistedFieldsJson',
    'convertResponsesOutputToInputItemsJson',
    'extractAntigravityGeminiSessionIdJson',
    'ensureBridgeOutputFieldsJson',
    'lookupAntigravityPinnedAliasForSessionIdJson',
    'unpinAntigravitySessionAliasForSessionIdJson',
    'cacheAntigravitySessionSignatureJson',
    'getAntigravityRequestSessionMetaJson',
    'resetAntigravitySignatureCachesJson',
    'coerceClientHeadersJson',
    'extractSessionIdentifiersJson',
    'extractTargetModelIdJson',
    'extractClockScheduleDirectiveTextPartsJson',
    'extractSseWrapperErrorJson',
    'extractMetadataPassthroughJson',
    'extractJsonToolCallsFromTextJson',
    'extractXmlToolCallsFromTextJson',
    'extractSimpleXmlToolsFromTextJson',
    'extractParameterXmlToolsFromTextJson',
    'extractInvokeToolsFromTextJson',
    'extractToolNamespaceXmlBlocksFromTextJson',
    'extractApplyPatchCallsFromTextJson',
    'extractBareExecCommandFromTextJson',
    'extractExecuteBlocksFromTextJson',
    'extractExploredListDirectoryCallsFromTextJson',
    'extractQwenToolCallTokensFromTextJson',
    'extractAdapterContextMetadataFieldsJson',
    'evaluateResponsesHostPolicyJson',
    'enforceChatBudgetJson',
    'resolveBudgetForModelJson',
    'finalizeGovernedRequestJson',
    'governResponseJson',
    'governToolNameResponseJson',
    'findLastUserMessageIndexJson',
    'injectContinueExecutionDirectiveJson',
    'injectTimeTagIntoMessagesJson',
    'injectMcpToolsForChatJson',
    'injectMcpToolsForResponsesJson',
    'mapOpenaiChatToChatJson',
    'mapOpenaiChatFromChatJson',
    'isStopMessageStateActiveJson',
    'isContextLengthExceededSignalJson',
    'isCompactionRequestJson',
    'isShellLikeToolNameTokenJson',
    'looksLikeJsonStreamPrefixJson',
    'mapResumeToolOutputsDetailedJson',
    'mergeContextToolOutputsJson',
    'mergeToolCallsJson',
    'mergeGovernanceSummaryIntoMetadataJson',
    'findHeaderValueJson',
    'normalizeAliasMapJson',
    'normalizeMessageReasoningToolsJson',
    'normalizeOpenaiMessageJson',
    'normalizeOpenaiChatMessagesJson',
    'normalizeOpenaiToolJson',
    'normalizeOpenaiToolCallJson',
    'normalizeChatResponseReasoningToolsJson',
    'normalizeBridgeToolCallIdsJson',
    'normalizeChatMessageContentJson',
    'normalizeArgsBySchemaJson',
    'normalizeToolsJson',
    'normalizeFunctionCallIdJson',
    'normalizeFunctionCallOutputIdJson',
    'normalizeHeaderKeyJson',
    'normalizeHubEndpointJson',
    'normalizeOutputContentPartJson',
    'normalizeToolSessionMessagesJson',
    'updateToolSessionHistoryJson',
    'normalizeContextCaptureLabelJson',
    'normalizeSnapshotStagePayloadJson',
    'normalizeContextToolsJson',
    'normalizeDueInjectTextJson',
    'normalizeProviderProtocolTokenJson',
    'normalizeResponsesCallIdJson',
    'normalizeMessageContentPartsJson',
    'normalizeShellLikeToolCallsBeforeGovernanceJson',
    'normalizeToolCallIdStyleCandidateJson',
    'parseClockScheduleDirectiveCandidateJson',
    'parseLenientJsonishJson',
    'parseJsonObjectCandidateJson',
    'parseProviderKeyJson',
    'parseRoutingInstructionKindsJson',
    'parseStopMessageInstructionJson',
    'pinAliasQueueJson',
    'planChatClockOperationsJson',
    'planChatServertoolOrchestrationBundleJson',
    'planChatWebSearchOperationsJson',
    'planContinueExecutionOperationsJson',
    'resolveAliasSelectionStrategyJson',
    'resolveBridgePolicyJson',
    'resolveBridgePolicyActionsJson',
    'resolveAliasMapFromRespSemanticsJson',
    'resolveClientInjectReadyJson',
    'resolveClientToolsRawJson',
    'resolveClientToolsRawFromRespSemanticsJson',
    'resolveClockReminderFlowPlanJson',
    'resolveClockConfigJson',
    'resolveClockSessionScopeJson',
    'resolveClockTimeTagFallbackLineJson',
    'resolveCompatProfileJson',
    'resolveHasActiveStopMessageForContinueExecutionJson',
    'resolveHasInstructionRequestedPassthroughJson',
    'resolveHubClientProtocolJson',
    'resolveHubProtocolSpecJson',
    'resolveHubProtocolAllowlistsJson',
    'resolveOutboundStreamIntentJson',
    'resolveProviderProtocolJson',
    'resolveHubPolicyOverrideJson',
    'resolveHubShadowCompareConfigJson',
    'resolveApplyPatchToolModeFromToolsJson',
    'resolveActiveProcessModeJson',
    'resolveStopMessageRouterMetadataJson',
    'resolveGovernanceContextJson',
    'resolveStopMessageSessionScopeJson',
    'VirtualRouterEngineProxy',
    'ensureProtocolStateJson',
    'getProtocolStateJson',
    'readRuntimeMetadataJson',
    'resolveDefaultToolGovernanceRulesJson',
    'ensureRuntimeMetadataJson',
    'cloneRuntimeMetadataJson',
    'applyReqInboundSemanticLiftJson',
    'pickHeaderJson',
    'resolveReqOutboundContextMergePlanJson',
    'runReqOutboundStage3CompatJson',
    'runHubPipelineJson',
    'findMappableSemanticsKeysJson',
    'deriveToolCallKeyJson',
    'extractToolCallsFromReasoningTextJson',
    'mapReasoningContentToResponsesOutputJson',
    'validateToolArgumentsJson',
    'repairToolCallsJson',
    'isImagePathJson',
    'resolveServerToolFollowupSnapshotJson',
    'resolveSseStreamModeJson',
    'resolveSseProtocolFromMetadataJson',
    'repairArgumentsToStringJsonishJson',
    'runBridgeActionPipelineJson',
    'sanitizeChatCompletionLikeJson',
    'sanitizeFormatEnvelopeJson',
    'sanitizeReasoningTaggedTextJson',
    'ensureBridgeInstructionsJson',
    'sanitizeResponsesFunctionNameJson',
    'shouldRecordSnapshotsJson',
    'writeSnapshotViaHooksJson',
    'selectToolCallIdStyleJson',
    'serializeStopMessageStateJson',
    'shouldAttachReqOutboundContextSnapshotJson',
    'shouldReserveClockDueReminderJson',
    'shouldRunHubChatProcessJson',
    'splitAntigravityTargetsJson',
    'stripOrphanFunctionCallsTagJson',
    'stripClockClearDirectiveTextJson',
    'stripChatProcessHistoricalImagesJson',
    'stripPrivateFieldsJson',
    'cleanRoutingInstructionMarkersJson'
];
function resolvePackageRoot(startDir) {
    let current = startDir;
    for (let i = 0; i < 10; i += 1) {
        if (fs.existsSync(path.join(current, 'package.json'))) {
            return current;
        }
        const parent = path.dirname(current);
        if (parent === current) {
            break;
        }
        current = parent;
    }
    return path.resolve(startDir, '../../../../');
}
function readNativePathFromEnv() {
    const raw = String(process.env.ROUTECODEX_LLMS_ROUTER_NATIVE_PATH || process.env.RCC_LLMS_ROUTER_NATIVE_PATH || '').trim();
    return raw || undefined;
}
function buildNativeBindingCacheKey(envPath) {
    if (!envPath) {
        return 'auto';
    }
    const resolved = path.isAbsolute(envPath) ? envPath : path.resolve(process.cwd(), envPath);
    return `env:${resolved}`;
}
function resolveLoadPathForNode(resolvedPath) {
    const ext = path.extname(resolvedPath).toLowerCase();
    if (!ext || ext === '.node') {
        return resolvedPath;
    }
    if (ext !== '.dylib' && ext !== '.so' && ext !== '.dll') {
        return resolvedPath;
    }
    return resolvedPath.replace(/\.(dylib|so|dll)$/i, '.node');
}
function tryRequireFromPath(modulePath, options) {
    try {
        const resolved = path.isAbsolute(modulePath) ? modulePath : path.resolve(process.cwd(), modulePath);
        const loadPath = resolveLoadPathForNode(resolved);
        const loaded = require(loadPath);
        if (!loaded || typeof loaded !== 'object') {
            return null;
        }
        if (options?.requireComplete !== false && !hasCompleteNativeBinding(loaded, REQUIRED_NATIVE_EXPORTS)) {
            return null;
        }
        return loaded;
    }
    catch {
        return null;
    }
}
function getWorkspaceNativeCandidates() {
    return ['release', 'debug'].map((mode) => path.join(workspaceRoot, 'rust-core', 'target', mode, 'router_hotpath_napi.node'));
}
function getPackagedNativeCandidates() {
    return [path.join(workspaceRoot, 'dist', 'native', 'router_hotpath_napi.node')];
}
export function loadNativeRouterHotpathBinding() {
    const envPath = readNativePathFromEnv();
    const cacheKey = buildNativeBindingCacheKey(envPath);
    if (cachedBinding !== undefined && cachedBindingCacheKey === cacheKey) {
        return cachedBinding;
    }
    cachedBindingCacheKey = cacheKey;
    cachedBinding = undefined;
    if (envPath) {
        // Explicit env path is allowed to provide partial exports for focused test mocks.
        // Missing capabilities still fail-fast at callsite via native-required checks.
        cachedBinding = tryRequireFromPath(envPath, { requireComplete: false });
        if (cachedBinding)
            return cachedBinding;
    }
    for (const candidate of getWorkspaceNativeCandidates()) {
        const loaded = tryRequireFromPath(candidate);
        if (loaded) {
            cachedBinding = loaded;
            return cachedBinding;
        }
    }
    for (const candidate of getPackagedNativeCandidates()) {
        const loaded = tryRequireFromPath(candidate);
        if (loaded) {
            cachedBinding = loaded;
            return cachedBinding;
        }
    }
    cachedBinding = null;
    return cachedBinding;
}
export function resolveNativeModuleUrlFromEnv() {
    const modulePath = readNativePathFromEnv();
    if (!modulePath) {
        return undefined;
    }
    const normalized = path.isAbsolute(modulePath) ? modulePath : path.resolve(process.cwd(), modulePath);
    return pathToFileURL(normalized).href;
}
