import { createHash } from "node:crypto";
import type { VerificationSamplingCandidate } from "./verificationPopulationService.js";
import { buildLocationSexStratumKey } from "./verificationPopulationService.js";

export const DEFAULT_SAMPLING_Z = 1.96;
export const DEFAULT_SAMPLING_P = 0.5;
export const DEFAULT_SAMPLING_E = 0.05;
export const DEFAULT_RESERVE_RATIO_PCT = 15;
/** Protocol Section 5.4 applies a ~10 % non-response inflation (÷ 0.9). */
export const DEFAULT_NON_RESPONSE_FACTOR = 0.9;

export type VerificationSamplingParameters = {
  Z: number;
  p: number;
  e: number;
  thresholdPct: number;
  reserveRatioPct: number;
  /** Fraction of the FPC sample expected to be reachable (default 0.9 = 10 % non-response). */
  nonResponseFactor?: number;
};

export type VerificationStratumPlan = {
  stratumKey: string;
  locationId: string | null;
  locationName: string;
  sexKey: string;
  population: number;
  primarySample: number;
  reserveSample: number;
};

export type VerificationSamplePlan = {
  parameters: VerificationSamplingParameters;
  totalPopulation: number;
  n0: number;
  nAfterFpc: number;
  primarySampleTotal: number;
  reserveSampleTotal: number;
  strata: VerificationStratumPlan[];
  warnings: string[];
};

export type VerificationDrawnSubject = {
  traineeId: bigint;
  subjectRole: "primary" | "reserve";
  stratumKey: string;
  reserveOrder: number | null;
};

export type VerificationDrawResult = {
  plan: VerificationSamplePlan;
  subjects: VerificationDrawnSubject[];
  seed: string;
  strata: Array<{
    stratumKey: string;
    locationId: string | null;
    locationName: string;
    sexKey: string;
    population: number;
    primaryDrawn: number;
    reserveDrawn: number;
  }>;
  samplingStrategy: string;
};

function makeSeededRng(seed: string) {
  const hash = createHash("sha256").update(seed).digest();
  let state = hash.readUInt32LE(0) || 1;
  return () => {
    state |= 0;
    state = (state + 0x6d2b79f5) | 0;
    let t = Math.imul(state ^ (state >>> 15), 1 | state);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

function seededShuffle<T>(arr: T[], seed: string): T[] {
  const out = [...arr];
  const rand = makeSeededRng(seed);
  for (let i = out.length - 1; i > 0; i--) {
    const j = Math.floor(rand() * (i + 1));
    const tmp = out[i];
    out[i] = out[j]!;
    out[j] = tmp!;
  }
  return out;
}

export function computeSampleSizeAfterFpc(N: number, params: Pick<VerificationSamplingParameters, "Z" | "p" | "e">): {
  n0: number;
  nAfterFpc: number;
} {
  if (N <= 0) return { n0: 0, nAfterFpc: 0 };
  const { Z, p, e } = params;
  const n0 = Math.ceil((Z * Z * p * (1 - p)) / (e * e));
  const nAfterFpc = Math.ceil(n0 / (1 + (n0 - 1) / N));
  return { n0, nAfterFpc: Math.min(nAfterFpc, N) };
}

export function allocateByLargestRemainder(
  groupSizes: Array<{ key: string; count: number }>,
  totalSample: number,
  minPerGroup: boolean,
): Map<string, number> {
  const total = groupSizes.reduce((s, g) => s + g.count, 0);
  if (total <= 0 || totalSample <= 0) return new Map<string, number>();
  const alloc = new Map<string, number>();
  const remainders: Array<{ key: string; remainder: number }> = [];
  let assigned = 0;
  const minBase = minPerGroup && totalSample >= groupSizes.length ? 1 : 0;
  for (const g of groupSizes) {
    const remainingPool = Math.max(0, g.count - minBase);
    const remainingTarget = Math.max(0, totalSample - minBase * groupSizes.length);
    const exact = total > 0 ? (remainingPool / Math.max(1, total - minBase * groupSizes.length)) * remainingTarget : 0;
    const base = minBase + Math.floor(exact);
    alloc.set(g.key, Math.min(g.count, base));
    assigned += Math.min(g.count, base);
    remainders.push({ key: g.key, remainder: exact - Math.floor(exact) });
  }
  let left = totalSample - assigned;
  remainders.sort((a, b) => b.remainder - a.remainder || a.key.localeCompare(b.key));
  for (const r of remainders) {
    if (left <= 0) break;
    const current = alloc.get(r.key) ?? 0;
    const cap = groupSizes.find((g) => g.key === r.key)?.count ?? current;
    if (current < cap) {
      alloc.set(r.key, current + 1);
      left -= 1;
    }
  }
  return alloc;
}

export function buildVerificationSamplePlan(
  candidates: VerificationSamplingCandidate[],
  parameters: VerificationSamplingParameters,
): VerificationSamplePlan {
  const warnings: string[] = [];
  const N = candidates.length;
  const { n0, nAfterFpc: nAfterFpcRaw } = computeSampleSizeAfterFpc(N, parameters);
  const nonResponseFactor = parameters.nonResponseFactor ?? DEFAULT_NON_RESPONSE_FACTOR;
  const nAfterFpc = Math.max(nAfterFpcRaw, Math.ceil(nAfterFpcRaw / nonResponseFactor));

  const grouped = new Map<string, VerificationSamplingCandidate[]>();
  for (const c of candidates) {
    const key = buildLocationSexStratumKey(c.locationId, c.sexKey);
    const arr = grouped.get(key) ?? [];
    arr.push(c);
    grouped.set(key, arr);
  }

  const groupSizes = Array.from(grouped.entries()).map(([key, arr]) => ({ key, count: arr.length }));
  const primaryAlloc = allocateByLargestRemainder(groupSizes, nAfterFpc, true);

  const strata: VerificationStratumPlan[] = [];
  let primarySampleTotal = 0;
  let reserveSampleTotal = 0;

  for (const [key, arr] of grouped.entries()) {
    const primarySample = Math.max(0, Math.min(arr.length, primaryAlloc.get(key) ?? 0));
    const reserveSample = Math.min(
      Math.max(0, arr.length - primarySample),
      Math.ceil(primarySample * (parameters.reserveRatioPct / 100)),
    );
    const sample = arr[0]!;
    strata.push({
      stratumKey: key,
      locationId: sample.locationId?.toString() ?? null,
      locationName: sample.locationName,
      sexKey: sample.sexKey,
      population: arr.length,
      primarySample,
      reserveSample,
    });
    primarySampleTotal += primarySample;
    reserveSampleTotal += reserveSample;
  }

  strata.sort((a, b) => a.locationName.localeCompare(b.locationName) || a.sexKey.localeCompare(b.sexKey));

  if (primarySampleTotal === 0 && N > 0) {
    warnings.push("Sample allocation produced zero primary subjects.");
  }

  return {
    parameters,
    totalPopulation: N,
    n0,
    nAfterFpc,
    primarySampleTotal,
    reserveSampleTotal,
    strata,
    warnings,
  };
}

export function drawVerificationSample(
  candidates: VerificationSamplingCandidate[],
  plan: VerificationSamplePlan,
  seed: string,
  excludeTraineeIds: Set<string> = new Set(),
): VerificationDrawResult {
  const eligible = candidates.filter((c) => !excludeTraineeIds.has(c.traineeId.toString()));
  const grouped = new Map<string, VerificationSamplingCandidate[]>();
  for (const c of eligible) {
    const key = buildLocationSexStratumKey(c.locationId, c.sexKey);
    const arr = grouped.get(key) ?? [];
    arr.push(c);
    grouped.set(key, arr);
  }

  const subjects: VerificationDrawnSubject[] = [];
  const stratumSummary: Array<{
    key: string;
    population: number;
    primaryDrawn: number;
    reserveDrawn: number;
  }> = [];

  for (const stratum of plan.strata) {
    const pool = grouped.get(stratum.stratumKey) ?? [];
    const shuffled = seededShuffle(
      pool.map((x) => x.traineeId).sort((a, b) => (a < b ? -1 : 1)),
      `${seed}|${stratum.stratumKey}`,
    );
    const primaryIds = shuffled.slice(0, Math.min(stratum.primarySample, shuffled.length));
    const remaining = shuffled.filter((id) => !primaryIds.some((p) => p === id));
    // Reserves are drawn from the same eligible pool as primaries (all registered trainees minus exclusions).
    const reserveIds = remaining.slice(0, Math.min(stratum.reserveSample, remaining.length));

    for (const traineeId of primaryIds) {
      subjects.push({
        traineeId,
        subjectRole: "primary",
        stratumKey: stratum.stratumKey,
        reserveOrder: null,
      });
    }
    reserveIds.forEach((traineeId, idx) => {
      subjects.push({
        traineeId,
        subjectRole: "reserve",
        stratumKey: stratum.stratumKey,
        reserveOrder: idx + 1,
      });
    });

    stratumSummary.push({
      key: stratum.stratumKey,
      population: stratum.population,
      primaryDrawn: primaryIds.length,
      reserveDrawn: reserveIds.length,
    });
  }

  // Build a lookup from plan.strata (which already has locationId, locationName, sexKey)
  const planStratumLookup = new Map(
    plan.strata.map((ps) => [
      ps.stratumKey,
      { locationId: ps.locationId, locationName: ps.locationName, sexKey: ps.sexKey },
    ]),
  );
  const strata = stratumSummary
    .sort((a, b) => a.key.localeCompare(b.key))
    .map((s) => {
      const planInfo = planStratumLookup.get(s.key);
      return {
        stratumKey: s.key,
        locationId: planInfo?.locationId ?? null,
        locationName: planInfo?.locationName ?? "Unknown",
        sexKey: planInfo?.sexKey ?? "unknown",
        population: s.population,
        primaryDrawn: s.primaryDrawn,
        reserveDrawn: s.reserveDrawn,
      };
    });

  return { plan, subjects, seed, strata, samplingStrategy: "icos_location_sex_v1" };
}
