import { audit } from "../../core/audit/audit.js";
import { execute, insert, json, one, pool, query, transaction, type Db, type Row } from "../../core/db/db.js";
import { conflict, invalid, notFound, type Ctx } from "../../core/http/route.js";
import { defineJob, enqueue } from "../../core/jobs/jobs.js";
import { showPhone } from "../../shared/phone.js";
import { traineeRows } from "../registration/index.js";
import { DUPLICATE_ALGORITHM_VERSION, findCandidatePairs, pairDedupeKey, riskLevelFromScore, scoreTraineePair, type TraineeDuplicateRecord } from "./matching.rules.js";

const FIELDS = "t.id, t.provider_id, t.first_name, t.father_name, t.grandfather_name, t.sex, t.age_years, t.dob_raw, t.phone_raw, t.phone_e164, t.phone_alt_raw, t.emergency_phone_raw, t.external_beneficiary_id, t.region_raw, t.trainee_code, p.name AS provider";
const record = (t: Row): TraineeDuplicateRecord => ({ id: BigInt((t["id"] as string) ?? 0), trainingProviderId: BigInt((t["provider_id"] as string) ?? 0), firstName: (t["first_name"] as string) ?? "", fatherName: t["father_name"] ?? null, grandfatherName: t["grandfather_name"] ?? null, sex: (t["sex"] as string) ?? "", ageYears: t["age_years"] ?? null, dateOfBirthEtCalendar: t["dob_raw"] ?? null, phonePrimary: t["phone_raw"] ?? null, phoneAlternative: t["phone_alt_raw"] ?? null, emergencyContactPhone: t["emergency_phone_raw"] ?? null, externalBeneficiaryId: t["external_beneficiary_id"] ?? null, region: t["region_raw"] ?? null });
export interface Candidate { id: string; code: string; name: string; provider: string; score: number; reasons: string[] }
/** Compares one person with those whose names start alike or who share the phone, using V1's scoring. */
export async function candidatesFor(db: Db, pid: string, person: Row, limit = 5, exceptId = "0"): Promise<Candidate[]> {
  const f = String(person["first_name"] ?? "").slice(0, 2), g = String(person["father_name"] ?? "").slice(0, 2);
  const rows = await query(db, `SELECT ${FIELDS} FROM trainees t JOIN providers p ON p.id=t.provider_id WHERE t.project_id=? AND t.id<>? AND t.roster_status IN ('active','reserve') AND ((t.first_name LIKE ? AND t.father_name LIKE ?) OR t.phone_e164=?)`, [pid, exceptId, `${f.replace(/[%_\\]/g, "\\$&")}%`, `${g.replace(/[%_\\]/g, "\\$&")}%`, (person["phone_e164"] as string) ?? "-"]);
  const me = record({ ...person, id: exceptId });
  return rows.map((t) => { const s = scoreTraineePair(me, record(t)); return { id: String(t["id"]), code: t["trainee_code"] as string, name: [t["first_name"], t["father_name"], t["grandfather_name"]].filter(Boolean).join(" "), provider: t["provider"] as string, score: s?.score ?? (t["phone_e164"] && t["phone_e164"] === person["phone_e164"] ? 100 : 0), reasons: s?.matchSignals.reasons ?? ["Same phone number"] }; })
    .filter((x) => riskLevelFromScore(x.score)).sort((a, b) => b.score - a.score).slice(0, limit);
}
export async function check(c: Ctx, b: { firstName: string; fatherName: string; grandfatherName: string; phone: string; sex?: string | undefined }) {
  const { parsePhone } = await import("../../shared/phone.js"), p = parsePhone(b.phone);
  const hit = (await candidatesFor(pool, c.pid, { first_name: b.firstName, father_name: b.fatherName, grandfather_name: b.grandfatherName, sex: b.sex, phone_e164: p.ok ? p.e164 : undefined }, 1))[0];
  if (!hit) return null;
  const t = (await traineeRows(c, "t.id=?", [hit.id]))[0];
  // A provider learns that a possible match exists elsewhere, but not that person's details.
  return { trainee: t ?? { id: hit.id, code: hit.code, fullName: hit.name, providerCode: hit.provider, phone: "" }, score: hit.score, reasons: hit.reasons };
}
const SIDE = (x: string) => `${x}.id AS ${x}_id, ${x}.trainee_code AS ${x}_code, ${x}.first_name AS ${x}_fn, ${x}.father_name AS ${x}_fa, ${x}.grandfather_name AS ${x}_gf, ${x}.sex AS ${x}_sex, ${x}.age_years AS ${x}_age, COALESCE(${x}.date_of_birth, ${x}.dob_raw) AS ${x}_dob, ${x}.phone_e164 AS ${x}_phone, ${x}.created_at AS ${x}_at, p${x}.name AS ${x}_prov, p${x}.id AS ${x}_provider_id, k${x}.code AS ${x}_cls, s${x}.att_rate_to_date AS ${x}_rate`;
const JOIN = (x: string) => `JOIN trainees ${x} ON ${x}.id=d.trainee_${x}_id JOIN providers p${x} ON p${x}.id=${x}.provider_id JOIN training_classes k${x} ON k${x}.id=${x}.class_id JOIN trainee_status s${x} ON s${x}.trainee_id=${x}.id`;
const SEL = `SELECT d.*, ${SIDE("a")}, ${SIDE("b")} FROM duplicate_candidates d ${JOIN("a")} ${JOIN("b")}`;
const side = (d: Row, x: string) => ({ id: d[`${x}_id`], code: d[`${x}_code`], firstName: d[`${x}_fn`], fatherName: d[`${x}_fa`] ?? "", grandfatherName: d[`${x}_gf`] ?? "", sex: d[`${x}_sex`], age: d[`${x}_age`], dob: d[`${x}_dob`] ?? undefined, phone: showPhone(d[`${x}_phone`]), provider: d[`${x}_prov`], classCode: d[`${x}_cls`], registeredAt: d[`${x}_at`], attendanceRate: d[`${x}_rate`] ?? undefined });
const view = (d: Row) => ({ id: d["id"], score: Number(d["score"]), risk: d["risk"], status: d["status"], crossProvider: d["a_provider_id"] !== d["b_provider_id"], reasons: json<{ reasons?: string[] }>(d["signals_json"], {}).reasons ?? [], a: side(d, "a"), b: side(d, "b"), note: d["reviewer_note"] ?? undefined });
export async function list(c: Ctx) {
  const where = ["d.project_id=?"], args: string[] = [c.pid];
  for (const [k, col] of [["status", "d.status"], ["risk", "d.risk"]] as const) if (c.query[k]) { where.push(`${col}=?`); args.push(c.query[k]!); }
  if (c.access.providerId) { where.push("a.provider_id=? AND b.provider_id=?"); args.push(c.access.providerId, c.access.providerId); }
  return (await query(pool, `${SEL} WHERE ${where.join(" AND ")} ORDER BY d.status='pending' DESC, d.score DESC LIMIT 500`, args)).map(view).filter((d) => c.query["crossProvider"] !== "true" || d.crossProvider);
}
export const summary = (c: Ctx) => query(pool, "SELECT status, risk, COUNT(*) AS count FROM duplicate_candidates WHERE project_id=? GROUP BY status, risk", [c.pid]);
export async function decide(c: Ctx, did: string, b: { decision: "confirmed_duplicate" | "not_duplicate"; note: string }) {
  const d = (await one(pool, `${SEL} WHERE d.id=? AND d.project_id=?`, [did, c.pid])) ?? notFound("Duplicate");
  if (c.access.providerId) notFound("Duplicate");
  await transaction(async (tx) => {
    if (!(await execute(tx, "UPDATE duplicate_candidates SET status=?, reviewer_note=?, reviewed_by=?, reviewed_at=UTC_TIMESTAMP(3) WHERE id=? AND status='pending'", [b.decision, b.note, c.user.id, did])).affectedRows) conflict("ALREADY_DECIDED", "This pair is already decided.");
    await audit(tx, c, { module: "duplicates", action: b.decision, entityType: "duplicate", entityId: did, summary: `${d["a_code"]} and ${d["b_code"]}: ${b.decision.replace("_", " ")}`, after: b });
  });
  return view((await one(pool, `${SEL} WHERE d.id=?`, [did]))!);
}
export const scan = (c: Ctx) => enqueue(pool, "duplicates.scan", {}, { projectId: c.pid, userId: c.user.id, dedupe: `dup:${c.pid}` }).then((jobId) => ({ jobId }));
/** Earlier decisions are never overwritten; only pairs still waiting are refreshed. */
defineJob("duplicates.scan", async (job) => {
  const pid = job.projectId!, people = (await query(pool, `SELECT ${FIELDS} FROM trainees t JOIN providers p ON p.id=t.provider_id WHERE t.project_id=? AND t.roster_status IN ('active','reserve')`, [pid])).map(record);
  await job.progress(20, `Comparing ${people.length} trainees`);
  const decided = new Set((await query(pool, "SELECT pair_key FROM duplicate_candidates WHERE project_id=? AND status<>'pending'", [pid])).map((x) => x["pair_key"] as string));
  const pairs = findCandidatePairs(people, decided);
  await transaction(async (tx) => {
    const run = await insert(tx, "duplicate_scan_runs", { project_id: pid, trigger_kind: job.userId ? "manual" : "scheduled", algorithm_version: DUPLICATE_ALGORITHM_VERSION, status: "finished", scanned_count: people.length, candidate_count: pairs.length, started_at: new Date().toISOString().slice(0, 19).replace("T", " "), created_by: job.userId });
    for (const p of pairs) await execute(tx, `INSERT INTO duplicate_candidates (project_id, scan_run_id, trainee_a_id, trainee_b_id, pair_key, score, risk, signals_json, status, first_seen_at, last_seen_at) VALUES (?,?,?,?,?,?,?,?,'pending',UTC_TIMESTAMP(3),UTC_TIMESTAMP(3)) ON DUPLICATE KEY UPDATE score=VALUES(score), risk=VALUES(risk), signals_json=VALUES(signals_json), last_seen_at=VALUES(last_seen_at), scan_run_id=VALUES(scan_run_id)`,
      [pid, run, String(p.traineeAId), String(p.traineeBId), pairDedupeKey(p.traineeAId, p.traineeBId), p.score, riskLevelFromScore(p.score) === "high" ? "high" : "medium", JSON.stringify(p.matchSignals)]);
    await execute(tx, "UPDATE duplicate_scan_runs SET finished_at=UTC_TIMESTAMP(3) WHERE id=?", [run]);
  });
  return { message: `${pairs.length} possible duplicates found.` };
});
