import { failNativeRequired, isNativeDisabledByEnv } from './native-router-hotpath-policy.js';
import { loadNativeRouterHotpathBindingForInternalUse } from './native-router-hotpath.js';
function parseHint(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 hint = {};
        if (row.force === true) {
            hint.force = true;
        }
        if (row.disable === true) {
            hint.disable = true;
        }
        return Object.keys(hint).length ? hint : undefined;
    }
    catch {
        return null;
    }
}
export function extractWebSearchSemanticsHintWithNative(semantics) {
    const capability = 'extractWebSearchSemanticsHintJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const binding = loadNativeRouterHotpathBindingForInternalUse();
    const fn = binding?.extractWebSearchSemanticsHintJson;
    if (typeof fn !== 'function') {
        return fail();
    }
    try {
        const raw = fn(JSON.stringify(semantics ?? null));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseHint(raw);
        return parsed === null ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
