import { failNativeRequired, isNativeDisabledByEnv } from './native-router-hotpath-policy.js';
import { loadNativeRouterHotpathBindingForInternalUse } from './native-router-hotpath.js';
import { sanitizeFormatEnvelopeWithNative } from './native-hub-pipeline-edge-stage-semantics.js';
import { augmentContextSnapshotWithNative, collectToolOutputsWithNative, mapResumeToolOutputsDetailedWithNative, normalizeToolCallIdStyleCandidateWithNative, resolveServerToolFollowupSnapshotWithNative } from './native-hub-pipeline-inbound-outbound-semantics.js';
function readNativeFunction(name) {
    const binding = loadNativeRouterHotpathBindingForInternalUse();
    const fn = binding?.[name];
    return typeof fn === 'function' ? fn : null;
}
function parseOptionalString(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return undefined;
        }
        if (typeof parsed !== 'string') {
            return null;
        }
        const normalized = parsed.trim();
        return normalized ? normalized : undefined;
    }
    catch {
        return null;
    }
}
function parseBoolean(raw) {
    try {
        const parsed = JSON.parse(raw);
        return typeof parsed === 'boolean' ? parsed : null;
    }
    catch {
        return null;
    }
}
function parseRecord(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
function parseArray(raw) {
    try {
        const parsed = JSON.parse(raw);
        return Array.isArray(parsed) ? parsed : null;
    }
    catch {
        return null;
    }
}
function parseToolOutputSnapshotBuildResult(raw) {
    const parsed = parseRecord(raw);
    if (!parsed) {
        return null;
    }
    const snapshot = parsed.snapshot;
    const payload = parsed.payload;
    if (!snapshot || typeof snapshot !== 'object' || Array.isArray(snapshot)) {
        return null;
    }
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
        return null;
    }
    return {
        snapshot: snapshot,
        payload: payload
    };
}
function safeStringify(value) {
    try {
        return JSON.stringify(value);
    }
    catch {
        return undefined;
    }
}
function replaceRecord(target, source) {
    for (const key of Object.keys(target)) {
        if (!Object.prototype.hasOwnProperty.call(source, key)) {
            delete target[key];
        }
    }
    Object.assign(target, source);
}
export function pruneChatRequestPayloadWithNative(payload, preserveStreamField = false) {
    const capability = 'pruneChatRequestPayloadJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify({ payload, preserveStreamField });
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function sanitizeReqInboundFormatEnvelopeWithNative(candidate) {
    return sanitizeFormatEnvelopeWithNative(candidate);
}
export function mapReqInboundResumeToolOutputsDetailedWithNative(responsesResume) {
    return mapResumeToolOutputsDetailedWithNative(responsesResume);
}
export function resolveClientInjectReadyWithNative(metadata) {
    const capability = 'resolveClientInjectReadyJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('resolveClientInjectReadyJson');
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseBoolean(raw);
        return parsed === null ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeContextCaptureLabelWithNative(label) {
    const capability = 'normalizeContextCaptureLabelJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('normalizeContextCaptureLabelJson');
    if (!fn) {
        return fail();
    }
    const labelJson = safeStringify(label ?? null);
    if (!labelJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(labelJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseOptionalString(raw);
        if (parsed === null) {
            return fail('invalid payload');
        }
        return parsed ?? 'context_capture';
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function shouldRunHubChatProcessWithNative(requestId, entryEndpoint) {
    const capability = 'shouldRunHubChatProcessJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('shouldRunHubChatProcessJson');
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(requestId, entryEndpoint);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseBoolean(raw);
        return parsed === null ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeProviderProtocolTokenWithNative(value) {
    const capability = 'normalizeProviderProtocolTokenJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('normalizeProviderProtocolTokenJson');
    if (!fn) {
        return fail();
    }
    const valueJson = safeStringify(value ?? null);
    if (!valueJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(valueJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseOptionalString(raw);
        return parsed === null ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function isShellLikeToolNameTokenWithNative(name) {
    const capability = 'isShellLikeToolNameTokenJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('isShellLikeToolNameTokenJson');
    if (!fn) {
        return fail();
    }
    const nameJson = safeStringify(name ?? null);
    if (!nameJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(nameJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseBoolean(raw);
        return parsed === null ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function applyReqInboundSemanticLiftWithNative(input) {
    const capability = 'applyReqInboundSemanticLiftJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('applyReqInboundSemanticLiftJson');
    if (!fn) {
        return fail();
    }
    const inputJson = safeStringify(input);
    if (!inputJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inputJson);
        if (raw instanceof Error) {
            return fail(raw.message || 'native error');
        }
        if (raw && typeof raw === 'object' && 'message' in raw) {
            const message = raw.message;
            if (typeof message === 'string' && message.trim().length) {
                return fail(message.trim());
            }
        }
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function chatEnvelopeToStandardizedWithNative(input) {
    const capability = 'chatEnvelopeToStandardizedJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const chatJson = safeStringify(input.chatEnvelope);
    const adapterContextJson = safeStringify(input.adapterContext);
    if (!chatJson || !adapterContextJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(chatJson, adapterContextJson, String(input.endpoint || ''), input.requestId);
        if (raw instanceof Error) {
            return fail(raw.message || 'native error');
        }
        if (raw && typeof raw === 'object' && 'message' in raw) {
            const message = raw.message;
            if (typeof message === 'string' && message.trim().length) {
                return fail(message.trim());
            }
        }
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveReqInboundServerToolFollowupSnapshotWithNative(adapterContext) {
    return resolveServerToolFollowupSnapshotWithNative(adapterContext);
}
export function augmentReqInboundContextSnapshotWithNative(context, fallbackSnapshot) {
    return augmentContextSnapshotWithNative(context, fallbackSnapshot);
}
export function normalizeReqInboundToolCallIdStyleWithNative(value) {
    return normalizeToolCallIdStyleCandidateWithNative(value);
}
export function mapReqInboundBridgeToolsToChatWithNative(rawTools) {
    const capability = 'mapBridgeToolsToChatJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(Array.isArray(rawTools) ? rawTools : []);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        return parsed.filter((entry) => Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry));
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function mapChatToolsToBridgeWithNative(rawTools) {
    const capability = 'mapChatToolsToBridgeJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(Array.isArray(rawTools) ? rawTools : []);
    if (!payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        return parsed.filter((entry) => Boolean(entry) && typeof entry === 'object' && !Array.isArray(entry));
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function captureReqInboundResponsesContextSnapshotWithNative(input) {
    const capability = 'captureReqInboundResponsesContextSnapshotJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const inputJson = safeStringify({
        rawRequest: input.rawRequest,
        requestId: input.requestId,
        toolCallIdStyle: input.toolCallIdStyle
    });
    if (!inputJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inputJson);
        if (raw instanceof Error) {
            return fail(raw.message || 'native error');
        }
        if (raw && typeof raw === 'object' && 'message' in raw) {
            const message = raw.message;
            if (typeof message === 'string' && message.trim().length) {
                return fail(message.trim());
            }
        }
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function collectReqInboundToolOutputsWithNative(payload) {
    return collectToolOutputsWithNative(payload);
}
export function buildReqInboundToolOutputSnapshotWithNative(payload, providerProtocol) {
    const capability = 'buildReqInboundToolOutputSnapshotJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const payloadJson = safeStringify(payload);
    const providerProtocolJson = safeStringify(providerProtocol ?? null);
    if (!payloadJson || !providerProtocolJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(payloadJson, providerProtocolJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseToolOutputSnapshotBuildResult(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        replaceRecord(payload, parsed.payload);
        return parsed.snapshot;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function appendReqInboundToolParseDiagnosticTextWithNative(outputText, toolName) {
    const capability = 'appendToolParseDiagnosticTextJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('appendToolParseDiagnosticTextJson');
    if (!fn) {
        return fail();
    }
    const toolNameJson = safeStringify(toolName ?? null);
    if (!toolNameJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(outputText, toolNameJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseOptionalString(raw);
        return parsed === null ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function injectReqInboundToolParseDiagnosticsWithNative(payload) {
    const capability = 'injectToolParseDiagnosticsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('injectToolParseDiagnosticsJson');
    if (!fn) {
        return fail();
    }
    try {
        const payloadJson = JSON.stringify(payload);
        if (typeof payloadJson !== 'string') {
            return fail('json stringify failed');
        }
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        replaceRecord(payload, parsed);
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeReqInboundShellLikeToolCallsWithNative(payload) {
    const capability = 'normalizeShellLikeToolCallsBeforeGovernanceJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('normalizeShellLikeToolCallsBeforeGovernanceJson');
    if (!fn) {
        return fail();
    }
    try {
        const payloadJson = JSON.stringify(payload);
        if (typeof payloadJson !== 'string') {
            return fail('json stringify failed');
        }
        const raw = fn(payloadJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecord(raw);
        if (!parsed) {
            return fail('invalid payload');
        }
        replaceRecord(payload, parsed);
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
