const CHAT_CONTEXT_CONFIRM_SUPPRESSION_STORAGE_KEY = 'codex-live-context-confirm-suppressed-by-session';

type ContextConfirmSuppressionMap = Record<string, string>;

function buildLocalDateKey(date = new Date()) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function readStoredContextConfirmSuppressionMap(): ContextConfirmSuppressionMap {
  if (typeof window === 'undefined') {
    return {};
  }

  try {
    const raw = window.localStorage.getItem(CHAT_CONTEXT_CONFIRM_SUPPRESSION_STORAGE_KEY);

    if (!raw) {
      return {};
    }

    const parsed = JSON.parse(raw);

    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
      return {};
    }

    return Object.fromEntries(
      Object.entries(parsed).flatMap(([sessionId, value]) => {
        const normalizedSessionId = sessionId.trim();
        const normalizedValue = typeof value === 'string' ? value.trim() : '';

        return normalizedSessionId && normalizedValue ? [[normalizedSessionId, normalizedValue]] : [];
      }),
    );
  } catch {
    return {};
  }
}

function writeStoredContextConfirmSuppressionMap(nextMap: ContextConfirmSuppressionMap) {
  if (typeof window === 'undefined') {
    return;
  }

  if (Object.keys(nextMap).length === 0) {
    window.localStorage.removeItem(CHAT_CONTEXT_CONFIRM_SUPPRESSION_STORAGE_KEY);
    return;
  }

  window.localStorage.setItem(CHAT_CONTEXT_CONFIRM_SUPPRESSION_STORAGE_KEY, JSON.stringify(nextMap));
}

export function shouldSkipContextConfirmForSessionToday(sessionId: string, date = new Date()) {
  const normalizedSessionId = sessionId.trim();

  if (!normalizedSessionId) {
    return false;
  }

  const suppressionMap = readStoredContextConfirmSuppressionMap();
  return suppressionMap[normalizedSessionId] === buildLocalDateKey(date);
}

export function setSkipContextConfirmForSessionToday(sessionId: string, shouldSkip: boolean, date = new Date()) {
  const normalizedSessionId = sessionId.trim();

  if (!normalizedSessionId) {
    return;
  }

  const suppressionMap = readStoredContextConfirmSuppressionMap();

  if (shouldSkip) {
    suppressionMap[normalizedSessionId] = buildLocalDateKey(date);
  } else {
    delete suppressionMap[normalizedSessionId];
  }

  writeStoredContextConfirmSuppressionMap(suppressionMap);
}
