import type { PrismaClient } from "@prisma/client";
import {
  resolveTraineeDeliveryLocationId,
  type TraineeLocationScope,
} from "./providerLocationBreakdown.js";
import { parseDeliveryLocationIds } from "./trainingScopeGuards.js";
import { trackedRosterRoleFilter } from "./traineeRoster.js";

const TRACKED_ROSTER_WHERE = trackedRosterRoleFilter();

export type VerificationSamplingCandidate = {
  traineeId: bigint;
  locationId: bigint | null;
  locationName: string;
  sexKey: "male" | "female" | "unknown";
};

export type VerificationPopulationCell = {
  locationId: string | null;
  locationName: string;
  locationCode: string | null;
  sexKey: "male" | "female" | "unknown";
  count: number;
};

export type VerificationPopulationSummary = {
  totalEligible: number;
  byCell: VerificationPopulationCell[];
  byLocation: Array<{
    locationId: string | null;
    locationName: string;
    locationCode: string | null;
    male: number;
    female: number;
    unknownSex: number;
    total: number;
  }>;
  unknownLocationCount: number;
  unknownSexCount: number;
  warnings: string[];
};

export function normalizeSexKey(raw: string | null | undefined): "male" | "female" | "unknown" {
  const s = (raw ?? "").trim().toLowerCase();
  if (s === "m" || s === "male" || s.startsWith("m ")) return "male";
  if (s === "f" || s === "female" || s.startsWith("f ")) return "female";
  return "unknown";
}

export function buildLocationSexStratumKey(locationId: bigint | null, sexKey: string): string {
  return `location:${locationId?.toString() ?? "none"}|sex:${sexKey}`;
}

async function buildLocationScope(
  prisma: PrismaClient,
  projectId: bigint,
  trainingProviderId: bigint,
): Promise<TraineeLocationScope> {
  const [cohorts, trainings] = await Promise.all([
    prisma.trainingCohort.findMany({
      where: { projectId, trainingProviderId },
      select: { id: true, locationId: true, trainingId: true },
    }),
    prisma.training.findMany({
      where: { projectId, trainingProviderId },
      select: { id: true, deliveryLocationIds: true, locationId: true },
    }),
  ]);
  const cohortLocationById = new Map<string, bigint | null>();
  for (const c of cohorts) cohortLocationById.set(c.id.toString(), c.locationId);
  const trainingDeliverySiteIdsByTrainingId = new Map<string, string[]>();
  for (const tr of trainings) {
    const ids = parseDeliveryLocationIds(tr.deliveryLocationIds);
    const effective =
      ids.length > 0 ? ids.map((id) => id.toString()) : tr.locationId ? [tr.locationId.toString()] : [];
    trainingDeliverySiteIdsByTrainingId.set(tr.id.toString(), effective);
  }
  return { cohortLocationById, trainingDeliverySiteIdsByTrainingId };
}

export async function loadVerificationCandidates(
  prisma: PrismaClient,
  projectId: bigint,
  trainingProviderId: bigint,
  denominatorTraineeIds: bigint[],
): Promise<{ candidates: VerificationSamplingCandidate[]; locationMeta: Map<string, { name: string; code: string | null }> }> {
  const scope = await buildLocationScope(prisma, projectId, trainingProviderId);
  const locations = await prisma.location.findMany({
    where: { isActive: true },
    select: { id: true, name: true, code: true },
  });
  const locationMeta = new Map(locations.map((l) => [l.id.toString(), { name: l.name, code: l.code }]));

  const idSet = new Set(denominatorTraineeIds.map((id) => id.toString()));
  const rows = await prisma.trainee.findMany({
    where: {
      id: { in: denominatorTraineeIds },
      projectId,
      trainingProviderId,
      rosterRole: TRACKED_ROSTER_WHERE,
    },
    select: { id: true, cohortId: true, trainingId: true, locationId: true, sex: true },
  });

  const candidates: VerificationSamplingCandidate[] = [];
  for (const r of rows) {
    if (!idSet.has(r.id.toString())) continue;
    const locId = resolveTraineeDeliveryLocationId(r, scope);
    const meta = locId ? locationMeta.get(locId.toString()) : null;
    candidates.push({
      traineeId: r.id,
      locationId: locId,
      locationName: meta?.name ?? "Unassigned location",
      sexKey: normalizeSexKey(r.sex),
    });
  }
  return { candidates, locationMeta };
}

export function summarizeVerificationPopulation(
  candidates: VerificationSamplingCandidate[],
  locationMeta: Map<string, { name: string; code: string | null }>,
): VerificationPopulationSummary {
  const cellMap = new Map<string, VerificationPopulationCell>();
  let unknownLocationCount = 0;
  let unknownSexCount = 0;
  const warnings: string[] = [];

  for (const c of candidates) {
    if (!c.locationId) unknownLocationCount += 1;
    if (c.sexKey === "unknown") unknownSexCount += 1;
    const key = buildLocationSexStratumKey(c.locationId, c.sexKey);
    const locKey = c.locationId?.toString() ?? "none";
    const meta = c.locationId ? locationMeta.get(locKey) : null;
    const prev = cellMap.get(key) ?? {
      locationId: c.locationId ? locKey : null,
      locationName: meta?.name ?? c.locationName,
      locationCode: meta?.code ?? null,
      sexKey: c.sexKey,
      count: 0,
    };
    prev.count += 1;
    cellMap.set(key, prev);
  }

  if (unknownLocationCount > 0) {
    warnings.push(`${unknownLocationCount} eligible trainee(s) have no assigned delivery location.`);
  }
  if (unknownSexCount > 0) {
    warnings.push(`${unknownSexCount} eligible trainee(s) have unknown sex.`);
  }

  const byCell = Array.from(cellMap.values()).sort(
    (a, b) => a.locationName.localeCompare(b.locationName) || a.sexKey.localeCompare(b.sexKey),
  );

  const byLoc = new Map<
    string,
    { locationId: string | null; locationName: string; locationCode: string | null; male: number; female: number; unknownSex: number }
  >();
  for (const cell of byCell) {
    const locKey = cell.locationId ?? "__none__";
    const row = byLoc.get(locKey) ?? {
      locationId: cell.locationId,
      locationName: cell.locationName,
      locationCode: cell.locationCode,
      male: 0,
      female: 0,
      unknownSex: 0,
    };
    if (cell.sexKey === "male") row.male += cell.count;
    else if (cell.sexKey === "female") row.female += cell.count;
    else row.unknownSex += cell.count;
    byLoc.set(locKey, row);
  }

  return {
    totalEligible: candidates.length,
    byCell,
    byLocation: Array.from(byLoc.values())
      .map((r) => ({ ...r, total: r.male + r.female + r.unknownSex }))
      .sort((a, b) => b.total - a.total || a.locationName.localeCompare(b.locationName)),
    unknownLocationCount,
    unknownSexCount,
    warnings,
  };
}
