// Compares V2's stored numbers with the output of V1's own calculation code (JSON written by the V1 run).
import { readFileSync } from "node:fs";
import { pool, query } from "../src/core/db/db.js";

const v1 = JSON.parse(readFileSync(process.argv[2]!, "utf8")) as { kpis: { indicatorCode: string; tpId: string; claimed: number }[]; drop: Record<string, number | string | boolean>[] };
const snap = await query(pool, "SELECT indicator_code AS c, provider_key AS p, value, layer FROM kpi_snapshots WHERE layer='monitoring' AND as_of_date=(SELECT MAX(as_of_date) FROM kpi_snapshots)");
let bad = 0, kpis = 0, people = 0, fields = 0;
for (const k of v1.kpis) {
  const s = snap.find((x) => x["c"] === k.indicatorCode && String(x["p"]) === (k.tpId === "PROJECT" ? "0" : k.tpId));
  kpis++;
  if (!s || Number(s["value"] ?? 0) !== k.claimed) { bad++; console.log("KPI DIFFERS", k.indicatorCode, k.tpId, "V1", k.claimed, "V2", s?.["value"]); }
}
const status = new Map((await query(pool, "SELECT trainee_id, att_sessions_to_date AS pd, att_present_to_date AS prd, att_possible_final AS pf, att_rate_to_date AS r, att_rate_final AS rf, att_max_reachable AS mr, system_dropout_risk AS risk, system_dropout_final AS fin, dropout_status AS d, att_dispute AS dis FROM trainee_status")).map((s) => [String(s["trainee_id"]), s]));
for (const p of v1.drop) {
  const s = status.get(String(p["traineeId"]));
  people++;
  const pairs: [string, unknown, unknown][] = s ? [["possibleToDate", p["possibleToDate"], s["pd"]], ["presentToDate", p["presentToDate"], s["prd"]], ["possibleFinal", p["possibleFinal"], s["pf"]], ["pctToDate", p["attendancePctToDate"], s["r"] ?? 0], ["pctFinal", s["rf"] === null ? null : p["attendancePctFinal"], s["rf"]], ["maxRecoverable", p["maxRecoverablePct"], s["mr"] ?? 0],
    ["risk", p["systemDropoutRisk"], Boolean(s["risk"])], ["final", p["systemDropoutFinal"], Boolean(s["fin"])], ["tpReported", p["tpReportedDropout"], s["d"] === "yes"], ["disputed", p["disputedSystemFinal"], Boolean(s["dis"])]] : [["row", 1, undefined]];
  for (const [name, a, b] of pairs) { fields++; if (a !== b) { bad++; if (bad < 25) console.log("TRAINEE DIFFERS", p["traineeUniqueId"], name, "V1", a, "V2", b); } }
}
console.log(`${kpis} KPI values and ${people} trainees (${fields} figures) compared with V1's own code: ${bad} differences`);
await pool.end();
if (bad || !kpis || !people) process.exitCode = 1;
