import { prisma } from "../src/prisma.js";
import { computeDropoutProjections } from "../src/services/dropoutProtocol.js";

/** READ-ONLY: reports every trainee the system flags as a dropout (attendance < 80% after
 *  training ended) whose TP dropout row is N (disputed) or missing, plus report/verification
 *  inventory. Nothing here writes. */

async function main() {
  const projects = await prisma.project.findMany({ select: { id: true, projectCode: true } });
  console.log(`Projects: ${projects.length}\n`);

  const rows: Array<{
    project: string;
    provider: string;
    providerName: string;
    training: string;
    uid: string;
    name: string;
    attPct: number;
    status: string;
  }> = [];

  for (const project of projects) {
    const trainings = await prisma.training.findMany({
      where: { projectId: project.id },
      select: { id: true, trainingProviderId: true, title: true, endDate: true },
    });
    for (const training of trainings) {
      const projections = await computeDropoutProjections({
        projectId: project.id,
        trainingId: training.id,
      });
      const flagged = projections.filter((p) => p.systemDropoutFinal);
      if (flagged.length) {
        const provider = await prisma.trainingProvider.findUnique({
          where: { id: training.trainingProviderId },
          select: { name: true },
        });
        const tpRows = await prisma.traineeOutcome.findMany({
          where: {
            projectId: project.id,
            trainingId: training.id,
            outcomeType: "dropout",
            traineeId: { in: flagged.map((f) => f.traineeId) },
            reportedValue: { not: null },
          },
          select: { traineeId: true, reportedValue: true, meta: true, reportBatchId: true },
        });
        const byTrainee = new Map<string, Array<{ v: boolean; batch: string | null; dispute: string | null }>>();
        for (const r of tpRows) {
          const meta = (r.meta ?? {}) as Record<string, unknown>;
          const arr = byTrainee.get(r.traineeId.toString()) ?? [];
          arr.push({
            v: r.reportedValue === true,
            batch: r.reportBatchId?.toString() ?? null,
            dispute: typeof meta.dropout_dispute === "string" ? meta.dropout_dispute : null,
          });
          byTrainee.set(r.traineeId.toString(), arr);
        }
        for (const f of flagged) {
          const submitted = byTrainee.get(f.traineeId.toString()) ?? [];
          const hasY = submitted.some((s) => s.v);
          const hasN = submitted.some((s) => !s.v);
          rows.push({
            project: project.projectCode,
            provider: training.trainingProviderId.toString(),
            providerName: provider?.name ?? "?",
            training: `${training.id} ${training.title}`,
            uid: f.traineeUniqueId,
            name: f.traineeName,
            attPct: f.attendancePctFinal,
            status: hasY
              ? "OK - reported Y"
              : hasN
                ? `DISPUTED (dropout=no, batch ${submitted.find((s) => !s.v)?.batch ?? "?"})`
                : "MISSING (no TP dropout row at all)",
          });
        }
      }
    }
  }

  console.log(`=== System-final trainees (attendance < 80%, training ended): ${rows.length} ===\n`);
  const grouped = new Map<string, typeof rows>();
  for (const r of rows) {
    const key = `${r.project} | TP ${r.provider} ${r.providerName} | ${r.training}`;
    const arr = grouped.get(key) ?? [];
    arr.push(r);
    grouped.set(key, arr);
  }
  for (const [key, arr] of grouped) {
    const bad = arr.filter((r) => !r.status.startsWith("OK"));
    console.log(`${key}`);
    console.log(`  total system-final: ${arr.length}, needs action: ${bad.length}`);
    for (const r of bad) console.log(`    ${r.uid}  ${r.name}  att=${r.attPct}%  ${r.status}`);
    console.log("");
  }
  const badTotal = rows.filter((r) => !r.status.startsWith("OK")).length;
  console.log(`TOTAL needing action: ${badTotal} / ${rows.length}\n`);

  console.log("=== Outcome report batches by type/status ===");
  const batches = await prisma.outcomeReportBatch.groupBy({
    by: ["reportType", "status"],
    _count: true,
    where: projects.length ? { projectId: { in: projects.map((p) => p.id) } } : {},
  });
  for (const b of batches) console.log(`  ${b.reportType.padEnd(22)} ${b.status.padEnd(12)} ${b._count}`);

  console.log("\n=== Verification sample runs ===");
  const runs = await prisma.verificationSampleRun.groupBy({
    by: ["status", "reportType"],
    _count: true,
  });
  for (const r of runs) console.log(`  ${r.reportType.padEnd(24)} ${r.status.padEnd(10)} ${r._count}`);

  console.log("\n=== Verification rows touched by auto-dropout ===");
  const autoDropout = await prisma.verificationSampleSubject.count({
    where: { verificationStatusCode: "V-NCOMP", reviewerNote: { contains: "Auto-marked: dropout" } },
  });
  const ncomp = await prisma.verificationSampleSubject.count({ where: { verificationStatusCode: "V-NCOMP" } });
  console.log(`  auto-marked dropout (undoable): ${autoDropout}`);
  console.log(`  all V-NCOMP rows:              ${ncomp}`);
  const closedAuto = await prisma.verificationSampleSubject.count({
    where: {
      verificationStatusCode: "V-NCOMP",
      reviewerNote: { contains: "Auto-marked: dropout" },
      run: { status: { not: "open" } },
    },
  });
  console.log(`  auto-marked but run NOT open (will NOT be undone): ${closedAuto}`);

  console.log("\n=== Existing disputes (meta.dropout_dispute) ===");
  const disputed = await prisma.traineeOutcome.count({
    where: { meta: { path: "$.dropout_dispute", equals: "system_final_disputed" } as never },
  });
  console.log(`  rows tagged system_final_disputed: ${disputed}`);
}

main()
  .then(() => process.exit(0))
  .catch((e) => {
    console.error(e);
    process.exit(1);
  });
