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 { rosterRoleCountsDropout } from "./traineeRoster.js";

export type DropoutProjectionRow = {
  traineeId: bigint;
  traineeUniqueId: string;
  traineeName: string;
  trainingProviderId: bigint;
  trainingId: bigint;
  cohortId: bigint | null;
  possibleToDate: number;
  presentToDate: number;
  attendancePctToDate: number;
  possibleFinal: number;
  presentFinal: number;
  attendancePctFinal: number;
  maxRecoverablePct: number;
  systemDropoutRisk: boolean;
  systemDropoutFinal: boolean;
  tpReportedDropout: boolean;
  /** TP reported N for a system-final low-attendance trainee (attendance data disputed). */
  disputedSystemFinal: boolean;
  effectiveDropout: boolean;
  reasonCode: string | null;
  reasonSource: "tp_reported" | "system_auto" | null;
  missingInTpReport: boolean;
};

type ScopeArgs = {
  projectId: bigint;
  trainingProviderId?: bigint | null;
  trainingId?: bigint | null;
  cohortId?: bigint | null;
  now?: Date;
  traineeId?: bigint | null;
};

function dateOnlyUtc(d: Date) {
  return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
}

function pct(n: number, d: number) {
  if (d <= 0) return 0;
  return Math.round((n / d) * 10000) / 100;
}

function normReason(raw: string | null | undefined): string | null {
  const v = String(raw ?? "").trim().toLowerCase();
  if (!v) return null;
  if (v.includes("voluntary")) return "voluntary_withdrawal";
  if (v.includes("dismiss")) return "dismissal";
  if (v.includes("health")) return "health";
  if (v.includes("economic") || v.includes("financial")) return "economic";
  if (v.includes("migration") || v.includes("relocat")) return "migration";
  if (v.includes("attendance") || v.includes("absen")) return "low_attendance_auto";
  if (v.includes("withdraw")) return "voluntary_withdrawal";
  return "other";
}

function buildName(firstName: string, fatherName: string | null, grandfatherName: string | null) {
  return [firstName, fatherName ?? "", grandfatherName ?? ""].join(" ").replace(/\s+/g, " ").trim();
}

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

function breakdownAppliesToDeliveryBatch(
  b: { cohortId: bigint | null; batchId: bigint | null },
  traineeCohortId: bigint | null,
  deliveryBatchId: bigint,
): boolean {
  if (b.batchId != null) return b.batchId === deliveryBatchId;
  if (b.cohortId != null) return b.cohortId === traineeCohortId;
  return true;
}

export async function computeDropoutProjections(args: ScopeArgs): Promise<DropoutProjectionRow[]> {
  const today = dateOnlyUtc(args.now ?? new Date());
  const trainings = await prisma.training.findMany({
    where: {
      projectId: args.projectId,
      ...(args.trainingProviderId ? { trainingProviderId: args.trainingProviderId } : {}),
      ...(args.trainingId ? { id: args.trainingId } : {}),
    },
    select: {
      id: true,
      projectId: true,
      trainingProviderId: true,
      startDate: true,
      endDate: true,
      timelineAnchorDate: true,
      sessionWeekdays: true,
      cohorts: {
        select: { id: true, startDate: true, endDate: true, timelineAnchorDate: true, sessionWeekdays: true },
      },
      trainees: {
        where: {
          ...(args.cohortId ? { cohortId: args.cohortId } : {}),
          ...(args.traineeId ? { id: args.traineeId } : {}),
        },
        select: {
          id: true,
          traineeUniqueId: true,
          firstName: true,
          fatherName: true,
          grandfatherName: true,
          cohortId: true,
          batchId: true,
          rosterRole: true,
          attendanceEligibleFrom: true,
        },
      },
    },
    orderBy: { id: "asc" },
  });
  if (!trainings.length) return [];
  const holidays = await prisma.projectHoliday.findMany({
    where: { projectId: args.projectId },
    select: { holidayDate: true },
  });
  const holidayDates = holidays.map((h) => h.holidayDate);
  const exemptDays = await loadAttendanceExemptDaysFromStart(prisma);
  const trainingIds = trainings.map((t) => t.id);
  const breakdowns = await prisma.trainingBreakdown.findMany({
    where: {
      projectId: args.projectId,
      trainingId: { in: trainingIds },
      status: "approved",
    },
    select: { trainingId: true, cohortId: true, batchId: true, breakStartDate: true, breakEndDate: true },
  });
  const traineeIds = trainings.flatMap((t) => t.trainees.map((x) => x.id));
  if (!traineeIds.length) return [];
  const attendanceRows = await prisma.traineeAttendanceDay.findMany({
    where: {
      projectId: args.projectId,
      trainingId: { in: trainingIds },
      traineeId: { in: traineeIds },
      status: { in: ["present", "excused"] },
    },
    select: { traineeId: true, trainingId: true, batchId: true, sessionDate: true },
  });
  const dropoutRows = await prisma.traineeOutcome.findMany({
    where: {
      projectId: args.projectId,
      trainingId: { in: trainingIds },
      traineeId: { in: traineeIds },
      outcomeType: "dropout",
      reportedValue: { not: null },
    },
    orderBy: { id: "desc" },
    select: { traineeId: true, reportedValue: true, meta: true },
  });
  const enrollmentRows = await prisma.traineeEnrollment.findMany({
    where: {
      projectId: args.projectId,
      trainingId: { in: trainingIds },
      traineeId: { in: traineeIds },
    },
    select: { trainingId: true, traineeId: true, enrollmentStatus: true },
  });

  const presentMap = new Map<string, Set<string>>();
  for (const row of attendanceRows) {
    const k = `${row.trainingId.toString()}:${row.traineeId.toString()}:${row.batchId.toString()}`;
    const set = presentMap.get(k) ?? new Set<string>();
    set.add(sessionDateKey(row.sessionDate));
    presentMap.set(k, set);
  }
  const tpDropoutMap = new Map<string, string | null>();
  // Trainees with an explicit TP-reported dropout=false row — used to detect disputes of the
  // system-final verdict. A positive Y row anywhere always wins over an N.
  const tpExplicitNoSet = new Set<string>();
  for (const row of dropoutRows) {
    const k = row.traineeId.toString();
    const meta = (row.meta ?? {}) as Record<string, unknown>;
    const reason = typeof meta.dropout_reason === "string" ? meta.dropout_reason : null;
    if (row.reportedValue === true) {
      if (!tpDropoutMap.has(k)) tpDropoutMap.set(k, normReason(reason));
    } else if (row.reportedValue === false) {
      tpExplicitNoSet.add(k);
    }
  }
  const enrollmentMap = new Map<string, string>();
  for (const row of enrollmentRows) {
    enrollmentMap.set(`${row.trainingId.toString()}:${row.traineeId.toString()}`, row.enrollmentStatus);
  }

  const allTraineeBatchIds = [
    ...new Set(
      trainings.flatMap((t) => t.trainees.map((x) => x.batchId).filter((b): b is bigint => b != null)),
    ),
  ];
  const allBatches =
    allTraineeBatchIds.length > 0
      ? await prisma.trainingBatch.findMany({
          where: { projectId: args.projectId, trainingId: { in: trainingIds }, id: { in: allTraineeBatchIds } },
          select: {
            id: true,
            trainingId: true,
            startDate: true,
            endDate: true,
            timelineAnchorDate: true,
            sessionWeekdays: true,
          },
        })
      : [];
  const batchesByTraining = new Map<string, Map<string, (typeof allBatches)[0]>>();
  for (const b of allBatches) {
    const tk = b.trainingId.toString();
    const m = batchesByTraining.get(tk) ?? new Map();
    m.set(b.id.toString(), b);
    batchesByTraining.set(tk, m);
  }

  const rows: DropoutProjectionRow[] = [];
  for (const tr of trainings) {
    const batchRangeById = batchesByTraining.get(tr.id.toString()) ?? new Map();
    const byTrainingBreakdowns = breakdowns.filter((b) => b.trainingId === tr.id);
    for (const trainee of tr.trainees) {
      if (!rosterRoleCountsDropout(trainee.rosterRole)) continue;
      if (!trainee.batchId) continue;
      const batchScoped = batchRangeById.get(trainee.batchId.toString());
      if (!batchScoped) continue;
      const scopedStart = effectiveStartDate(batchScoped.startDate, batchScoped.timelineAnchorDate);
      const tRange: TrainingDateRange = {
        startDate: scopedStart,
        endDate: batchScoped.endDate,
        sessionWeekdays: batchScoped.sessionWeekdays ?? tr.sessionWeekdays,
      };
      const allSessionDates = filterScheduledDatesExcludingExemptPeriod(
        scheduledSessionDates(tRange, holidayDates, batchScoped.endDate),
        scopedStart,
        exemptDays,
      );
      const toDateSessions = filterScheduledDatesExcludingExemptPeriod(
        scheduledSessionDates(tRange, holidayDates, today),
        scopedStart,
        exemptDays,
      );
      const trainingEnded = today > dateOnlyUtc(batchScoped.endDate);
      const excludedFinal = traineeBreakdownExcludedKeysForDeliveryBatch(byTrainingBreakdowns, trainee.cohortId, trainee.batchId);
      const excludedToDate = new Set<string>();
      for (const b of byTrainingBreakdowns) {
        if (!breakdownAppliesToDeliveryBatch(b, trainee.cohortId, trainee.batchId)) continue;
        for (
          let d = dateOnlyUtc(b.breakStartDate);
          d <= dateOnlyUtc(b.breakEndDate);
          d.setUTCDate(d.getUTCDate() + 1)
        ) {
          if (d <= today) excludedToDate.add(sessionDateKey(d));
        }
      }
      const keysFinal = eligibleSessionKeysForTrainee({
        sessionDatesOrdered: allSessionDates,
        attendanceEligibleFrom: trainee.attendanceEligibleFrom,
        excludedSessionKeys: excludedFinal,
      });
      const keysToDate = eligibleSessionKeysForTrainee({
        sessionDatesOrdered: toDateSessions,
        attendanceEligibleFrom: trainee.attendanceEligibleFrom,
        excludedSessionKeys: excludedToDate,
      });
      const possibleFinal = keysFinal.length;
      const possibleToDate = keysToDate.length;
      const mapKey = `${tr.id.toString()}:${trainee.id.toString()}:${trainee.batchId.toString()}`;
      const presentSet = presentMap.get(mapKey) ?? new Set<string>();
      const presentFinal = keysFinal.filter((k) => presentSet.has(k)).length;
      const presentToDate = keysToDate.filter((k) => presentSet.has(k)).length;
      const attendancePctFinal = pct(presentFinal, possibleFinal);
      const attendancePctToDate = pct(presentToDate, possibleToDate);
      const remainingSlots = Math.max(0, possibleFinal - possibleToDate);
      const maxRecoverablePct = pct(presentToDate + remainingSlots, possibleFinal || 0);
      const transferOut = Boolean(
        (enrollmentMap.get(`${tr.id.toString()}:${trainee.id.toString()}`) ?? "").toLowerCase().includes("transfer"),
      );
      const systemDropoutFinal = Boolean(!transferOut && trainingEnded && possibleFinal > 0 && attendancePctFinal < 80);
      const missPctToDate = 100 - attendancePctToDate;
      const systemDropoutRisk = !systemDropoutFinal && possibleToDate > 0 && (missPctToDate >= 15 || maxRecoverablePct < 80);
      const tpReportedDropout = tpDropoutMap.has(trainee.id.toString());
      // A TP-reported N (explicit dropout=false row) disputes the system verdict: the TP claims
      // the attendance data is wrong. The system-final flag stays on record (and counts toward
      // the KPI rate until M&E resolves the dispute), but the row is flagged for review.
      const disputedSystemFinal = Boolean(systemDropoutFinal && !tpReportedDropout && tpExplicitNoSet.has(trainee.id.toString()));
      const effectiveDropout = tpReportedDropout || systemDropoutFinal;
      const reasonCode = tpReportedDropout
        ? (tpDropoutMap.get(trainee.id.toString()) ?? "other")
        : systemDropoutFinal
          ? "low_attendance_auto"
          : null;
      const reasonSource: "tp_reported" | "system_auto" | null = tpReportedDropout
        ? "tp_reported"
        : systemDropoutFinal
          ? "system_auto"
          : null;
      rows.push({
        traineeId: trainee.id,
        traineeUniqueId: trainee.traineeUniqueId,
        traineeName: buildName(trainee.firstName, trainee.fatherName, trainee.grandfatherName),
        trainingProviderId: tr.trainingProviderId,
        trainingId: tr.id,
        cohortId: trainee.cohortId ?? null,
        possibleToDate,
        presentToDate,
        attendancePctToDate,
        possibleFinal,
        presentFinal,
        attendancePctFinal,
        maxRecoverablePct,
        systemDropoutRisk,
        systemDropoutFinal,
        tpReportedDropout,
        disputedSystemFinal,
        effectiveDropout,
        reasonCode,
        reasonSource,
        missingInTpReport: systemDropoutFinal && !tpReportedDropout && !disputedSystemFinal,
      });
    }
  }
  return rows;
}

export function summarizeReasonShares(
  rows: Array<DropoutProjectionRow & { countsTowardKpiRate?: boolean }>,
  opts?: { forKpiRate?: boolean },
) {
  const totals = new Map<string, number>();
  const effective = rows.filter((r) =>
    opts?.forKpiRate ? Boolean(r.countsTowardKpiRate) : r.effectiveDropout,
  );
  for (const row of effective) {
    const key = row.reasonCode ?? "other";
    totals.set(key, (totals.get(key) ?? 0) + 1);
  }
  const total = effective.length;
  return {
    total,
    shares: [...totals.entries()].map(([reasonCode, count]) => ({
      reasonCode,
      count,
      sharePct: total > 0 ? Math.round((count / total) * 10000) / 100 : 0,
    })),
  };
}

