import { prisma } from "../prisma.js";
import { scheduledSessionDates, sessionDateKey, type TrainingDateRange } from "./attendanceCalendar.js";
import { eligibleSessionKeysForTrainee, traineeBreakdownExcludedKeysForDeliveryBatch } from "./attendanceEligibility.js";
import { filterScheduledDatesExcludingExemptPeriod, loadAttendanceExemptDaysFromStart } from "./attendanceExemptPeriod.js";
import { rosterRoleCountsAttendanceSlots, rosterRoleReceivesAttendanceCapture } from "./traineeRoster.js";

type RollupRosterMode = "kpi" | "capture";

function traineeIncludedInRollup(mode: RollupRosterMode, rosterRole: string): boolean {
  return mode === "kpi" ? rosterRoleCountsAttendanceSlots(rosterRole) : rosterRoleReceivesAttendanceCapture(rosterRole);
}

function effectiveStartDate(startDate: Date, timelineAnchorDate?: Date | null): Date {
  return timelineAnchorDate ?? startDate;
}

export type AttendanceCounts = { present: number; possible: number; byTp: Map<string, { present: number; possible: number }> };

type TraineeSlot = {
  id: bigint;
  cohortId: bigint | null;
  /** Present when trainee row includes delivery batch linkage. */
  batchId?: bigint | null;
  rosterRole: string;
  attendanceEligibleFrom: Date | null;
};

/**
 * Protocol §9 — sessions attended ÷ sessions scheduled (to date), tracked roster (active + reserve) for KPI rate.
 * Denominator: per trainee, all scheduled sessions in delivery batch range (holidays/breakdowns excluded).
 */
export async function computeAttendancePresentPossible(projectId: bigint, asOf: Date = new Date()): Promise<AttendanceCounts> {
  return computeAttendancePresentPossibleInternal(projectId, "kpi", asOf);
}

/** Expected slots for attendance capture roster (active + reserve). Used for completion submission gates, not KPI rate. */
export async function computeAttendanceCapturePossible(projectId: bigint, asOf: Date = new Date()): Promise<AttendanceCounts> {
  return computeAttendancePresentPossibleInternal(projectId, "capture", asOf);
}

async function computeAttendancePresentPossibleInternal(
  projectId: bigint,
  mode: RollupRosterMode,
  asOf: Date = new Date(),
): Promise<AttendanceCounts> {
  const holidays = await prisma.projectHoliday.findMany({
    where: { projectId },
    select: { holidayDate: true },
  });
  const holidayDates = holidays.map((h) => h.holidayDate);
  const exemptDays = await loadAttendanceExemptDaysFromStart(prisma);

  const trainings = await prisma.training.findMany({
    where: { projectId },
    select: {
      id: true,
      trainingProviderId: true,
      startDate: true,
      endDate: true,
      timelineAnchorDate: true,
      sessionWeekdays: true,
      trainees: {
        select: {
          id: true,
          cohortId: true,
          batchId: true,
          rosterRole: true,
          attendanceEligibleFrom: true,
        },
      },
    },
  });
  const approvedBreakdowns = await prisma.trainingBreakdown.findMany({
    where: { projectId, status: "approved" },
    select: { trainingId: true, cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
  });

  const byTp = new Map<string, { present: number; possible: number }>();
  let projectPossible = 0;
  let projectPresent = 0;

  for (const tr of trainings) {
    const breakdowns = approvedBreakdowns.filter((b) => b.trainingId === tr.id);
    const tpId = tr.trainingProviderId.toString();

    const batchEligible = tr.trainees.filter((t) => traineeIncludedInRollup(mode, t.rosterRole) && t.batchId != null);
    const batchIds = [...new Set(batchEligible.map((t) => t.batchId!))];

    let possible = 0;
    let present = 0;

    if (batchIds.length > 0) {
      const batchRows = await prisma.trainingBatch.findMany({
        where: { projectId, trainingId: tr.id, id: { in: batchIds } },
        select: {
          id: true,
          cohortId: true,
          startDate: true,
          endDate: true,
          timelineAnchorDate: true,
          sessionWeekdays: true,
        },
      });
      const batchMeta = new Map(batchRows.map((b) => [b.id.toString(), b]));

      for (const bid of batchIds) {
        const batch = batchMeta.get(bid.toString());
        if (!batch) continue;
        const scopeTrainees = batchEligible.filter((t) => t.batchId!.toString() === bid.toString());
        if (scopeTrainees.length === 0) continue;

        const anchorStart = effectiveStartDate(batch.startDate, batch.timelineAnchorDate);
        const range: TrainingDateRange = {
          startDate: anchorStart,
          endDate: batch.endDate,
          sessionWeekdays: batch.sessionWeekdays ?? tr.sessionWeekdays,
        };
        const sessionDates = filterScheduledDatesExcludingExemptPeriod(
          scheduledSessionDates(range, holidayDates, asOf),
          anchorStart,
          exemptDays,
        );
        if (sessionDates.length === 0) continue;

        const eligibleKeysByTrainee = new Map<string, Set<string>>();
        for (const trainee of scopeTrainees) {
          const bdExcluded = traineeBreakdownExcludedKeysForDeliveryBatch(breakdowns, trainee.cohortId, bid);
          const keys = eligibleSessionKeysForTrainee({
            sessionDatesOrdered: sessionDates,
            attendanceEligibleFrom: trainee.attendanceEligibleFrom,
            excludedSessionKeys: bdExcluded,
          });
          eligibleKeysByTrainee.set(trainee.id.toString(), new Set(keys));
          possible += keys.length;
        }

        const first = sessionDates[0]!;
        const last = sessionDates[sessionDates.length - 1]!;
        const nextDayAfterLast = new Date(last.getTime() + 24 * 60 * 60 * 1000);
        const rows = await prisma.traineeAttendanceDay.findMany({
          where: {
            projectId,
            trainingId: tr.id,
            batchId: bid,
            status: { in: ["present", "excused"] },
            sessionDate: { gte: first, lt: nextDayAfterLast },
            traineeId: { in: scopeTrainees.map((x) => x.id) },
          },
          select: { traineeId: true, sessionDate: true },
        });
        present += rows.filter((r) => {
          const key = sessionDateKey(r.sessionDate);
          const allowed = eligibleKeysByTrainee.get(r.traineeId.toString());
          return Boolean(allowed?.has(key));
        }).length;
      }
    }

    projectPossible += possible;
    projectPresent += present;

    const cur = byTp.get(tpId) ?? { present: 0, possible: 0 };
    cur.present += present;
    cur.possible += possible;
    byTp.set(tpId, cur);
  }

  return {
    present: projectPresent,
    possible: projectPossible,
    byTp,
  };
}

export type TraineeAttendanceRateRow = {
  traineeId: bigint;
  traineeUniqueId: string;
  externalBeneficiaryId: string | null;
  firstName: string;
  fatherName: string | null;
  grandfatherName: string | null;
  sex: string;
  rosterRole: string;
  attendanceEligibleFrom: Date | null;
  trainingId: bigint;
  trainingTitle: string;
  cohortId: bigint | null;
  cohortCode: string | null;
  cohortName: string | null;
  batchId: bigint | null;
  batchCode: string | null;
  batchName: string | null;
  present: number;
  possible: number;
  /** null when the trainee has no eligible sessions yet (no delivery batch or not started). */
  ratePct: number | null;
};

/**
 * Per-trainee attendance rates for one training provider: attended (present + excused) ÷ eligible
 * scheduled sessions, using the same denominator policy as the provider KPI in
 * computeAttendancePresentPossible. Every tracked roster member (active + reserve) keeps a row so
 * the export lists the full roster; members without a delivery batch get possible = 0.
 */
export async function computeTraineeAttendanceRatesForProvider(
  projectId: bigint,
  trainingProviderId: bigint,
  asOf: Date = new Date(),
): Promise<TraineeAttendanceRateRow[]> {
  const [holidayRows, exemptDays, trainings] = await Promise.all([
    prisma.projectHoliday.findMany({ where: { projectId }, select: { holidayDate: true } }),
    loadAttendanceExemptDaysFromStart(prisma),
    prisma.training.findMany({
      where: { projectId, trainingProviderId },
      select: {
        id: true,
        title: true,
        sessionWeekdays: true,
        trainees: {
          select: {
            id: true,
            traineeUniqueId: true,
            externalBeneficiaryId: true,
            firstName: true,
            fatherName: true,
            grandfatherName: true,
            sex: true,
            cohortId: true,
            batchId: true,
            rosterRole: true,
            attendanceEligibleFrom: true,
          },
        },
      },
      orderBy: { id: "asc" },
    }),
  ]);

  const holidayDates = holidayRows.map((h) => h.holidayDate);
  const trainingIds = trainings.map((t) => t.id);
  if (trainingIds.length === 0) return [];

  const [batches, breakdowns, cohorts] = await Promise.all([
    prisma.trainingBatch.findMany({
      where: { projectId, trainingId: { in: trainingIds } },
      select: {
        id: true,
        trainingId: true,
        cohortId: true,
        code: true,
        name: true,
        startDate: true,
        endDate: true,
        timelineAnchorDate: true,
        sessionWeekdays: true,
      },
    }),
    prisma.trainingBreakdown.findMany({
      where: { projectId, trainingId: { in: trainingIds }, status: "approved" },
      select: { trainingId: true, cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
    }),
    prisma.trainingCohort.findMany({
      where: { projectId, trainingId: { in: trainingIds } },
      select: { id: true, code: true, name: true },
    }),
  ]);

  const trainingById = new Map(trainings.map((t) => [t.id.toString(), t]));
  const batchById = new Map(batches.map((b) => [b.id.toString(), b]));
  const cohortById = new Map(cohorts.map((c) => [c.id.toString(), c]));

  const sessionDatesByBatch = new Map<string, Date[]>();
  for (const batch of batches) {
    const training = trainingById.get(batch.trainingId.toString());
    if (!training) continue;
    const anchorStart = effectiveStartDate(batch.startDate, batch.timelineAnchorDate);
    sessionDatesByBatch.set(
      batch.id.toString(),
      filterScheduledDatesExcludingExemptPeriod(
        scheduledSessionDates(
          {
            startDate: anchorStart,
            endDate: batch.endDate,
            sessionWeekdays: batch.sessionWeekdays ?? training.sessionWeekdays,
          },
          holidayDates,
          asOf,
        ),
        anchorStart,
        exemptDays,
      ),
    );
  }

  const attendanceRows = batches.length
    ? await prisma.traineeAttendanceDay.findMany({
        where: {
          projectId,
          trainingProviderId,
          batchId: { in: batches.map((b) => b.id) },
          status: { in: ["present", "excused"] },
        },
        select: { traineeId: true, batchId: true, sessionDate: true },
      })
    : [];

  const attendedKeysByTraineeBatch = new Map<string, Set<string>>();
  for (const row of attendanceRows) {
    const key = `${row.traineeId.toString()}:${row.batchId.toString()}`;
    const set = attendedKeysByTraineeBatch.get(key) ?? new Set<string>();
    set.add(sessionDateKey(row.sessionDate));
    attendedKeysByTraineeBatch.set(key, set);
  }

  const out: TraineeAttendanceRateRow[] = [];
  for (const training of trainings) {
    const trainingBreakdowns = breakdowns.filter((b) => b.trainingId === training.id);
    for (const trainee of training.trainees) {
      if (!rosterRoleCountsAttendanceSlots(trainee.rosterRole)) continue;

      let possible = 0;
      let present = 0;
      if (trainee.batchId != null) {
        const batch = batchById.get(trainee.batchId.toString());
        const sessionDates = sessionDatesByBatch.get(trainee.batchId.toString()) ?? [];
        if (batch && sessionDates.length > 0) {
          const keys = eligibleSessionKeysForTrainee({
            sessionDatesOrdered: sessionDates,
            attendanceEligibleFrom: trainee.attendanceEligibleFrom,
            excludedSessionKeys: traineeBreakdownExcludedKeysForDeliveryBatch(
              trainingBreakdowns,
              trainee.cohortId,
              trainee.batchId,
            ),
          });
          const attended = attendedKeysByTraineeBatch.get(`${trainee.id.toString()}:${trainee.batchId.toString()}`);
          possible = keys.length;
          present = keys.reduce((count, key) => count + (attended?.has(key) ? 1 : 0), 0);
        }
      }

      const batch = trainee.batchId != null ? batchById.get(trainee.batchId.toString()) : undefined;
      const cohort = trainee.cohortId != null ? cohortById.get(trainee.cohortId.toString()) : undefined;
      out.push({
        traineeId: trainee.id,
        traineeUniqueId: trainee.traineeUniqueId,
        externalBeneficiaryId: trainee.externalBeneficiaryId,
        firstName: trainee.firstName,
        fatherName: trainee.fatherName,
        grandfatherName: trainee.grandfatherName,
        sex: trainee.sex,
        rosterRole: trainee.rosterRole,
        attendanceEligibleFrom: trainee.attendanceEligibleFrom,
        trainingId: training.id,
        trainingTitle: training.title,
        cohortId: trainee.cohortId,
        cohortCode: cohort?.code ?? null,
        cohortName: cohort?.name ?? null,
        batchId: trainee.batchId,
        batchCode: batch?.code ?? null,
        batchName: batch?.name ?? null,
        present,
        possible,
        ratePct: possible > 0 ? Math.round((present / possible) * 10000) / 100 : null,
      });
    }
  }

  return out.sort(
    (a, b) =>
      a.trainingTitle.localeCompare(b.trainingTitle) ||
      String(a.batchCode ?? "").localeCompare(String(b.batchCode ?? "")) ||
      a.traineeUniqueId.localeCompare(b.traineeUniqueId),
  );
}

/** Present/possible for one delivery batch within its cohort; denominator uses the batch timeline. */
export async function computeAttendancePresentPossibleForTrainingScope(
  projectId: bigint,
  trainingId: bigint,
  cohortId: bigint,
  batchId: bigint,
  asOf: Date = new Date(),
): Promise<{ present: number; possible: number }> {
  const holidays = await prisma.projectHoliday.findMany({
    where: { projectId },
    select: { holidayDate: true },
  });
  const holidayDates = holidays.map((h) => h.holidayDate);

  const [tr, batch] = await Promise.all([
    prisma.training.findFirst({
      where: { projectId, id: trainingId },
      select: {
        id: true,
        sessionWeekdays: true,
        trainees: {
          select: { id: true, cohortId: true, batchId: true, rosterRole: true, attendanceEligibleFrom: true },
        },
      },
    }),
    prisma.trainingBatch.findFirst({
      where: { projectId, id: batchId, trainingId },
      select: {
        id: true,
        cohortId: true,
        startDate: true,
        endDate: true,
        timelineAnchorDate: true,
        sessionWeekdays: true,
      },
    }),
  ]);

  if (!tr || !batch || batch.cohortId !== cohortId) return { present: 0, possible: 0 };

  const breakdowns = await prisma.trainingBreakdown.findMany({
    where: { projectId, trainingId: tr.id, status: "approved" },
    select: { cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
  });

  const anchorStart = effectiveStartDate(batch.startDate, batch.timelineAnchorDate);
  const range: TrainingDateRange = {
    startDate: anchorStart,
    endDate: batch.endDate,
    sessionWeekdays: batch.sessionWeekdays ?? tr.sessionWeekdays,
  };

  const scopeTrainees = tr.trainees.filter(
    (t) => rosterRoleCountsAttendanceSlots(t.rosterRole) && t.batchId === batch.id && t.cohortId === cohortId,
  );

  if (scopeTrainees.length === 0) return { present: 0, possible: 0 };

  const exemptDays = await loadAttendanceExemptDaysFromStart(prisma);
  const sessionDates = filterScheduledDatesExcludingExemptPeriod(
    scheduledSessionDates(range, holidayDates, asOf),
    anchorStart,
    exemptDays,
  );
  if (sessionDates.length === 0) return { present: 0, possible: 0 };

  const eligibleKeysByTrainee = new Map<string, Set<string>>();
  let possible = 0;
  for (const trainee of scopeTrainees) {
    const bdExcluded = traineeBreakdownExcludedKeysForDeliveryBatch(breakdowns, trainee.cohortId, batch.id);
    const keys = eligibleSessionKeysForTrainee({
      sessionDatesOrdered: sessionDates,
      attendanceEligibleFrom: trainee.attendanceEligibleFrom,
      excludedSessionKeys: bdExcluded,
    });
    eligibleKeysByTrainee.set(trainee.id.toString(), new Set(keys));
    possible += keys.length;
  }

  const first = sessionDates[0]!;
  const last = sessionDates[sessionDates.length - 1]!;
  const nextDayAfterLast = new Date(last.getTime() + 24 * 60 * 60 * 1000);
  const rows = await prisma.traineeAttendanceDay.findMany({
    where: {
      projectId,
      trainingId: tr.id,
      batchId: batch.id,
      status: { in: ["present", "excused"] },
      sessionDate: { gte: first, lt: nextDayAfterLast },
      traineeId: { in: scopeTrainees.map((x) => x.id) },
    },
    select: { traineeId: true, sessionDate: true },
  });
  const present = rows.filter((r) => {
    const key = sessionDateKey(r.sessionDate);
    const allowed = eligibleKeysByTrainee.get(r.traineeId.toString());
    return Boolean(allowed?.has(key));
  }).length;

  return { present, possible };
}
