// Corrects V1 reports that say "not a dropout" for named trainees who finished below 80 % attendance:
//   npm run correct:low-attendance
// The owner of the data decided this on 2026-12-01 for these eight people, and only for them.
// Nothing is overwritten: each touched report gets a new version, and the version the provider sent stays as "superseded".
import "dotenv/config";
import { auditSystem } from "../src/core/audit/audit.js";
import { execute, insert, insertMany, json, one, pool, query, transaction, type Row } from "../src/core/db/db.js";
import { recomputeKpis } from "../src/modules/indicators/kpi.service.js";
import { refreshClassOutcomes } from "../src/modules/outcomes/index.js";
import { syncOpenRuns } from "../src/modules/verification/index.js";

const CODES = ["PBPS-MC-000073", "PBPS-MC-000185", "PBPS-SCV-000932", "PBPS-SCV-000944", "PBPS-SCV-001189", "PBPS-SCV-001190", "PBPS-SCV-001210", "PBPS-SCV-001223"];
const WHY = "Data correction: attendance ended below 80 %, so the trainee is a dropout and cannot have completed or been certified.";
const people = await query(pool, "SELECT t.id, t.trainee_code AS code, t.project_id AS p, t.class_id AS k, s.system_dropout_final AS final, s.dropout_status AS d FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id WHERE t.trainee_code IN (?)", [CODES]);
// Someone whose attendance is now 80 % or more, or who is already a dropout, is left alone.
const todo = people.filter((x) => x["final"] && x["d"] === "no");
for (const x of people.filter((y) => !todo.includes(y))) console.log(`${x["code"]}: nothing to correct (${x["final"] ? `dropout is already ${x["d"]}` : "attendance is not below 80 %"})`);
for (const c of CODES.filter((x) => !people.some((y) => y["code"] === x))) console.log(`${c}: not in this database`);
for (const classId of new Set(todo.map((x) => String(x["k"])))) {
  const mine = todo.filter((x) => String(x["k"]) === classId), ids = mine.map((x) => String(x["id"])), project = String(mine[0]!["p"]), isMine = (l: Row) => ids.includes(String(l["trainee_id"]));
  const done = await transaction(async (tx) => {
    await one(tx, "SELECT id FROM training_classes WHERE id=? FOR UPDATE", [classId]);
    const touched: string[] = [];
    for (const r of await query(tx, "SELECT * FROM outcome_reports WHERE class_id=? AND status='accepted' ORDER BY id", [classId])) {
      const lines = await query(tx, "SELECT * FROM outcome_report_lines WHERE report_id=? ORDER BY id", [r["id"]]), drop = r["report_type"] === "dropout";
      if (!lines.some((l) => isMine(l) && l["value"] === (drop ? "no" : "yes"))) continue;
      const next = lines.map((l): Row => !isMine(l) ? l : drop ? { ...l, value: "yes", reason_code: "low_attendance_auto" } : { ...l, value: "no", event_date: null, reason_code: "dropout" }), yes = next.filter((l) => l["value"] === "yes").length;
      const v = (await one(tx, "SELECT MAX(version_no)+1 AS n FROM outcome_reports WHERE class_id=? AND report_type=? AND stage_key=?", [classId, r["report_type"], r["stage_key"]]))!;
      const id = await insert(tx, "outcome_reports", { project_id: r["project_id"], provider_id: r["provider_id"], training_id: r["training_id"], site_id: r["site_id"], class_id: classId, report_type: r["report_type"], stage_key: r["stage_key"], version_no: v["n"], status: "accepted", source_filename: r["source_filename"], rows_total: next.length, yes_count: yes, no_count: next.length - yes, na_count: r["na_count"], reason_for_change: WHY, supersedes_report_id: r["id"], submitted_by: r["submitted_by"], submitted_at: String(r["submitted_at"]).slice(0, 23).replace("T", " "), reviewed_at: new Date().toISOString().slice(0, 23).replace("T", " "), is_legacy_partial_roster: r["is_legacy_partial_roster"], review_note: WHY });
      await insertMany(tx, "outcome_report_lines", ["report_id", "trainee_id", "value", "event_date", "reason_code", "details_json", "raw_json", "legacy_status_date"], next.map((l) => [id, l["trainee_id"], l["value"], l["event_date"], l["reason_code"], isMine(l) ? JSON.stringify({ ...json<Row>(l["details_json"], {}), source_type: "data_correction" }) : l["details_json"], l["raw_json"], l["legacy_status_date"]]));
      await execute(tx, "UPDATE outcome_reports SET status='superseded' WHERE id=?", [r["id"]]);
      touched.push(`${r["report_type"]} report ${r["id"]} -> ${id}`);
    }
    await refreshClassOutcomes(tx, classId);
    return { touched, sample: await syncOpenRuns(tx, { classId, trainees: ids }) };
  });
  await auditSystem(project, { module: "outcomes", action: "data_correction", entityType: "training_class", entityId: classId, summary: `${mine.map((x) => x["code"]).join(", ")}: corrected to dropout`, after: { why: WHY, ...done } });
  await recomputeKpis(pool, project);
  console.log(`${mine.map((x) => x["code"]).join(", ")}\n   ${done.touched.join(", ")}\n   samples: ${done.sample.marked} settled as dropout, ${done.sample.claims} claims changed`);
}
// V1 never refreshed a sample that was not marked "before the report" when drawn (Selam's). Every open sample follows the accepted reports.
for (const r of await query(pool, "SELECT id, project_id AS p FROM verification_runs WHERE status NOT IN ('finalised','cancelled')")) {
  const x = await transaction((tx) => syncOpenRuns(tx, { runId: String(r["id"]) }));
  if (x.marked + x.reopened + x.claims) await auditSystem(String(r["p"]), { module: "verification", action: "refreshed_from_reports", entityType: "verification_run", entityId: String(r["id"]), summary: `${x.marked} dropouts settled, ${x.reopened} opened again, ${x.claims} claims updated` });
  console.log(`sample ${r["id"]}: ${x.marked} dropouts settled, ${x.reopened} opened again, ${x.claims} claims updated`);
}
const left = await query(pool, "SELECT t.trainee_code AS code FROM trainee_status s JOIN trainees t ON t.id=s.trainee_id WHERE s.system_dropout_final=1 AND s.roster_status IN ('active','reserve') AND (s.dropout_status='no' OR 'yes' IN (s.completion_status, s.certification_status))");
console.log(left.length ? `STILL CONTRADICTORY, ask the owner of the data: ${left.map((x) => x["code"]).join(", ")}` : "No trainee below 80 % is reported as staying, completing or certified.");
await pool.end();
process.exitCode = left.length ? 1 : 0;
