'use strict';

const BLOCKING_STATUSES = new Set(['running', 'busy']);

function normalizeStatus(value) {
  const text = String(value || '').trim().toLowerCase().replace(/[-\s]+/g, '_');
  if (!text) return '';
  if (text === 'waiting' || text === 'waiting_for_input' || text === 'waiting_input') return 'waiting_input';
  if (text === 'busy') return 'running';
  return text;
}

function sessionLabel(session) {
  return String(
    session?.label ||
    session?.title ||
    session?.name ||
    session?.id ||
    ''
  ).trim();
}

function sessionId(session) {
  return String(session?.id || session?.sessionId || session?.ctmSessionId || '').trim();
}

function restartSessionSummary(session, status, waitingForInput, waitingReason) {
  const normalized = waitingForInput ? 'waiting_input' : normalizeStatus(status);
  const summary = {
    id: sessionId(session),
    label: sessionLabel(session),
    status: normalized || 'idle',
  };
  if (waitingReason) summary.waitingReason = waitingReason;
  return summary;
}

function normalizeWaitingReason(value) {
  return String(value || '').trim().toLowerCase().replace(/[-\s]+/g, '_');
}

function defaultWaitingReasonForSession(session) {
  return normalizeWaitingReason(
    session?.waitingReason ||
    session?.waiting_reason ||
    session?.reason ||
    session?._waitingForInputReason ||
    ''
  );
}

function isBlockingWaitingReason(reason) {
  const text = normalizeWaitingReason(reason);
  return text === 'approval' || text === 'choice';
}

function isBlockingWaitingSession(session, summary, waitingForInput, waitingReason, options) {
  if (typeof options.isBlockingWaitingForInput === 'function') {
    return !!options.isBlockingWaitingForInput(session);
  }
  if (isBlockingWaitingReason(waitingReason)) return true;
  // Older callers did not provide waiting reasons. Preserve the conservative
  // behavior for unknown waiting_input rows instead of silently restarting over
  // a possible approval prompt.
  return summary.status === 'waiting_input' && !waitingReason;
}

function summarizeRestartGuard(sessions = [], options = {}) {
  const items = Array.from(sessions || []).filter(Boolean);
  const blockers = [];
  const restorable = [];

  for (const session of items) {
    const rawStatus = typeof options.statusForSession === 'function'
      ? options.statusForSession(session)
      : (session.standupStatus || session.liveStatus || session.serverState || session.status || '');
    const waitingForInput = typeof options.isWaitingForInput === 'function'
      ? !!options.isWaitingForInput(session)
      : !!session.waitingForInput;
    const waitingReason = typeof options.waitingReasonForSession === 'function'
      ? normalizeWaitingReason(options.waitingReasonForSession(session))
      : defaultWaitingReasonForSession(session);
    const summary = restartSessionSummary(session, rawStatus, waitingForInput, waitingReason);
    if (
      BLOCKING_STATUSES.has(summary.status) ||
      (summary.status === 'waiting_input' &&
        isBlockingWaitingSession(session, summary, waitingForInput, waitingReason, options))
    ) blockers.push(summary);
    else restorable.push(summary);
  }

  return {
    totalCount: items.length,
    blockingCount: blockers.length,
    restorableCount: restorable.length,
    blockers,
    restorable,
  };
}

module.exports = {
  summarizeRestartGuard,
  _private: {
    normalizeStatus,
    normalizeWaitingReason,
    isBlockingWaitingReason,
    restartSessionSummary,
  },
};
