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 parseArray(raw) {
    try {
        const parsed = JSON.parse(raw);
        return Array.isArray(parsed) ? parsed : null;
    }
    catch {
        return null;
    }
}
function parseRecordOrNull(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return null;
        }
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return null;
        }
        return parsed;
    }
    catch {
        return null;
    }
}
function parseRecordOrNullResult(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return { ok: true, value: null };
        }
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return { ok: false };
        }
        return { ok: true, value: parsed };
    }
    catch {
        return { ok: false };
    }
}
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 parseIndex(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (typeof parsed !== 'number' || !Number.isFinite(parsed)) {
            return null;
        }
        return Math.floor(parsed);
    }
    catch {
        return null;
    }
}
function parseStringOrNull(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return null;
        }
        return typeof parsed === 'string' ? parsed : undefined;
    }
    catch {
        return undefined;
    }
}
function parseClockConfigOrNull(raw) {
    try {
        const parsed = JSON.parse(raw);
        if (parsed === null) {
            return null;
        }
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
            return undefined;
        }
        return parsed;
    }
    catch {
        return undefined;
    }
}
export function resolveClockConfigWithNative(raw, rawIsUndefined) {
    const capability = 'resolveClockConfigJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    try {
        const rawResponse = fn(JSON.stringify(raw ?? null), rawIsUndefined === true);
        if (typeof rawResponse !== 'string' || !rawResponse) {
            return fail('empty result');
        }
        const parsed = parseClockConfigOrNull(rawResponse);
        return parsed === undefined ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function resolveClockSessionScopeWithNative(primary, fallback) {
    const capability = 'resolveClockSessionScopeJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction(capability);
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(JSON.stringify(primary ?? null), JSON.stringify(fallback ?? null));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseStringOrNull(raw);
        return parsed === undefined ? fail('invalid payload') : parsed;
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildClockMarkerScheduleMessagesWithNative(requestId, markerIndex, marker, payload) {
    const capability = 'buildClockMarkerScheduleMessagesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('buildClockMarkerScheduleMessagesJson');
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(requestId, Number.isFinite(markerIndex) ? Math.floor(markerIndex) : 0, JSON.stringify(marker), JSON.stringify(payload));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function findLastUserMessageIndexWithNative(messages) {
    const capability = 'findLastUserMessageIndexJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('findLastUserMessageIndexJson');
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(JSON.stringify(messages));
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseIndex(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function injectTimeTagIntoMessagesWithNative(messages, timeTagLine) {
    const capability = 'injectTimeTagIntoMessagesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('injectTimeTagIntoMessagesJson');
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(JSON.stringify(messages), timeTagLine);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildDueReminderUserMessageWithNative(reservation, dueInjectText) {
    const capability = 'buildDueReminderUserMessageJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('buildDueReminderUserMessageJson');
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(JSON.stringify(reservation ?? null), dueInjectText);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseRecordOrNullResult(raw);
        return parsed.ok ? parsed.value : fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
export function buildClockReminderMetadataWithNative(nextRequestMetadata, metadata, dueUserMessage, reservation) {
    const capability = 'buildClockReminderMetadataJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('buildClockReminderMetadataJson');
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(JSON.stringify(nextRequestMetadata ?? null), JSON.stringify(metadata ?? {}), dueUserMessage !== null && dueUserMessage !== undefined, JSON.stringify(reservation ?? null));
        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 buildClockReminderMessagesWithNative(baseMessages, markerToolMessages, dueUserMessage, timeTagLine) {
    const capability = 'buildClockReminderMessagesJson';
    const fail = (reason) => failNativeRequired(capability, reason);
    if (isNativeDisabledByEnv()) {
        return fail('native disabled');
    }
    const fn = readNativeFunction('buildClockReminderMessagesJson');
    if (!fn) {
        return fail();
    }
    try {
        const raw = fn(JSON.stringify(baseMessages), JSON.stringify(markerToolMessages), JSON.stringify(dueUserMessage ?? null), timeTagLine);
        if (typeof raw !== 'string' || !raw) {
            return fail('empty result');
        }
        const parsed = parseArray(raw);
        return parsed ?? fail('invalid payload');
    }
    catch (error) {
        const reason = error instanceof Error ? error.message : String(error ?? 'unknown');
        return fail(reason);
    }
}
