import type { Prisma } from "@prisma/client";
import { prisma } from "../prisma.js";
import {
  loadVerificationCandidates,
  summarizeVerificationPopulation,
} from "./verificationPopulationService.js";
import {
  buildVerificationSamplePlan,
  drawVerificationSample,
  DEFAULT_RESERVE_RATIO_PCT,
  DEFAULT_SAMPLING_E,
  DEFAULT_SAMPLING_P,
  DEFAULT_SAMPLING_Z,
  type VerificationSamplingParameters,
} from "./verificationSamplingService.js";

export type VerificationDrawContext = {
  projectId: bigint;
  tpId: bigint;
  indicator: {
    id: bigint;
    code: string;
    thresholdValue: number | null;
    verificationNumeratorVariable: string | null;
    verificationDenominatorVariable: string | null;
    monitoringNumeratorVariable: string | null;
    monitoringDenominatorVariable: string | null;
  };
  denominatorVar: string;
  numeratorVar: string;
  reportType: string;
  isRegistrationBased: boolean;
  stageKey: string | null;
  stageDef: { id: bigint; stageKey: string; label: string } | null;
};

export async function resolveSamplingParameters(
  thresholdValue: number | null,
  overrides?: Partial<VerificationSamplingParameters>,
): Promise<VerificationSamplingParameters> {
  return {
    Z: overrides?.Z ?? DEFAULT_SAMPLING_Z,
    p: overrides?.p ?? DEFAULT_SAMPLING_P,
    e: overrides?.e ?? DEFAULT_SAMPLING_E,
    thresholdPct: overrides?.thresholdPct ?? thresholdValue ?? 90,
    reserveRatioPct: overrides?.reserveRatioPct ?? DEFAULT_RESERVE_RATIO_PCT,
  };
}

export async function buildVerificationSamplePlanPayload(
  projectId: bigint,
  tpId: bigint,
  denominatorIds: bigint[],
  parameters: VerificationSamplingParameters,
  excludeTraineeIds: Set<string> = new Set(),
) {
  const filteredIds = denominatorIds.filter((id) => !excludeTraineeIds.has(id.toString()));
  const { candidates, locationMeta } = await loadVerificationCandidates(prisma, projectId, tpId, filteredIds);
  const population = summarizeVerificationPopulation(candidates, locationMeta);
  const plan = buildVerificationSamplePlan(candidates, parameters);
  return { candidates, population, plan };
}

export async function createVerificationDrawRun(args: {
  projectId: bigint;
  tpId: bigint;
  indicator: VerificationDrawContext["indicator"];
  reportType: string;
  stageKey: string | null;
  stageDef: VerificationDrawContext["stageDef"];
  periodKey: string;
  roundNo: number;
  tier: number;
  parentRunId?: bigint | null;
  denominatorIds: bigint[];
  numeratorSet: Set<string>;
  parameters: VerificationSamplingParameters;
  sampleSeed?: string;
  excludeTraineeIds?: Set<string>;
  preReportDraw?: boolean;
  createdByUserId: bigint;
}) {
  const seed = args.sampleSeed?.trim() || `auto-${Date.now().toString(36)}-${args.createdByUserId.toString()}`;

  // Draw pool is all registered trainees (minus explicit exclusions only).
  // Reserves are drawn from the same pool as primaries — not restricted to completers.
  // Dropout trainees are auto-marked V-NCOMP after the draw, not excluded from the pool.
  const effectiveExclude = args.excludeTraineeIds ?? new Set<string>();

  const { candidates, population, plan } = await buildVerificationSamplePlanPayload(
    args.projectId,
    args.tpId,
    args.denominatorIds,
    args.parameters,
    effectiveExclude,
  );
  if (population.totalEligible <= 0) {
    throw new Error("No eligible trainees found for verification sampling.");
  }

  const draw = drawVerificationSample(candidates, plan, seed, effectiveExclude);
  const primaryCount = draw.subjects.filter((s) => s.subjectRole === "primary").length;
  if (primaryCount <= 0) {
    throw new Error("Sample draw produced zero primary subjects.");
  }

  // Identify dropouts among sampled trainees so they can be auto-marked V-NCOMP.
  const sampledTraineeIds = draw.subjects.map((s) => s.traineeId);
  const dropoutRows = await prisma.traineeOutcome.findMany({
    where: {
      projectId: args.projectId,
      trainingProviderId: args.tpId,
      traineeId: { in: sampledTraineeIds },
      outcomeType: "dropout",
      reportedValue: true,
      ...(args.stageKey ? { meta: { path: "$.stageKey", equals: args.stageKey } as Prisma.JsonFilter } : {}),
    },
    select: { traineeId: true },
    distinct: ["traineeId"],
  });
  const dropoutIds = new Set(dropoutRows.map((r) => r.traineeId.toString()));

  const samplingParameters: Prisma.InputJsonValue = { ...args.parameters };
  const reserveSampleTotal = draw.subjects.filter((s) => s.subjectRole === "reserve").length;
  const run = await prisma.verificationSampleRun.create({
    data: {
      projectId: args.projectId,
      trainingProviderId: args.tpId,
      trainingId: null,
      indicatorId: args.indicator.id,
      indicatorCode: args.indicator.code,
      reportType: args.reportType,
      stageKey: args.stageKey,
      indicatorStageId: args.stageDef?.id ?? null,
      sampleRatioPct: null,
      basePopulationCount: population.totalEligible,
      sampleSize: primaryCount,
      periodKey: args.periodKey,
      roundNo: args.roundNo,
      tier: args.tier,
      parentRunId: args.parentRunId ?? null,
      samplingSeed: seed,
      samplingStrategy: draw.samplingStrategy,
      n0: plan.n0,
      nAfterFpc: plan.nAfterFpc,
      reserveSampleTotal,
      samplingParameters,
      preReportDraw: args.preReportDraw ?? false,
      status: "open",
      drawnAt: new Date(),
      createdByUserId: args.createdByUserId,
      subjects: {
        create: draw.subjects.map((s) => {
          const isDropout = dropoutIds.has(s.traineeId.toString());
          return {
            traineeId: s.traineeId,
            subjectRole: s.subjectRole,
            stratumKey: s.stratumKey,
            reserveOrder: s.reserveOrder,
            tpClaimValue: args.numeratorSet.has(s.traineeId.toString()),
            // Dropouts did not complete — auto-mark as V-NCOMP so no call is needed.
            verificationStatusCode: isDropout ? "V-NCOMP" : undefined,
            verifiedValue: isDropout ? false : undefined,
          };
        }),
      },
    },
    select: { id: true },
  });

  // Create stratum records
  if (draw.strata.length > 0) {
    await prisma.verificationSampleStratum.createMany({
      data: draw.strata.map((s) => ({
        runId: run.id,
        stratumKey: s.stratumKey,
        locationId: s.locationId ? BigInt(s.locationId) : null,
        locationName: s.locationName,
        sexKey: s.sexKey,
        population: s.population,
        primaryDrawn: s.primaryDrawn,
        reserveDrawn: s.reserveDrawn,
      })),
    });
  }

  // Create dropout records
  if (dropoutIds.size > 0) {
    await prisma.verificationSampleRunDropout.createMany({
      data: [...dropoutIds].map((id) => ({
        runId: run.id,
        traineeId: BigInt(id),
      })),
    });
  }

  return { runId: run.id, plan, population, draw, primaryCount };
}

/** Collect trainee IDs already used in tier 1 (+ tier 2 if drawing again). */
export async function collectSampledTraineeIds(runId: bigint): Promise<Set<string>> {
  const run = await prisma.verificationSampleRun.findUnique({
    where: { id: runId },
    select: { id: true, parentRunId: true },
  });
  if (!run) return new Set();
  const runIds = [run.id];
  if (run.parentRunId) runIds.push(run.parentRunId);
  else {
    const children = await prisma.verificationSampleRun.findMany({
      where: { parentRunId: run.id },
      select: { id: true },
    });
    runIds.push(...children.map((c) => c.id));
  }
  const subjects = await prisma.verificationSampleSubject.findMany({
    where: { runId: { in: runIds } },
    select: { traineeId: true },
  });
  return new Set(subjects.map((s) => s.traineeId.toString()));
}

/** Auto-backfill: retroactively update open pre-report runs when outcome reports arrive. */
export async function autoBackfillVerificationRuns(
  projectId: bigint,
  trainingProviderId: bigint,
  reportType: string,
  stageKey: string | null,
): Promise<{ runsProcessed: number; totalDropoutMarked: number; totalClaimUpdated: number }> {
  const openRuns = await prisma.verificationSampleRun.findMany({
    where: {
      projectId,
      trainingProviderId,
      status: "open",
      preReportDraw: true,
      reportType,
    },
    select: { id: true, stageKey: true },
  });
  if (openRuns.length === 0) return { runsProcessed: 0, totalDropoutMarked: 0, totalClaimUpdated: 0 };

  let totalDropoutMarked = 0;
  let totalClaimUpdated = 0;

  for (const openRun of openRuns) {
    const subjects = await prisma.verificationSampleSubject.findMany({
      where: { runId: openRun.id },
      select: { id: true, traineeId: true, subjectRole: true, verificationStatusCode: true, tpClaimValue: true },
    });
    if (subjects.length === 0) continue;

    const subjectTraineeIds = subjects.map((s) => s.traineeId);
    const effectiveStageKey = openRun.stageKey ?? stageKey;

    // Find dropouts
    const dropoutRows = await prisma.traineeOutcome.findMany({
      where: {
        projectId,
        trainingProviderId,
        traineeId: { in: subjectTraineeIds },
        outcomeType: "dropout",
        reportedValue: true,
        ...(effectiveStageKey ? { meta: { path: "$.stageKey", equals: effectiveStageKey } as Prisma.JsonFilter } : {}),
      },
      select: { traineeId: true },
      distinct: ["traineeId"],
    });
    const dropoutIds = new Set(dropoutRows.map((r) => r.traineeId.toString()));

    // Auto-mark dropouts
    for (const s of subjects) {
      if (dropoutIds.has(s.traineeId.toString()) && !s.verificationStatusCode) {
        await prisma.verificationSampleSubject.update({
          where: { id: s.id },
          data: { verificationStatusCode: "V-NCOMP", verifiedValue: false, verifiedAt: new Date(), reviewerNote: "Auto-marked: dropout confirmed by outcome report" },
        });
        totalDropoutMarked++;
      }
    }

    // Update tpClaimValue
    const completionRows = await prisma.traineeOutcome.findMany({
      where: {
        projectId,
        trainingProviderId,
        traineeId: { in: subjectTraineeIds },
        outcomeType: reportType,
        reportedValue: true,
        ...(effectiveStageKey ? { meta: { path: "$.stageKey", equals: effectiveStageKey } as Prisma.JsonFilter } : {}),
      },
      select: { traineeId: true },
      distinct: ["traineeId"],
    });
    const completionIds = new Set(completionRows.map((r) => r.traineeId.toString()));
    for (const s of subjects) {
      const claimedNow = completionIds.has(s.traineeId.toString());
      if (s.tpClaimValue !== claimedNow) {
        await prisma.verificationSampleSubject.update({
          where: { id: s.id },
          data: { tpClaimValue: claimedNow },
        });
        totalClaimUpdated++;
      }
    }

    console.log(`[auto-backfill] Run ${openRun.id}: ${subjects.length} subjects, ${dropoutIds.size} dropout records found, ${completionIds.size} ${reportType} records found (stageKey=${effectiveStageKey ?? "none"})`);

    // Update dropout records table
    if (dropoutIds.size > 0) {
      const existingDropouts = await prisma.verificationSampleRunDropout.findMany({ where: { runId: openRun.id }, select: { traineeId: true } });
      const existingSet = new Set(existingDropouts.map((d) => d.traineeId.toString()));
      const newDropouts = [...dropoutIds].filter((id) => !existingSet.has(id));
      if (newDropouts.length > 0) {
        await prisma.verificationSampleRunDropout.createMany({
          data: newDropouts.map((id) => ({ runId: openRun.id, traineeId: BigInt(id) })),
        });
      }
    }
  }

  return { runsProcessed: openRuns.length, totalDropoutMarked, totalClaimUpdated };
}
