import { failNativeRequired, isNativeDisabledByEnv } from './native-router-hotpath-policy.js';
import { loadNativeRouterHotpathBindingForInternalUse } from './native-router-hotpath.js';
function readNativeFunction(name) {
    const binding = loadNativeRouterHotpathBindingForInternalUse();
    const fn = binding?.[name];
    return typeof fn === 'function' ? fn : null;
}
function safeStringify(value) {
    try {
        return JSON.stringify(value);
    }
    catch {
        return undefined;
    }
}
function parseOrchestrationOutput(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        const requestId = typeof row.requestId === 'string' ? row.requestId : '';
        const success = row.success === true;
        if (!requestId) {
            return null;
        }
        const output = {
            requestId,
            success
        };
        if (row.payload && typeof row.payload === 'object' && !Array.isArray(row.payload)) {
            output.payload = row.payload;
        }
        if (row.metadata && typeof row.metadata === 'object' && !Array.isArray(row.metadata)) {
            output.metadata = row.metadata;
        }
        if (row.error && typeof row.error === 'object' && !Array.isArray(row.error)) {
            const err = row.error;
            const code = typeof err.code === 'string' ? err.code.trim() : '';
            const message = typeof err.message === 'string' ? err.message.trim() : '';
            if (code && message) {
                output.error = {
                    code,
                    message,
                    ...(Object.prototype.hasOwnProperty.call(err, 'details') ? { details: err.details } : {})
                };
            }
        }
        return output;
    }
    catch {
        return null;
    }
}
function parseString(raw) {
    try {
        const parsed = JSON.parse(raw);
        return typeof parsed === 'string' ? parsed : null;
    }
    catch {
        return null;
    }
}
function parseOptionalString(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return undefined;
        }
        return typeof parsed === 'string' ? parsed : null;
    }
    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 parseOptionalBoolean(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return undefined;
        }
        return typeof parsed === 'boolean' ? parsed : null;
    }
    catch {
        return null;
    }
}
function parseStopMessageRouterMetadata(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        const out = {};
        const assignIfNonEmpty = (key) => {
            const rawValue = row[key];
            if (typeof rawValue !== 'string') {
                return;
            }
            const trimmed = rawValue.trim();
            if (!trimmed) {
                return;
            }
            out[key] = trimmed;
        };
        assignIfNonEmpty('stopMessageClientInjectSessionScope');
        assignIfNonEmpty('stopMessageClientInjectScope');
        assignIfNonEmpty('clientTmuxSessionId');
        assignIfNonEmpty('client_tmux_session_id');
        assignIfNonEmpty('tmuxSessionId');
        assignIfNonEmpty('tmux_session_id');
        return out;
    }
    catch {
        return null;
    }
}
function parseHubPolicyOverride(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return undefined;
        }
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        const mode = typeof row.mode === 'string' ? row.mode.trim().toLowerCase() : '';
        if (mode !== 'off' && mode !== 'observe' && mode !== 'enforce') {
            return null;
        }
        const out = { mode };
        if (typeof row.sampleRate === 'number' && Number.isFinite(row.sampleRate)) {
            out.sampleRate = row.sampleRate;
        }
        return out;
    }
    catch {
        return null;
    }
}
function parseHubShadowCompareConfig(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return undefined;
        }
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        const row = parsed;
        const baselineMode = typeof row.baselineMode === 'string' ? row.baselineMode.trim().toLowerCase() : '';
        if (baselineMode !== 'off' && baselineMode !== 'observe' && baselineMode !== 'enforce') {
            return null;
        }
        return { baselineMode };
    }
    catch {
        return null;
    }
}
function parseApplyPatchToolMode(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return undefined;
        }
        if (typeof parsed !== 'string') {
            return null;
        }
        const mode = parsed.trim().toLowerCase();
        if (mode === 'schema' || mode === 'freeform') {
            return mode;
        }
        return null;
    }
    catch {
        return null;
    }
}
function parseStringArray(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!Array.isArray(parsed)) {
            return null;
        }
        const out = [];
        for (const entry of parsed) {
            if (typeof entry !== 'string') {
                return null;
            }
            out.push(entry);
        }
        return out;
    }
    catch {
        return null;
    }
}
export function runHubPipelineOrchestrationWithNative(input) {
    const capability = 'runHubPipelineJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const inputJson = safeStringify(input);
    if (!inputJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inputJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseOrchestrationOutput(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function normalizeHubEndpointWithNative(endpoint) {
    const capability = 'normalizeHubEndpointJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(String(endpoint || ''));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseString(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveHubProviderProtocolWithNative(value) {
    const capability = 'resolveProviderProtocolJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const normalizedInput = typeof value === 'string' ? value : '';
    try {
        const raw = fn(normalizedInput);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseString(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveHubClientProtocolWithNative(entryEndpoint) {
    const capability = 'resolveHubClientProtocolJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(String(entryEndpoint || ''));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseString(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveOutboundStreamIntentWithNative(providerPreference) {
    const capability = 'resolveOutboundStreamIntentJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const preferenceJson = safeStringify(providerPreference ?? null);
    if (!preferenceJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(preferenceJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseOptionalBoolean(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 applyOutboundStreamPreferenceWithNative(request, stream, processMode) {
    const capability = 'applyOutboundStreamPreferenceJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const requestJson = safeStringify(request ?? {});
    const streamJson = safeStringify(stream ?? null);
    const modeJson = safeStringify(processMode ?? null);
    if (!requestJson || !streamJson || !modeJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(requestJson, streamJson, modeJson);
        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 resolveHubSseProtocolFromMetadataWithNative(metadata) {
    const capability = 'resolveSseProtocolFromMetadataJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    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 = 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 resolveStopMessageRouterMetadataWithNative(metadata) {
    const capability = 'resolveStopMessageRouterMetadataJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? null);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseStopMessageRouterMetadata(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function extractAdapterContextMetadataFieldsWithNative(metadata, keys) {
    const capability = 'extractAdapterContextMetadataFieldsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? {});
    const keysJson = safeStringify(Array.isArray(keys) ? keys : []);
    if (!metadataJson || !keysJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson, keysJson);
        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 resolveHubPolicyOverrideFromMetadataWithNative(metadata) {
    const capability = 'resolveHubPolicyOverrideJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? null);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseHubPolicyOverride(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 resolveHubShadowCompareConfigWithNative(metadata) {
    const capability = 'resolveHubShadowCompareConfigJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? null);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseHubShadowCompareConfig(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 resolveApplyPatchToolModeFromToolsWithNative(toolsRaw) {
    const capability = 'resolveApplyPatchToolModeFromToolsJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const toolsJson = safeStringify(toolsRaw ?? null);
    if (!toolsJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(toolsJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseApplyPatchToolMode(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 resolveHasInstructionRequestedPassthroughWithNative(messages) {
    const capability = 'resolveHasInstructionRequestedPassthroughJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const messagesJson = safeStringify(messages ?? null);
    if (!messagesJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(messagesJson);
        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 resolveActiveProcessModeWithNative(baseMode, messages) {
    const capability = 'resolveActiveProcessModeJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const baseModeJson = safeStringify(baseMode);
    const messagesJson = safeStringify(messages ?? null);
    if (!baseModeJson || !messagesJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(baseModeJson, messagesJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseString(raw);
        if (parsed === 'chat' || parsed === 'passthrough') {
            return parsed;
        }
        return fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function findMappableSemanticsKeysWithNative(metadata) {
    const capability = 'findMappableSemanticsKeysJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const metadataJson = safeStringify(metadata ?? null);
    if (!metadataJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(metadataJson);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseStringArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildPassthroughAuditWithNative(rawInbound, providerProtocol) {
    const capability = 'buildPassthroughAuditJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const inboundJson = safeStringify(rawInbound ?? {});
    if (!inboundJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(inboundJson, String(providerProtocol || ''));
        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 annotatePassthroughGovernanceSkipWithNative(audit) {
    const capability = 'annotatePassthroughGovernanceSkipJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const auditJson = safeStringify(audit ?? {});
    if (!auditJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(auditJson);
        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 attachPassthroughProviderInputAuditWithNative(audit, providerPayload, providerProtocol) {
    const capability = 'attachPassthroughProviderInputAuditJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const auditJson = safeStringify(audit ?? {});
    const payloadJson = safeStringify(providerPayload ?? {});
    if (!auditJson || !payloadJson) {
        return fail('json stringify failed');
    }
    try {
        const raw = fn(auditJson, payloadJson, String(providerProtocol || ''));
        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);
    }
}
