function isFiniteNumber(value) {
    return typeof value === 'number' && Number.isFinite(value);
}
function updatedAtOf(state) {
    if (!state)
        return null;
    return isFiniteNumber(state.stopMessageUpdatedAt) ? state.stopMessageUpdatedAt : null;
}
function lastUsedAtOf(state) {
    if (!state)
        return null;
    return isFiniteNumber(state.stopMessageLastUsedAt) ? state.stopMessageLastUsedAt : null;
}
/**
 * Decide whether we should overwrite in-memory stopMessage fields with persisted ones.
 *
 * Key invariant:
 * - In-memory state may be ahead of disk because persistence is async (tmp+rename).
 * - Persisted state must still be able to update usage counters (stop_message_auto).
 *
 * Strategy:
 * - If existing has a newer stopMessageUpdatedAt than persisted → keep existing config.
 * - Otherwise → adopt persisted fully.
 *
 * Note:
 * - We intentionally do NOT merge counters from an older persisted config into a newer in-memory config.
 *   A stopMessage "set" is expected to re-arm/reset counters; allowing older lastUsedAt to overwrite
 *   would make re-arming flaky until the async persistence catches up.
 */
export function mergeStopMessageFromPersisted(existing, persisted) {
    if (!persisted) {
        return { ...existing };
    }
    const existingUpdatedAt = updatedAtOf(existing);
    const persistedUpdatedAt = updatedAtOf(persisted);
    const existingIsNewer = existingUpdatedAt !== null && (persistedUpdatedAt === null || persistedUpdatedAt < existingUpdatedAt);
    if (!existingIsNewer) {
        return {
            ...existing,
            stopMessageSource: persisted.stopMessageSource,
            stopMessageText: persisted.stopMessageText,
            stopMessageMaxRepeats: persisted.stopMessageMaxRepeats,
            stopMessageUsed: persisted.stopMessageUsed,
            stopMessageStageMode: persisted.stopMessageStageMode,
            stopMessageAiMode: persisted.stopMessageAiMode,
            stopMessageAiSeedPrompt: persisted.stopMessageAiSeedPrompt,
            stopMessageAiHistory: persisted.stopMessageAiHistory,
            stopMessageUpdatedAt: persisted.stopMessageUpdatedAt,
            stopMessageLastUsedAt: persisted.stopMessageLastUsedAt
        };
    }
    return { ...existing };
}
