/** Training session calendar: weekday patterns (Mon=1…Sun=7), project holidays, date range. */

export const DEFAULT_SESSION_WEEKDAYS = [1, 2, 3, 4, 5] as const;

export function parseSessionWeekdays(raw: unknown): number[] {
  if (!Array.isArray(raw) || raw.length === 0) return [...DEFAULT_SESSION_WEEKDAYS];
  const nums = raw.map((x) => Number(x)).filter((n) => Number.isInteger(n) && n >= 1 && n <= 7);
  return nums.length ? Array.from(new Set(nums)).sort((a, b) => a - b) : [...DEFAULT_SESSION_WEEKDAYS];
}

/** ISO weekday with Monday = 1 … Sunday = 7. */
export function isoWeekdayMonToSun(d: Date): number {
  const x = d.getDay();
  return x === 0 ? 7 : x;
}

export function sessionDateKey(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

/**
 * Normalize attendance CSV session dates.
 * Accepts YYYY-MM-DD and Excel-rewritten M/D/YYYY (or MM/DD/YYYY).
 */
export function normalizeAttendanceSessionDate(raw: string): string | null {
  let value = String(raw ?? "").trim();
  if (!value) return null;

  // Excel formula cells exported as ="2026-05-18"
  const formula = /^=\s*"([^"]*)"\s*$/.exec(value);
  if (formula) value = (formula[1] ?? "").trim();

  const iso = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(value);
  if (iso) {
    const y = Number(iso[1]);
    const m = Number(iso[2]);
    const d = Number(iso[3]);
    if (!Number.isInteger(y) || !Number.isInteger(m) || !Number.isInteger(d)) return null;
    if (m < 1 || m > 12 || d < 1 || d > 31) return null;
    const probe = new Date(Date.UTC(y, m - 1, d));
    if (probe.getUTCFullYear() !== y || probe.getUTCMonth() + 1 !== m || probe.getUTCDate() !== d) return null;
    return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
  }

  // Excel often rewrites ISO dates as M/D/YYYY when the file is opened/saved.
  const slash = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(value);
  if (slash) {
    const m = Number(slash[1]);
    const d = Number(slash[2]);
    const y = Number(slash[3]);
    if (!Number.isInteger(y) || !Number.isInteger(m) || !Number.isInteger(d)) return null;
    if (m < 1 || m > 12 || d < 1 || d > 31) return null;
    const probe = new Date(Date.UTC(y, m - 1, d));
    if (probe.getUTCFullYear() !== y || probe.getUTCMonth() + 1 !== m || probe.getUTCDate() !== d) return null;
    return `${String(y).padStart(4, "0")}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
  }

  return null;
}

export function eachCalendarDateInclusive(start: Date, end: Date): Date[] {
  const s = new Date(start.getFullYear(), start.getMonth(), start.getDate());
  const e = new Date(end.getFullYear(), end.getMonth(), end.getDate());
  const out: Date[] = [];
  const cur = new Date(s);
  while (cur.getTime() <= e.getTime()) {
    out.push(new Date(cur));
    cur.setDate(cur.getDate() + 1);
  }
  return out;
}

export function holidayKeySet(dates: Iterable<Date>): Set<string> {
  const s = new Set<string>();
  for (const d of dates) s.add(sessionDateKey(d));
  return s;
}

export type TrainingDateRange = {
  startDate: Date;
  endDate: Date;
  sessionWeekdays: unknown;
};

/**
 * Session dates between training start and end (inclusive), on configured weekdays,
 * excluding project holidays. When `capTo` is set, dates after `capTo` are omitted
 * (e.g. only sessions up to “today” count as “delivered” for KPI).
 */
function localMidnight(d: Date): Date {
  return new Date(d.getFullYear(), d.getMonth(), d.getDate());
}

function minLocalDate(a: Date, b: Date): Date {
  return new Date(Math.min(localMidnight(a).getTime(), localMidnight(b).getTime()));
}

/**
 * Session dates between training start and end (inclusive), on configured weekdays,
 * excluding project holidays. When `capTo` is set (e.g. today), dates after it are omitted.
 */
export function scheduledSessionDates(
  training: TrainingDateRange,
  projectHolidayDates: Date[],
  capTo?: Date,
): Date[] {
  const weekdays = new Set(parseSessionWeekdays(training.sessionWeekdays));
  const holidays = holidayKeySet(projectHolidayDates);
  const rangeEnd = capTo ? minLocalDate(training.endDate, capTo) : training.endDate;
  const days = eachCalendarDateInclusive(training.startDate, rangeEnd);
  return days.filter((d) => {
    if (!weekdays.has(isoWeekdayMonToSun(d))) return false;
    if (holidays.has(sessionDateKey(d))) return false;
    return true;
  });
}

export function isScheduledSessionDate(
  training: TrainingDateRange,
  projectHolidayDates: Date[],
  sessionDate: Date,
  capTo?: Date,
): boolean {
  const dates = scheduledSessionDates(training, projectHolidayDates, capTo);
  const key = sessionDateKey(sessionDate);
  return dates.some((d) => sessionDateKey(d) === key);
}
