import type { DateOnly } from "../../shared/dates.js";

export interface TraineeMarks { eligibleFrom: DateOnly | null; attended: ReadonlySet<DateOnly> }
export interface AttendanceResult {
  possibleToDate: number; presentToDate: number; possibleFinal: number; presentFinal: number;
  rateToDate: number; rateFinal: number; maxReachable: number; systemFinal: boolean; systemRisk: boolean;
}
export const pct = (n: number, d: number): number => (d <= 0 ? 0 : Math.round((n / d) * 10000) / 100);

/** Attendance and system dropout for one trainee. `sessions` are the counted days of the whole class (V1 dropoutProtocol). */
export function computeAttendance(sessions: readonly DateOnly[], t: TraineeMarks, todayDate: DateOnly, classEnd: DateOnly): AttendanceResult {
  const mine = t.eligibleFrom ? sessions.filter((d) => d >= t.eligibleFrom!) : sessions;
  let possibleToDate = 0, presentToDate = 0, presentFinal = 0;
  for (const d of mine) {
    const attended = t.attended.has(d);
    if (attended) presentFinal++;
    if (d <= todayDate) { possibleToDate++; if (attended) presentToDate++; }
  }
  const possibleFinal = mine.length;
  const rateToDate = pct(presentToDate, possibleToDate), rateFinal = pct(presentFinal, possibleFinal);
  const maxReachable = pct(presentToDate + (possibleFinal - possibleToDate), possibleFinal);
  const systemFinal = todayDate > classEnd && possibleFinal > 0 && rateFinal < 80;
  const systemRisk = !systemFinal && possibleToDate > 0 && (100 - rateToDate >= 15 || maxReachable < 80);
  return { possibleToDate, presentToDate, possibleFinal, presentFinal, rateToDate, rateFinal, maxReachable, systemFinal, systemRisk };
}
