import { failNativeRequired } 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 parseRecordPayload(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
export function serializeStopMessageStateWithNative(state) {
    const capability = 'serializeStopMessageStateJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const stateJson = safeStringify(state);
    if (!stateJson) {
        return fail('json stringify failed');
    }
    try {
        const result = fn(stateJson);
        if (typeof result !== 'string' || !result) {
            return fail('empty result');
        }
        const parsed = parseRecordPayload(result);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function deserializeStopMessageStateWithNative(data, state) {
    const capability = 'deserializeStopMessageStateJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    const dataJson = safeStringify(data);
    const stateJson = safeStringify(state);
    if (!dataJson || !stateJson) {
        return fail('json stringify failed');
    }
    try {
        const result = fn(dataJson, stateJson);
        if (typeof result !== 'string' || !result) {
            return fail('empty result');
        }
        const parsed = parseRecordPayload(result);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
