'use strict';

const DEFAULT_WALLE_HISTORY_RETRY_MS = 2500;

function isWalleLikeSession(session) {
  if (!session || typeof session !== 'object') return false;
  return session.type === 'walle'
    || session.agentType === 'walle'
    || session.meta?.type === 'walle'
    || session._restoreTask?.type === 'walle'
    || !!session._restoreTask?.chat_session_id
    || !!session.chatSessionId;
}

function shouldAutoStartDeferredRestore(session, msg, source) {
  if (!session?._restoreDeferred || !msg?.autoStartRestore) return false;
  if (!isWalleLikeSession(session)) return true;
  const normalizedSource = String(source || msg.type || '').trim();
  // Wall-E history is not a terminal frame. A visible attach from older clients
  // may still start the runtime, but snapshots/reflow/prewarm must not.
  return normalizedSource === 'attach';
}

function shouldRequestWalleHistory(input = {}, opts = {}) {
  if (opts.force === true) return true;
  if (input.hasRenderableMessages === true) return false;
  if (input.historyStatus === 'loaded' || input.loaded === true) return false;

  const requested = input.requested === true || input.historyStatus === 'loading' || input.loading === true;
  if (!requested) return true;

  const retryAfterMs = Number.isFinite(Number(opts.retryAfterMs))
    ? Math.max(0, Number(opts.retryAfterMs))
    : DEFAULT_WALLE_HISTORY_RETRY_MS;
  const requestedAt = Number(input.requestedAt || 0);
  if (!requestedAt) return true;
  const now = Number.isFinite(Number(opts.now)) ? Number(opts.now) : Date.now();
  return now - requestedAt >= retryAfterMs;
}

module.exports = {
  DEFAULT_WALLE_HISTORY_RETRY_MS,
  isWalleLikeSession,
  shouldAutoStartDeferredRestore,
  shouldRequestWalleHistory,
};
