// Compares V1's endpoints (read from its source) with the V1 endpoints that V2 routes say they replace.
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { buildApp } from "../src/app/buildApp.js";
import { pool } from "../src/core/db/db.js";
import { scanV1 } from "./scan-v1.js";

const { endpoints, unparsed } = scanV1();
const covered = new Map<string, string>();
const app = await buildApp({ logger: false, onRoute: (r) => { if (r.method !== "HEAD") for (const key of r.config?.v1 ?? []) covered.set(key, `${String(r.method)} ${r.url}`); } });
await app.ready();

const known = new Set(endpoints.map((e) => e.key));
const unknown = [...covered.keys()].filter((k) => !known.has(k));
const distinct = [...known];
/** Not rebuilt on purpose (client decision of 2026-12-01): no withdrawal, no replacement, reserves are equal to everyone else. */
const REMOVED = ["POST /api/projects/:projectId/trainees/replacement", "DELETE /api/projects/:projectId/trainees/:traineeId"];
const missing = distinct.filter((k) => !covered.has(k) && !REMOVED.includes(k));
const rows = endpoints.map((e) => `| ${covered.has(e.key) ? "done" : "**missing**"} | \`${e.key}\` | ${e.file}:${e.line} | ${covered.get(e.key) ?? ""} |`);
const out = join(import.meta.dirname, "PARITY.md");
mkdirSync(import.meta.dirname, { recursive: true });
writeFileSync(out, `# V1 to V2 parity (generated by npm run parity)\n\n${distinct.length - missing.length} of ${distinct.length} V1 endpoints replaced.\n\n| Status | V1 endpoint | V1 source | V2 route |\n|---|---|---|---|\n${rows.join("\n")}\n`);
console.log(`V1 route declarations: ${endpoints.length}, distinct endpoints: ${distinct.length}, replaced: ${distinct.length - missing.length}, missing: ${missing.length}`);
for (const u of unparsed) console.log("COULD NOT READ", u);
for (const u of unknown) console.log("V2 claims a V1 endpoint that does not exist:", u);
await app.close();
await pool.end();
if (unparsed.length || unknown.length || (process.argv.includes("--release") && missing.length)) process.exitCode = 1;
