/**
 * Daily-spend tracking — bucketed USD spend per local date.
 *
 * Persisted in GlobalConfig.dailySpendByDate as a map from YYYY-MM-DD
 * (local time) to USD. The store is updated from addToTotalSessionCost
 * so `/cost` and `/budget` can report real "today's spend" instead of
 * the current session's spend alone.
 *
 * All helpers here are pure — persistence lives in a wrapper in
 * cost-tracker so these remain trivially unit-testable.
 */

export type DailySpendStore = Record<string, number>

const MS_PER_DAY = 24 * 60 * 60 * 1000

/**
 * Format a Date as YYYY-MM-DD in the caller's local timezone. Using
 * local time (not UTC) matches how a user thinks about "today" — a
 * user in UTC-8 expects the budget to reset at local midnight, not at
 * 16:00 their time.
 */
export function getLocalDateKey(d: Date): string {
  const yyyy = d.getFullYear()
  const mm = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  return `${yyyy}-${mm}-${dd}`
}

/**
 * Return a new store with `amount` accumulated into the bucket for
 * `now`'s local date. Non-positive amounts are ignored.
 */
export function addToDailySpend(
  store: DailySpendStore,
  now: Date,
  amount: number,
): DailySpendStore {
  if (!Number.isFinite(amount) || amount <= 0) return store
  const key = getLocalDateKey(now)
  return {
    ...store,
    [key]: (store[key] ?? 0) + amount,
  }
}

/**
 * Today's spend according to the local calendar.
 */
export function getTodaySpend(store: DailySpendStore, now: Date): number {
  return store[getLocalDateKey(now)] ?? 0
}

/**
 * Drop buckets older than `keepDays` (inclusive of today). Keeps the
 * config file from growing unbounded while preserving enough history
 * for weekly/7-day reporting.
 */
export function pruneOldDays(store: DailySpendStore, now: Date, keepDays: number): DailySpendStore {
  const cutoff = now.getTime() - (keepDays - 1) * MS_PER_DAY
  const cutoffKey = getLocalDateKey(new Date(cutoff))
  const out: DailySpendStore = {}
  for (const [key, value] of Object.entries(store)) {
    if (key >= cutoffKey) out[key] = value
  }
  return out
}
