/**
 * The Extended-route delivery clock (owner answers 033–046, B017, B031–B035;
 * Nash, 2026-10-07 item 1). All maths is in America/Chicago:
 *
 *   Monday–Friday 7 AM–7 PM · Saturday 9 AM–5 PM · Sunday closed
 *   US federal holidays closed, on their observed dates (a Saturday holiday is
 *   observed the Friday before, a Sunday holiday the Monday after).
 *
 * The clock pauses outside these windows and resumes at the next opening.
 * Pure functions, no I/O — the alert job (T14) builds on them.
 */
export const BUSINESS_TIME_ZONE = 'America/Chicago'

const HOUR = 3_600_000
type Ymd = { y: number; m: number; d: number }

/** Opening and closing hour for a weekday (0 = Sunday), or null when closed. */
const WINDOWS: Record<number, [number, number] | null> = {
  0: null, 1: [7, 19], 2: [7, 19], 3: [7, 19], 4: [7, 19], 5: [7, 19], 6: [9, 17],
}

const fmt = new Intl.DateTimeFormat('en-US', {
  timeZone: BUSINESS_TIME_ZONE, hourCycle: 'h23',
  year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
})

function wall(instant: number) {
  const p = Object.fromEntries(fmt.formatToParts(new Date(instant)).map((x) => [x.type, x.value]))
  return { y: +p.year, m: +p.month, d: +p.day, h: +p.hour, mi: +p.minute, s: +p.second }
}

/** The UTC instant of a Chicago wall-clock time (never called inside the 2–3 AM DST gap). */
function chicagoToUtc(date: Ymd, hour: number): number {
  const guess = Date.UTC(date.y, date.m - 1, date.d, hour)
  const offsetAt = (t: number) => { const w = wall(t); return Date.UTC(w.y, w.m - 1, w.d, w.h, w.mi, w.s) - t }
  const first = guess - offsetAt(guess)
  return guess - offsetAt(first)
}

const key = ({ y, m, d }: Ymd) => `${y}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`
const weekday = ({ y, m, d }: Ymd) => new Date(Date.UTC(y, m - 1, d)).getUTCDay()
const nextDay = ({ y, m, d }: Ymd): Ymd => { const t = new Date(Date.UTC(y, m - 1, d + 1)); return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate() } }

function nthWeekday(y: number, m: number, dow: number, n: number): Ymd {
  const first = new Date(Date.UTC(y, m - 1, 1)).getUTCDay()
  return { y, m, d: 1 + ((dow - first + 7) % 7) + (n - 1) * 7 }
}
function lastWeekday(y: number, m: number, dow: number): Ymd {
  const lastDate = new Date(Date.UTC(y, m, 0)).getUTCDate()
  const last = new Date(Date.UTC(y, m - 1, lastDate)).getUTCDay()
  return { y, m, d: lastDate - ((last - dow + 7) % 7) }
}
/** A fixed-date holiday moves to Friday when it falls on Saturday, Monday when on Sunday. */
function observed(date: Ymd): Ymd {
  const dow = weekday(date)
  const t = new Date(Date.UTC(date.y, date.m - 1, date.d + (dow === 6 ? -1 : dow === 0 ? 1 : 0)))
  return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate() }
}

/** Observed US federal holidays for a year, as YYYY-MM-DD. */
export function federalHolidays(year: number): Set<string> {
  const days: Ymd[] = [
    observed({ y: year, m: 1, d: 1 }),       // New Year's Day
    nthWeekday(year, 1, 1, 3),               // Martin Luther King Jr. Day
    nthWeekday(year, 2, 1, 3),               // Washington's Birthday
    lastWeekday(year, 5, 1),                 // Memorial Day
    observed({ y: year, m: 6, d: 19 }),      // Juneteenth
    observed({ y: year, m: 7, d: 4 }),       // Independence Day
    nthWeekday(year, 9, 1, 1),               // Labor Day
    nthWeekday(year, 10, 1, 2),              // Columbus Day
    observed({ y: year, m: 11, d: 11 }),     // Veterans Day
    nthWeekday(year, 11, 4, 4),              // Thanksgiving
    observed({ y: year, m: 12, d: 25 }),     // Christmas Day
  ]
  // New Year's Day of the next year can be observed on Dec 31 of this one.
  const nextNewYear = observed({ y: year + 1, m: 1, d: 1 })
  if (nextNewYear.y === year) days.push(nextNewYear)
  return new Set(days.map(key))
}

const holidayCache = new Map<number, Set<string>>()
export function isFederalHoliday(date: Ymd): boolean {
  if (!holidayCache.has(date.y)) holidayCache.set(date.y, federalHolidays(date.y))
  return holidayCache.get(date.y)!.has(key(date))
}

/** The business window of one Chicago calendar date, as UTC instants, or null when closed. */
function windowOf(date: Ymd): [number, number] | null {
  const hours = WINDOWS[weekday(date)]
  if (!hours || isFederalHoliday(date)) return null
  return [chicagoToUtc(date, hours[0]), chicagoToUtc(date, hours[1])]
}

const dateOf = (instant: number): Ymd => { const w = wall(instant); return { y: w.y, m: w.m, d: w.d } }

/** Business time elapsed between two instants, in milliseconds. */
export function businessMillisBetween(start: Date, end: Date): number {
  const a = start.getTime(), b = end.getTime()
  if (b <= a) return 0
  let total = 0
  for (let day = dateOf(a); ; day = nextDay(day)) {
    const w = windowOf(day)
    if (w) total += Math.max(0, Math.min(w[1], b) - Math.max(w[0], a))
    if (w ? w[1] >= b : chicagoToUtc(day, 23) >= b) break
  }
  return total
}

/** The instant when `hours` of business time have elapsed after `start` (a checkpoint's due time). */
export function addBusinessHours(start: Date, hours: number): Date {
  let remaining = hours * HOUR
  const a = start.getTime()
  for (let day = dateOf(a), guard = 0; guard < 400; day = nextDay(day), guard++) {
    const w = windowOf(day)
    if (!w) continue
    const from = Math.max(w[0], a)
    const available = w[1] - from
    if (available <= 0) continue
    if (remaining <= available) return new Date(from + remaining)
    remaining -= available
  }
  throw new Error('business clock did not converge')
}

/** True when the instant falls inside a business window (its closing moment included). */
export function isWithinBusinessHours(at: Date): boolean {
  const t = at.getTime()
  const w = windowOf(dateOf(t))
  return !!w && t >= w[0] && t <= w[1]
}

/** When an alert due at `due` may be sent: at once inside business hours, else at the next opening. */
export function alertSendTime(due: Date): Date {
  if (isWithinBusinessHours(due)) return due
  const t = due.getTime()
  for (let day = dateOf(t), guard = 0; guard < 400; day = nextDay(day), guard++) {
    const w = windowOf(day)
    if (w && w[0] >= t) return new Date(w[0])
  }
  throw new Error('no business opening found')
}
