/**
 * Period helpers for the AAO Gateway Phase 2b usage tracker.
 *
 * Buckets are monthly UTC strings — 'YYYY-MM' — chosen for three reasons:
 *  1. Cheap string comparison + sort (lexicographic order matches calendar order).
 *  2. Trivial human readability in admin logs and the UI history bar.
 *  3. LiteLLM Proxy uses the same shape, easing future migration.
 *
 * Resetting always happens at the UTC month boundary — operators in
 * different timezones see the same period roll over at the same instant
 * (vs. local-time resets, where two adjacent gateway instances in
 * different time zones would disagree). Choosing UTC also avoids DST
 * edge cases entirely.
 *
 * Pure functions; injectable `now` for tests. Never touch the system
 * clock outside the optional argument.
 */

/**
 * Format a UTC Date as 'YYYY-MM' (e.g. '2026-05'). Pure — never reads
 * the system clock unless `now` is omitted.
 */
export function currentPeriodYearMonth(now?: Date): string {
  const d = now ?? new Date();
  const y = d.getUTCFullYear();
  const m = d.getUTCMonth() + 1; // getUTCMonth is 0-indexed
  return `${y}-${m < 10 ? '0' : ''}${m}`;
}

/**
 * Strict shape check for a 'YYYY-MM' bucket string. Used by the admin
 * GET /:id/usage response to defend against corrupted DB rows and (in
 * future) by an admin-supplied period filter.
 *
 * Validates the calendar (no '2026-13', no '2026-0') but does NOT
 * validate whether the period exists yet — '2099-12' parses fine.
 */
export function isValidPeriod(p: unknown): p is string {
  if (typeof p !== 'string') return false;
  const m = p.match(/^(\d{4})-(\d{2})$/);
  if (!m) return false;
  const month = Number(m[2]);
  return month >= 1 && month <= 12;
}
