import { audit } from "../../core/audit/audit.js";
import { randomToken } from "../../core/crypto.js";
import { execute, insert, insertMany, json, one, pool, query, transaction, type Db, type Row } from "../../core/db/db.js";
import { openFile, storeEvidence, type Incoming } from "../../core/files/files.js";
import { readTable, toCsv, toXlsx } from "../../core/files/table.js";
import { can, conflict, deny, invalid, notFound, type Ctx } from "../../core/http/route.js";
import { showPhone } from "../../shared/phone.js";
import { queueKpis } from "../projects/index.js";
import { resolveTargets } from "../indicators/index.js";
import { buildVerificationSamplePlan, drawVerificationSample, type VerificationSamplingCandidate } from "./sampling.rules.js";
import { blockers, decide, deriveStatus, STATUS, type SubjectFacts } from "./verification.rules.js";

/** Provider users never see samples, subjects or open runs. */
const independent = (c: Ctx) => { if (c.access.providerId) deny(); };
const REPORT: Record<string, string> = { training_completion_rate: "completion", training_certification_rate: "certification", employment_placement_rate: "employment_placement", locality_compliant_placement_rate: "locality_compliant", job_retention_3_month_rate: "job_retention_3m" };
const CLAIM: Record<string, string> = { eligible_enrolled_trainee_rate: "s.eligibility_status='eligible'", training_completion_rate: "s.completion_status='yes'", training_certification_rate: "s.certification_status='yes'", employment_placement_rate: "s.placement_status='yes'", locality_compliant_placement_rate: "s.locality_status='yes'", job_retention_3_month_rate: "s.retention_3m_status='yes'" };
/** Who can be sampled: everyone registered, or the people who passed the report this indicator builds on. */
const BASE: Record<string, string> = { training_certification_rate: "s.completion_status='yes'", employment_placement_rate: "s.certification_status='yes'", locality_compliant_placement_rate: "s.placement_status='yes'", job_retention_3_month_rate: "s.placement_status='yes'" };
const claimOf = (code: string) => CLAIM[code] ?? "0";
const planView = (p: Row) => ({ id: p["id"], indicatorCode: p["indicator_code"], indicatorName: p["iname"] ?? p["indicator_code"], version: p["version_no"], status: p["status"], populationMetric: p["population_metric"], strata: json<string[]>(p["stratify_by_json"], []), z: Number(p["z_value"]), p: Number(p["p_value"]), e: Number(p["margin_e"]), nonResponse: Number(p["non_response_factor"]), reservePct: Number(p["reserve_pct"]), minPerStratum: p["min_per_stratum"], tiering: p["tiering"], estimator: p["estimator"], ciZ: Number(p["ci_z_value"]), decisionRule: p["decision_rule"], maxAttempts: p["max_call_attempts"], effectiveFrom: p["effective_from"] ?? String(p["created_at"] ?? "").slice(0, 10) });
const PLAN = "SELECT p.*, (SELECT i.name FROM indicator_definitions i WHERE i.project_id=p.project_id AND i.code=p.indicator_code AND i.status='active' LIMIT 1) AS iname FROM verification_plans p";
export const plans = async (c: Ctx) => { independent(c); for (const d of await query(pool, "SELECT code FROM indicator_definitions WHERE project_id=? AND status='active'", [c.pid])) if (CLAIM[d["code"]]) await planFor(pool, c.pid, d["code"]); return (await query(pool, `${PLAN} WHERE p.project_id=? ORDER BY p.indicator_code, p.version_no DESC`, [c.pid])).map(planView); };
export const stages = (c: Ctx) => query(pool, "SELECT indicator_code AS indicatorCode, stage_key AS stageKey, label, offset_days AS offsetDays, is_final AS isFinal FROM indicator_stages WHERE project_id=? AND is_active=1 ORDER BY sort_order", [c.pid]);
async function planFor(db: Db, pid: string, code: string): Promise<Row> {
  const p = await one(db, `${PLAN} WHERE p.project_id=? AND p.indicator_code=? AND p.status='active' ORDER BY p.version_no DESC LIMIT 1`, [pid, code]);
  if (p) return p;
  if (!CLAIM[code]) invalid("indicator", "This indicator is not verified by sampling.");
  await insert(db, "verification_plans", { project_id: pid, indicator_code: code, version_no: 1, status: "active", population_metric: BASE[code] ? "trainees.base" : "trainees.registered", stratify_by_json: '["location","sex"]', z_value: 1.96, p_value: 0.5, margin_e: 0.05, non_response_factor: 0.9, reserve_pct: 15, tiering: "two_tier", estimator: "wilson_one_sided", ci_z_value: 1.645, decision_rule: "ci_vs_target", definite_codes_json: '["V-COMP","V-NCOMP"]', max_call_attempts: 3, notes: "V1 method" });
  return planFor(db, pid, code);
}
export async function savePlan(c: Ctx, b: Row) {
  independent(c);
  if (!CLAIM[b["indicatorCode"]]) invalid("indicatorCode", "This indicator is not verified by sampling.");
  const old = await planFor(pool, c.pid, b["indicatorCode"]), v = planView(old), n = { ...v, ...b };
  const pid = await transaction(async (tx) => {
    const max = Number((await one(tx, "SELECT MAX(version_no) AS v FROM verification_plans WHERE project_id=? AND indicator_code=?", [c.pid, v.indicatorCode]))!["v"]);
    await execute(tx, "UPDATE verification_plans SET status='retired' WHERE project_id=? AND indicator_code=? AND status='active'", [c.pid, v.indicatorCode]);
    const id = await insert(tx, "verification_plans", { project_id: c.pid, indicator_code: v.indicatorCode, version_no: max + 1, status: "active", population_metric: n.populationMetric, stratify_by_json: JSON.stringify(n.strata), z_value: n.z, p_value: n.p, margin_e: n.e, non_response_factor: n.nonResponse, reserve_pct: n.reservePct, min_per_stratum: n.minPerStratum ?? 1, tiering: n.tiering, estimator: n.estimator, ci_z_value: n.ciZ, decision_rule: n.decisionRule, definite_codes_json: '["V-COMP","V-NCOMP"]', max_call_attempts: n.maxAttempts });
    await audit(tx, c, { module: "verification", action: "plan_saved", entityType: "verification_plan", entityId: id, summary: `Verification plan of ${v.indicatorName}, version ${max + 1}`, before: v, after: b });
    return id;
  });
  return planView((await one(pool, `${PLAN} WHERE p.id=?`, [pid]))!);
}
async function population(db: Db, pid: string, providerId: string, plan: Row, stage = ""): Promise<{ rows: Row[]; candidates: VerificationSamplingCandidate[] }> {
  const rows = await query(db, `SELECT t.id, t.first_name, t.father_name, t.grandfather_name, t.phone_e164, t.phone_alt_e164, t.sex, t.trainee_code, tr.title, tr.level, l.id AS lid, l.name AS lname, (${claimOf(plan["indicator_code"])}) AS claim, s.dropout_status FROM trainees t JOIN trainee_status s ON s.trainee_id=t.id JOIN trainings tr ON tr.id=t.training_id JOIN training_sites st ON st.id=t.site_id LEFT JOIN locations l ON l.id=st.location_id WHERE t.project_id=? AND t.provider_id=? AND t.roster_status IN ('active','reserve') ${plan["population_metric"] === "trainees.claimed" ? `AND ${claimOf(plan["indicator_code"])}` : plan["population_metric"] === "trainees.base" && BASE[plan["indicator_code"]] ? `AND ${BASE[plan["indicator_code"]]}` : ""} ORDER BY t.id`, [pid, providerId]);
  return { rows, candidates: rows.map((r) => ({ traineeId: BigInt(r["id"]), locationId: r["lid"] ? BigInt(r["lid"]) : null, locationName: r["lname"] ?? "Unassigned location", sexKey: r["sex"] ?? "unknown" })) };
}
const params = (p: Row) => ({ Z: Number(p["z_value"]), p: Number(p["p_value"]), e: Number(p["margin_e"]), thresholdPct: 0, reserveRatioPct: Number(p["reserve_pct"]), nonResponseFactor: Number(p["non_response_factor"]) });
const ended = async (pid: string, code: string, provider: string) => { const type = REPORT[code]; if (!type) return true; const n = (await one(pool, "SELECT COUNT(*) AS n, SUM(EXISTS(SELECT 1 FROM outcome_reports r WHERE r.class_id=c.id AND r.report_type=? AND r.status='accepted')) AS d FROM training_classes c WHERE c.project_id=? AND c.provider_id=? AND c.is_cancelled=0 AND c.effective_end<CURRENT_DATE", [type, pid, provider]))!; return n["n"] > 0 && Number(n["n"]) === Number(n["d"]); };
export async function preview(c: Ctx) {
  independent(c);
  const code = c.query["indicator"] ?? "", provider = c.query["providerId"] ?? "0", plan = await planFor(pool, c.pid, code), { candidates } = await population(pool, c.pid, provider, plan, c.query["stage"]), s = buildVerificationSamplePlan(candidates, params(plan)), done = await ended(c.pid, code, provider);
  return { population: s.totalPopulation, n0: s.n0, nFpc: s.nAfterFpc, nTarget: s.primarySampleTotal, reserves: s.reserveSampleTotal, strata: s.strata.map((x) => ({ location: x.locationName, sex: x.sexKey, population: x.population, primary: x.primarySample, reserve: x.reserveSample })), warnings: [...s.warnings, ...(done ? [] : ["Not every ended class has an accepted report yet."])], reportsSubmitted: done };
}
const RUN = `SELECT r.*, p.name AS pname, (SELECT i.name FROM indicator_definitions i WHERE i.project_id=r.project_id AND i.code=r.indicator_code AND i.status='active' LIMIT 1) AS iname FROM verification_runs r JOIN providers p ON p.id=r.provider_id`;
const runView = (r: Row) => ({ id: r["id"], indicatorCode: r["indicator_code"], indicatorName: r["iname"] ?? r["indicator_code"], providerId: r["provider_id"], providerName: r["pname"], period: r["period_key"], ...(r["stage_key"] ? { stageKey: r["stage_key"] } : {}), tier: r["tier"], status: r["status"], populationCount: r["population_count"], sampleSize: r["sample_size"], counts: { primary: r["cnt_primary"], reserve: r["cnt_reserve"], completed: r["cnt_completed"], definite: r["cnt_definite"], success: r["cnt_success"], unreachable: r["cnt_unreachable"], refused: r["cnt_refused"], inconclusive: r["cnt_inconclusive"] }, ...(r["status"] === "finalised" ? { finalisedAt: r["finalised_at"], result: { rate: Number(r["verified_rate_pct"]), ciLow: Number(r["ci_lower_pct"]), ciHigh: Number(r["ci_upper_pct"]), target: Number(r["target_used"] ?? 0), pathway: r["pathway"] } } : {}) });
export async function runs(c: Ctx) { independent(c); return (await query(pool, `${RUN} WHERE r.project_id=? ORDER BY r.id DESC`, [c.pid])).map(runView); }
/** Providers get only finished, aggregate results of their own. */
export const results = async (c: Ctx) => (await query(pool, `${RUN} WHERE r.project_id=? AND r.status='finalised' ${c.access.providerId ? "AND r.provider_id=?" : ""} ORDER BY r.finalised_at DESC`, c.access.providerId ? [c.pid, c.access.providerId] : [c.pid])).map(runView);
async function draw(tx: Db, c: Ctx, o: { plan: Row; provider: string; period: string; stage: string; seed: string; tier: number; parent?: Row; exclude: Set<string>; preReport: boolean }): Promise<string> {
  const { rows, candidates } = await population(tx, c.pid, o.provider, o.plan, o.stage), left = candidates.filter((x) => !o.exclude.has(String(x.traineeId)));
  if (!left.length) invalid("providerId", "No trainee is available for this sample.");
  const plan = buildVerificationSamplePlan(left, params(o.plan)), d = drawVerificationSample(left, plan, o.seed, new Set()), by = new Map(rows.map((r) => [String(r["id"]), r]));
  const target = await targetFor(tx, c.pid, o.plan["indicator_code"], o.provider);
  const round = Number((await one(tx, "SELECT COALESCE(MAX(round_no),0)+1 AS n FROM verification_runs WHERE project_id=? AND provider_id=? AND indicator_code=? AND period_key=? AND stage_key=? AND tier=?", [c.pid, o.provider, o.plan["indicator_code"], o.period, o.stage, o.tier]))!["n"]);
  const rid = await insert(tx, "verification_runs", { project_id: c.pid, provider_id: o.provider, plan_id: o.plan["id"], indicator_code: o.plan["indicator_code"], report_type: REPORT[o.plan["indicator_code"]], stage_key: o.stage, period_key: o.period, round_no: round, tier: o.tier, parent_run_id: o.parent?.["id"], status: "in_field", is_pre_report_draw: o.preReport, seed: o.seed, sampling_strategy: d.samplingStrategy, parameters_json: JSON.stringify(params(o.plan)), population_count: left.length, n0: plan.n0, n_fpc: plan.nAfterFpc, sample_size: plan.primarySampleTotal, reserve_total: plan.reserveSampleTotal, target_used: target, drawn_at: new Date().toISOString().slice(0, 23).replace("T", " "), created_by: c.user.id });
  await insertMany(tx, "verification_strata", ["run_id", "stratum_key", "location_id", "location_name", "sex_key", "population", "primary_drawn", "reserve_drawn"], d.strata.map((s) => [rid, s.stratumKey, s.locationId, s.locationName, s.sexKey, s.population, s.primaryDrawn, s.reserveDrawn]));
  await insertMany(tx, "verification_frame_members", ["run_id", "trainee_id", "stratum_key", "claim_value", "attrs_json"], left.map((x) => { const r = by.get(String(x.traineeId))!; return [rid, String(x.traineeId), `location:${x.locationId ?? "none"}|sex:${x.sexKey}`, r["claim"] ? 1 : 0, JSON.stringify({ name: [r["first_name"], r["father_name"], r["grandfather_name"]].filter(Boolean).join(" "), phone: r["phone_e164"], phoneAlt: r["phone_alt_e164"], training: r["title"], level: r["level"], location: r["lname"], sex: r["sex"], code: r["trainee_code"] })]; }));
  // V1 rule: someone already reported as a dropout is recorded as "did not complete" without a call.
  await insertMany(tx, "verification_subjects", ["run_id", "trainee_id", "subject_key", "role", "stratum_key", "reserve_order", "status_code", "verified_value", "tp_claim_value", "supervisor_status", "is_auto_dropout"], d.subjects.map((s, i) => { const r = by.get(String(s.traineeId))!, drop = r["dropout_status"] === "yes"; return [rid, String(s.traineeId), `VS-${rid}-${String(i + 1).padStart(4, "0")}`, s.subjectRole, s.stratumKey, s.reserveOrder, drop ? "V-NCOMP" : null, drop ? 0 : null, r["claim"] ? 1 : 0, drop ? "approved" : "pending", drop ? 1 : 0]; }));
  await execute(tx, "INSERT INTO verification_run_dropouts (run_id, trainee_id) SELECT run_id, trainee_id FROM verification_subjects WHERE run_id=? AND is_auto_dropout=1", [rid]);
  await recount(tx, rid);
  await audit(tx, c, { module: "verification", action: o.tier === 2 ? "tier2_drawn" : "drawn", entityType: "verification_run", entityId: rid, summary: `Sample of ${plan.primarySampleTotal} drawn for ${o.plan["iname"] ?? o.plan["indicator_code"]}`, after: { seed: o.seed, provider: o.provider, period: o.period, population: left.length } });
  return rid;
}
const recount = (db: Db, rid: string) => execute(db, `UPDATE verification_runs r JOIN (SELECT run_id, SUM(role IN ('primary','replacement')) AS pr, SUM(role='reserve') AS rs, SUM(status_code IS NOT NULL AND role<>'reserve') AS done, SUM(role<>'reserve' AND COALESCE(status_code,'') IN ('V-COMP','V-NCOMP')) AS def, SUM(role<>'reserve' AND COALESCE(status_code,'')='V-COMP') AS ok, SUM(role<>'reserve' AND COALESCE(status_code,'')='V-UNR') AS unr, SUM(role<>'reserve' AND COALESCE(status_code,'')='V-REF') AS ref, SUM(role<>'reserve' AND COALESCE(status_code,'')='V-INC') AS inc FROM verification_subjects WHERE run_id=? GROUP BY run_id) k ON k.run_id=r.id SET r.cnt_primary=k.pr, r.cnt_reserve=k.rs, r.cnt_completed=k.done, r.cnt_definite=k.def, r.cnt_success=k.ok, r.cnt_unreachable=k.unr, r.cnt_refused=k.ref, r.cnt_inconclusive=k.inc`, [rid]);
/** V1's backfill: an open sample follows the accepted reports. New dropouts are settled without a call, dropouts taken back are opened again, and the provider's claim is read again. A result a person recorded is never touched. */
export async function syncOpenRuns(db: Db, o: { runId?: string; classId?: string; trainees?: string[] }): Promise<{ marked: number; reopened: number; claims: number }> {
  const total = { marked: 0, reopened: 0, claims: 0 };
  const who = `${o.classId ? "AND s.class_id=?" : ""} ${o.trainees ? "AND s.trainee_id IN (?)" : ""}`, args = [...(o.classId ? [o.classId] : []), ...(o.trainees ? [o.trainees] : [])] as never[];
  const runs = await query(db, `SELECT r.id, r.indicator_code AS code, r.stage_key AS stage FROM verification_runs r WHERE r.status NOT IN ('finalised','cancelled') ${o.runId ? "AND r.id=?" : ""} AND EXISTS (SELECT 1 FROM verification_frame_members f JOIN trainee_status s ON s.trainee_id=f.trainee_id WHERE f.run_id=r.id ${who})`, [...(o.runId ? [o.runId] : []), ...args] as never[]);
  for (const r of runs) {
    const rid = String(r["id"]), claim = `(${claimOf(r["code"])})`, join = "JOIN trainee_status s ON s.trainee_id=v.trainee_id", a = [rid, ...args] as never[];
    total.marked += (await execute(db, `UPDATE verification_subjects v ${join} SET v.status_code='V-NCOMP', v.verified_value=0, v.verified_at=UTC_TIMESTAMP(3), v.supervisor_status='approved', v.is_auto_dropout=1, v.reviewer_note='Auto-marked: dropout confirmed by outcome report' WHERE v.run_id=? AND v.status_code IS NULL AND s.dropout_status='yes' ${who}`, a)).affectedRows;
    total.reopened += (await execute(db, `UPDATE verification_subjects v ${join} SET v.status_code=NULL, v.verified_value=NULL, v.verified_at=NULL, v.supervisor_status='pending', v.is_auto_dropout=0, v.reviewer_note=NULL WHERE v.run_id=? AND v.is_auto_dropout=1 AND s.dropout_status<>'yes' ${who}`, a)).affectedRows;
    total.claims += (await execute(db, `UPDATE verification_subjects v ${join} SET v.tp_claim_value=COALESCE(${claim},0) WHERE v.run_id=? AND NOT (v.tp_claim_value <=> COALESCE(${claim},0)) ${who}`, a)).affectedRows;
    await execute(db, `UPDATE verification_frame_members v ${join} SET v.claim_value=COALESCE(${claim},0) WHERE v.run_id=? ${who}`, a);
    await execute(db, `DELETE v FROM verification_run_dropouts v ${join} WHERE v.run_id=? AND s.dropout_status<>'yes' ${who}`, a);
    await execute(db, `INSERT INTO verification_run_dropouts (run_id, trainee_id) SELECT v.run_id, v.trainee_id FROM verification_subjects v ${join} WHERE v.run_id=? AND s.dropout_status='yes' ${who} AND NOT EXISTS (SELECT 1 FROM verification_run_dropouts d WHERE d.run_id=v.run_id AND d.trainee_id=v.trainee_id)`, a);
    await recount(db, rid);
  }
  return total;
}
export async function refreshFromReports(c: Ctx, rid: string) {
  open(await runRow(c, rid));
  return transaction(async (tx) => {
    await one(tx, "SELECT id FROM verification_runs WHERE id=? FOR UPDATE", [rid]);
    const r = await syncOpenRuns(tx, { runId: rid });
    await audit(tx, c, { module: "verification", action: "refreshed_from_reports", entityType: "verification_run", entityId: rid, summary: `${r.marked} dropouts settled, ${r.reopened} opened again, ${r.claims} claims updated` });
    return r;
  });
}
export async function create(c: Ctx, b: { indicator: string; providerId: string; period: string; stage?: string | undefined; seed?: string | undefined; preReport?: boolean | undefined }) {
  independent(c);
  if (!(await one(pool, "SELECT 1 AS x FROM providers WHERE id=? AND project_id=?", [b.providerId, c.pid]))) invalid("providerId", "Choose the provider.");
  if (b.preReport && (await planFor(pool, c.pid, b.indicator))["population_metric"] !== "trainees.registered" && !(await ended(c.pid, b.indicator, b.providerId))) conflict("REPORTS_MISSING", "This sample is taken from trainees who passed a report, so every ended class needs its report first.");
  if (!b.preReport && !(await ended(c.pid, b.indicator, b.providerId))) conflict("REPORTS_MISSING", "Not every ended class has an accepted report. Confirm a draw before the reports if you want to continue.");
  const st = (await stages(c)).filter((x) => x["indicatorCode"] === b.indicator);
  if (st.length && !st.some((x) => x["stageKey"] === b.stage)) invalid("stage", "Choose the stage.");
  if (!st.length && b.stage) invalid("stage", "This indicator has no stages.");
  const runId = await transaction(async (tx) => {
    await one(tx, "SELECT id FROM providers WHERE id=? FOR UPDATE", [b.providerId]);
    if (await one(tx, "SELECT 1 AS x FROM verification_runs WHERE project_id=? AND provider_id=? AND indicator_code=? AND stage_key=? AND status NOT IN ('finalised','cancelled')", [c.pid, b.providerId, b.indicator, b.stage ?? ""])) conflict("RUN_OPEN", "A sample of this indicator is already open for this provider. It follows the reports by itself, so a new one is not needed until it is finished or cancelled.");
    return draw(tx, c, { plan: await planFor(tx, c.pid, b.indicator), provider: b.providerId, period: b.period, stage: b.stage ?? "", seed: b.seed?.trim() || randomToken().slice(0, 16), tier: 1, exclude: new Set(), preReport: Boolean(b.preReport) });
  });
  return { runId, jobId: "" };
}
/** The pass mark: the provider's own target, else the project's, else the one in the indicator. */
export async function targetFor(db: Db, pid: string, code: string, provider: string): Promise<number | null> {
  const t = (await resolveTargets(db, pid, new Date().toISOString().slice(0, 10))).filter((x) => x["code"] === code), own = t.filter((x) => String(x["providerId"]) === String(provider)).at(-1) ?? t.filter((x) => x["providerId"] === null).at(-1);
  const v = own?.["value"] ?? (await one(db, "SELECT default_target AS t FROM indicator_definitions WHERE project_id=? AND code=? AND status='active'", [pid, code]))?.["t"];
  return v === undefined || v === null ? null : Number(v);
}
/** An open run follows the target until it is finished; then the one used is kept for ever. */
const targetOf = async (db: Db, r: Row) => (r["status"] === "finalised" ? r["target_used"] : await targetFor(db, r["project_id"], r["indicator_code"], r["provider_id"])) as number | null;
const runRow = async (c: Ctx, rid: string, db: Db = pool): Promise<Row> => { independent(c); return (await one(db, `${RUN} WHERE r.id=? AND r.project_id=?`, [rid, c.pid])) ?? notFound("Run"); };
const open = (r: Row) => { if (["finalised", "cancelled"].includes(r["status"])) conflict("RUN_CLOSED", "This run is finished and cannot be changed."); };
const facts = async (db: Db, ids: string[]): Promise<SubjectFacts[]> => (await query(db, "SELECT id, role, status_code, replaces_subject_id, supervisor_status FROM verification_subjects WHERE run_id IN (?)", [ids])).map((s) => ({ id: String(s["id"]), role: s["role"], status: s["status_code"], replaces: s["replaces_subject_id"] === null ? null : String(s["replaces_subject_id"]), supervisor: s["supervisor_status"] }));
export async function getRun(c: Ctx, rid: string) {
  const r = await runRow(c, rid), plan = (await one(pool, "SELECT * FROM verification_plans WHERE id=?", [r["plan_id"]]))!, all = await facts(pool, [rid]), statusCounts: Record<string, number> = { pending: 0 };
  for (const s of STATUS) statusCounts[s] = 0;
  for (const s of all) if (s.role !== "reserve") statusCounts[s.status ?? "pending"]!++;
  const done = await query(pool, "SELECT stratum_key, SUM(status_code IS NOT NULL AND role<>'reserve') AS n FROM verification_subjects WHERE run_id=? GROUP BY stratum_key", [rid]);
  return { run: { ...runView(r), seed: r["seed"] ?? "", drawnAt: r["drawn_at"], targetUsed: (await targetOf(pool, r)) ?? undefined, planTiering: plan["tiering"], estimator: plan["estimator"], parameters: { z: Number(plan["z_value"]), p: Number(plan["p_value"]), e: Number(plan["margin_e"]), nonResponse: Number(plan["non_response_factor"]), reservePct: Number(plan["reserve_pct"]), ciZ: Number(plan["ci_z_value"]) } }, strata: (await query(pool, "SELECT * FROM verification_strata WHERE run_id=? ORDER BY location_name, sex_key", [rid])).map((s) => ({ key: s["stratum_key"], location: s["location_name"], sex: s["sex_key"], population: s["population"], primary: s["primary_drawn"], reserve: s["reserve_drawn"], completed: Number(done.find((d) => d["stratum_key"] === s["stratum_key"])?.["n"] ?? 0) })), statusCounts, blockers: blockers(all).length };
}
const SUB = `SELECT s.*, r.provider_id, r.status AS run_status, r.project_id, r.indicator_code, p.name AS pname, u.name AS ename, f.attrs_json, t.first_name, t.father_name, t.grandfather_name, t.phone_e164, t.phone_raw, t.phone_alt_e164, t.sex, tr.title, tr.level, l.name AS lname, (SELECT i.name FROM indicator_definitions i WHERE i.project_id=r.project_id AND i.code=r.indicator_code AND i.status='active' LIMIT 1) AS iname, (SELECT v.answers_json FROM verification_responses v WHERE v.subject_id=s.id ORDER BY v.id DESC LIMIT 1) AS answers
  FROM verification_subjects s JOIN verification_runs r ON r.id=s.run_id JOIN providers p ON p.id=r.provider_id JOIN trainees t ON t.id=s.trainee_id JOIN trainings tr ON tr.id=t.training_id JOIN training_sites st ON st.id=t.site_id LEFT JOIN locations l ON l.id=st.location_id LEFT JOIN users u ON u.id=s.assigned_enumerator_id LEFT JOIN verification_frame_members f ON f.run_id=s.run_id AND f.trainee_id=s.trainee_id`;
async function subjectViews(rows: Row[]) {
  const at = rows.length ? await query(pool, "SELECT * FROM verification_call_attempts WHERE subject_id IN (?) ORDER BY attempt_no", [rows.map((r) => r["id"] as string)]) : [];
  const ev = rows.length ? await query(pool, "SELECT e.id, e.subject_id, e.evidence_type AS type, f.original_name AS name FROM verification_evidence e JOIN files f ON f.id=e.file_id WHERE e.subject_id IN (?) ORDER BY e.id", [rows.map((r) => r["id"] as string)]) : [];
  return rows.map((s) => { const a = json<Row>(s["attrs_json"], {}); return { evidence: ev.filter((x) => x["subject_id"] === s["id"]).map((x) => ({ id: x["id"], name: x["name"], type: x["type"] })), id: s["id"], key: s["subject_key"], runId: s["run_id"], traineeId: s["trainee_id"], name: a["name"] ?? [s["first_name"], s["father_name"], s["grandfather_name"]].filter(Boolean).join(" "), phone: showPhone(a["phone"] ?? s["phone_e164"]) || (s["phone_raw"] ?? ""), phoneAlt: showPhone(a["phoneAlt"] ?? s["phone_alt_e164"]) || undefined, providerName: s["pname"], trainingTitle: a["training"] ?? s["title"], level: a["level"] ?? s["level"], location: a["location"] ?? s["lname"] ?? "", sex: s["sex"] ?? "", stratum: s["stratum_key"] ?? "", role: s["role"], enumerator: s["ename"] ?? undefined, attempts: at.filter((x) => x["subject_id"] === s["id"]).map((x) => ({ no: x["attempt_no"], at: x["called_at"], outcome: x["outcome"], note: x["note"] ?? undefined })), status: s["status_code"] ?? undefined, supervisor: s["supervisor_status"], answers: s["answers"] ? json(s["answers"], {}) : undefined, indicatorName: s["iname"] ?? "", note: s["reviewer_note"] ?? undefined }; });
}
/** An enumerator sees only the people assigned to them. */
const mine = (c: Ctx) => (can(c, "verification.approve") || can(c, "verification.plan") ? "1=1" : `s.assigned_enumerator_id=${Number(c.user.id)}`);
export async function subjects(c: Ctx, rid: string) {
  await runRow(c, rid);
  const q = c.query, where = ["s.run_id=?", mine(c)], args: string[] = [rid];
  if (q["status"] === "pending") where.push("s.status_code IS NULL"); else if (q["status"]) { where.push("s.status_code=?"); args.push(q["status"]); }
  if (q["role"]) { where.push("s.role=?"); args.push(q["role"]); }
  if (q["enumerator"]) { where.push("u.name=?"); args.push(q["enumerator"]); }
  return subjectViews(await query(pool, `${SUB} WHERE ${where.join(" AND ")} ORDER BY s.id`, args));
}
async function subject(c: Ctx, sid: string): Promise<Row> { independent(c); return (await one(pool, `${SUB} WHERE s.id=? AND r.project_id=? AND ${mine(c)}`, [sid, c.pid])) ?? notFound("Subject"); }
export const getSubject = async (c: Ctx, sid: string) => (await subjectViews([await subject(c, sid)]))[0];
export const myWork = async (c: Ctx) => { independent(c); return subjectViews(await query(pool, `${SUB} WHERE r.project_id=? AND r.status='in_field' AND s.assigned_enumerator_id=? AND s.role<>'reserve' AND (s.status_code IS NULL OR s.supervisor_status='rejected') ORDER BY s.id LIMIT 500`, [c.pid, c.user.id])); };
export const reviewQueue = async (c: Ctx) => { independent(c); return subjectViews(await query(pool, `${SUB} WHERE r.project_id=? AND r.status='in_field' AND s.role<>'reserve' AND s.status_code IS NOT NULL AND s.supervisor_status='pending' ORDER BY s.verified_at LIMIT 500`, [c.pid])); };
export async function assign(c: Ctx, rid: string, ids: string[], enumerator: string) {
  open(await runRow(c, rid));
  const u = (await one(pool, "SELECT u.id FROM users u JOIN memberships m ON m.user_id=u.id JOIN role_permissions p ON p.role_id=m.role_id AND p.perm_key='verification.record' WHERE m.project_id=? AND m.provider_id IS NULL AND m.status='active' AND u.status='active' AND (u.name=? OR u.id=?)", [c.pid, enumerator, enumerator])) ?? invalid("enumerator", "Choose an active enumerator.");
  const r = await execute(pool, "UPDATE verification_subjects SET assigned_enumerator_id=? WHERE run_id=? AND id IN (?) AND (status_code IS NULL OR supervisor_status='rejected')", [u["id"], rid, ids]);
  await audit(pool, c, { module: "verification", action: "assigned", entityType: "verification_run", entityId: rid, summary: `${r.affectedRows} subjects assigned to ${enumerator}`, after: { subjectIds: ids } });
  return { assigned: r.affectedRows };
}
export const enumerators = (c: Ctx) => query(pool, "SELECT DISTINCT u.id, u.name FROM users u JOIN memberships m ON m.user_id=u.id JOIN role_permissions p ON p.role_id=m.role_id AND p.perm_key='verification.record' WHERE m.project_id=? AND m.provider_id IS NULL AND m.status='active' AND u.status='active' ORDER BY u.name", [c.pid]);
/** The team calls outside the system (up to three times). Here they record only that nobody could be reached. */
export async function unreachable(c: Ctx, sid: string, note?: string) {
  const s = await subject(c, sid);
  open({ status: s["run_status"] });
  if (s["role"] === "reserve") conflict("RESERVE", "A reserve is called only after it replaces someone.");
  if (s["supervisor_status"] === "approved" && s["status_code"]) conflict("APPROVED", "The supervisor already approved this record.");
  await transaction(async (tx) => {
    const n = Number((await one(tx, "SELECT COALESCE(MAX(attempt_no),0)+1 AS n FROM verification_call_attempts WHERE subject_id=?", [sid]))!["n"]);
    await insert(tx, "verification_call_attempts", { subject_id: sid, attempt_no: n, called_at: new Date().toISOString().slice(0, 23).replace("T", " "), outcome: "no_answer", note, enumerator_id: c.user.id });
    await execute(tx, "UPDATE verification_subjects SET status_code='V-UNR', verified_value=NULL, verified_at=UTC_TIMESTAMP(3), verified_by=?, supervisor_status='pending', is_auto_dropout=0 WHERE id=?", [c.user.id, sid]);
    await recount(tx, s["run_id"]);
    await audit(tx, c, { module: "verification", action: "unreachable", entityType: "verification_subject", entityId: sid, summary: `${s["subject_key"]} could not be reached`, before: { status: s["status_code"] }, after: { note } });
  });
  return getSubject(c, sid);
}
async function record(tx: Db, c: Ctx, s: Row, answers: Record<string, string>, source: string, uuid?: string): Promise<void> {
  const code = deriveStatus(answers) ?? invalid("answers", "Answer the consent and completion questions.");
  await insert(tx, "verification_responses", { subject_id: s["id"], questionnaire_key: "phone_survey_v1", answers_json: JSON.stringify(answers), derived_status_code: code, source, kobo_submission_uuid: uuid, submitted_by: c.user.id, submitted_at: new Date().toISOString().slice(0, 23).replace("T", " ") });
  await execute(tx, "UPDATE verification_subjects SET status_code=?, verified_value=?, verified_at=UTC_TIMESTAMP(3), verified_by=?, supervisor_status='pending', is_auto_dropout=0 WHERE id=?", [code, code === "V-COMP" ? 1 : code === "V-NCOMP" ? 0 : null, c.user.id, s["id"]]);
  await recount(tx, s["run_id"]);
  await audit(tx, c, { module: "verification", action: "response", entityType: "verification_subject", entityId: String(s["id"]), summary: `Answers recorded: ${code}`, before: { status: s["status_code"] }, after: { answers, source } });
}
export async function respond(c: Ctx, sid: string, answers: Record<string, string>) {
  const s = await subject(c, sid);
  open({ status: s["run_status"] });
  if (s["role"] === "reserve") conflict("RESERVE", "A reserve is called only after it replaces someone.");
  if (s["supervisor_status"] === "approved" && s["status_code"]) conflict("APPROVED", "The supervisor already approved this record.");
  await transaction((tx) => record(tx, c, s, answers, "mis_form"));
  return getSubject(c, sid);
}
/** V1 rule: an unreachable, refusing or inconclusive person is replaced by the next reserve of the same stratum. */
export async function replace(c: Ctx, sid: string) {
  const s = await subject(c, sid);
  open({ status: s["run_status"] });
  if (!["V-UNR", "V-REF", "V-INC"].includes(s["status_code"])) conflict("NOT_REPLACEABLE", "Only an unreachable, refused or inconclusive subject can be replaced.");
  const nid = await transaction(async (tx) => {
    await one(tx, "SELECT id FROM verification_runs WHERE id=? FOR UPDATE", [s["run_id"]]);
    if (await one(tx, "SELECT 1 AS x FROM verification_subjects WHERE replaces_subject_id=?", [sid])) conflict("ALREADY_REPLACED", "This subject already has a replacement.");
    const r = (await one(tx, "SELECT * FROM verification_subjects WHERE run_id=? AND role='reserve' AND stratum_key=? ORDER BY reserve_order LIMIT 1", [s["run_id"], s["stratum_key"]])) ?? conflict("NO_RESERVE", "No reserve is left in this stratum.");
    await execute(tx, "UPDATE verification_subjects SET role='replacement', replaces_subject_id=?, replacement_reason=?, assigned_enumerator_id=? WHERE id=?", [sid, s["status_code"], s["assigned_enumerator_id"], r["id"]]);
    await recount(tx, s["run_id"]);
    await audit(tx, c, { module: "verification", action: "replaced", entityType: "verification_subject", entityId: sid, summary: `${s["subject_key"]} replaced by ${r["subject_key"]}` });
    return String(r["id"]);
  });
  return (await subjectViews(await query(pool, `${SUB} WHERE s.id=?`, [nid])))[0];
}
export async function unreplace(c: Ctx, sid: string) {
  const s = await subject(c, sid);
  open({ status: s["run_status"] });
  if (s["role"] !== "replacement" || (s["status_code"] && !s["is_auto_dropout"])) conflict("NOT_POSSIBLE", "Only a replacement without a result can go back to the reserves.");
  await transaction(async (tx) => { await execute(tx, "UPDATE verification_subjects SET role='reserve', replaces_subject_id=NULL, replacement_reason=NULL, assigned_enumerator_id=NULL WHERE id=?", [sid]); await recount(tx, s["run_id"]); await audit(tx, c, { module: "verification", action: "replacement_undone", entityType: "verification_subject", entityId: sid, summary: `${s["subject_key"]} returned to the reserves` }); });
  return getSubject(c, sid);
}
/** V1 supplement: more reserves for strata that ran out, taken from the frozen frame with the run's own seed. */
export async function supplement(c: Ctx, rid: string, perStratum: number) {
  const r = await runRow(c, rid);
  open(r);
  return transaction(async (tx) => {
    await one(tx, "SELECT id FROM verification_runs WHERE id=? FOR UPDATE", [rid]);
    const free = await query(tx, "SELECT f.trainee_id, f.stratum_key, f.claim_value FROM verification_frame_members f WHERE f.run_id=? AND JSON_EXTRACT(f.attrs_json,'$.reconstructed') IS NULL AND NOT EXISTS (SELECT 1 FROM verification_subjects s WHERE s.run_id=f.run_id AND s.trainee_id=f.trainee_id) ORDER BY SHA2(CONCAT(?,f.trainee_id),256)", [rid, r["seed"] ?? ""]), n = Number((await one(tx, "SELECT COUNT(*) AS n FROM verification_subjects WHERE run_id=?", [rid]))!["n"]);
    let added = 0;
    for (const key of new Set(free.map((f) => f["stratum_key"] as string))) {
      const max = Number((await one(tx, "SELECT COALESCE(MAX(reserve_order),0) AS n FROM verification_subjects WHERE run_id=? AND stratum_key=?", [rid, key]))!["n"]);
      for (const [i, f] of free.filter((x) => x["stratum_key"] === key).slice(0, perStratum).entries()) { added++; await insert(tx, "verification_subjects", { run_id: rid, trainee_id: f["trainee_id"], subject_key: `VS-${rid}-${String(n + added).padStart(4, "0")}`, role: "reserve", stratum_key: key, reserve_order: max + i + 1, tp_claim_value: f["claim_value"] }); }
    }
    await recount(tx, rid);
    await audit(tx, c, { module: "verification", action: "reserves_added", entityType: "verification_run", entityId: rid, summary: `${added} reserves added` });
    return { added };
  });
}
export async function review(c: Ctx, sid: string, decision: "approve" | "reject", note?: string) {
  const s = await subject(c, sid);
  open({ status: s["run_status"] });
  if (!s["status_code"]) conflict("NO_RESULT", "There is no result to review yet.");
  if (decision === "reject" && !note?.trim()) invalid("note", "Write a note before you reject.");
  if (s["verified_by"] === c.user.id && !s["is_auto_dropout"]) conflict("OWN_RECORD", "Someone else must review a record you made.");
  await transaction(async (tx) => { await execute(tx, "UPDATE verification_subjects SET supervisor_status=?, reviewer_note=? WHERE id=?", [decision === "approve" ? "approved" : "rejected", note ?? null, sid]); await audit(tx, c, { module: "verification", action: `review_${decision}`, entityType: "verification_subject", entityId: sid, summary: `${s["subject_key"]}: ${decision}`, after: { note } }); });
  return getSubject(c, sid);
}
export async function finalize(c: Ctx, rid: string) {
  await transaction(async (tx) => {
    const r = (await one(tx, "SELECT * FROM verification_runs WHERE id=? AND project_id=? FOR UPDATE", [rid, c.pid])) ?? notFound("Run");
    independent(c);
    open(r);
    const all = await facts(tx, [rid]), b = blockers(all);
    if (b.length) conflict("NOT_READY", `${b.length} subjects still need a result, a replacement or approval.`);
    const plan = (await one(tx, "SELECT * FROM verification_plans WHERE id=?", [r["plan_id"]]))!, pooled = r["parent_run_id"] ? [...all, ...(await facts(tx, [r["parent_run_id"]]))] : all, target = await targetFor(tx, c.pid, r["indicator_code"], r["provider_id"]), d = decide(pooled, target ?? 0, { estimator: plan["estimator"], ciZ: Number(plan["ci_z_value"]), rule: plan["decision_rule"] });
    // Against a target of 0 everything would pass.
    if (!target) conflict("NO_TARGET", "There is no target for this indicator and provider, so nothing can pass or fail. Set it under Targets first.");
    if (!d.definite) conflict("NO_RESULTS", "No subject has a definite result.");
    await execute(tx, "UPDATE verification_runs SET status='finalised', target_used=?, verified_rate_pct=?, ci_lower_pct=?, ci_upper_pct=?, pathway=?, finalised_at=UTC_TIMESTAMP(3), finalised_by=? WHERE id=?", [target, d.rate, d.low, d.high, d.pathway, c.user.id, rid]);
    await queueKpis(tx, c.pid);
    await audit(tx, c, { module: "verification", action: "finalised", entityType: "verification_run", entityId: rid, providerId: r["provider_id"], summary: `Result ${d.rate} % (${d.low} to ${d.high}), ${d.pathway.replace("_", " ")}`, after: d });
  });
  return runView(await runRow(c, rid));
}
export async function tier2(c: Ctx, rid: string) {
  const r = await runRow(c, rid), plan = (await one(pool, "SELECT * FROM verification_plans WHERE id=?", [r["plan_id"]]))!;
  if (r["status"] !== "finalised" || r["pathway"] !== "inconclusive" || r["tier"] !== 1) conflict("TIER2_NOT_AVAILABLE", "A second sample is only for a finished first sample that is inconclusive.");
  if (plan["tiering"] !== "two_tier") conflict("SINGLE_TIER", "This indicator is verified with one sample only.");
  const id = await transaction(async (tx) => {
    await one(tx, "SELECT id FROM verification_runs WHERE id=? FOR UPDATE", [rid]);
    if (await one(tx, "SELECT 1 AS x FROM verification_runs WHERE parent_run_id=? AND status<>'cancelled'", [rid])) conflict("TIER2_EXISTS", "The second sample is already drawn.");
    const used = new Set((await query(tx, "SELECT CAST(trainee_id AS CHAR) AS t FROM verification_subjects WHERE run_id=?", [rid])).map((x) => x["t"] as string));
    return draw(tx, c, { plan, provider: r["provider_id"], period: r["period_key"], stage: r["stage_key"], seed: randomToken().slice(0, 16), tier: 2, parent: r, exclude: used, preReport: Boolean(r["is_pre_report_draw"]) });
  });
  return { runId: id };
}
export async function cancel(c: Ctx, rid: string, reason: string) { const r = await runRow(c, rid); open(r); await transaction(async (tx) => { await execute(tx, "UPDATE verification_runs SET status='cancelled' WHERE id=?", [rid]); await audit(tx, c, { module: "verification", action: "cancelled", entityType: "verification_run", entityId: rid, summary: "Run cancelled", after: { reason } }); }); return runView(await runRow(c, rid)); }
export async function kobo(c: Ctx, rid: string, format: string) {
  const list = await subjects(c, rid), header = ["subject_key", "name", "phone", "phone_alternative", "provider", "training", "level", "location", "sex", "role", "enumerator", "status"], rows = list.filter((s) => s.role !== "reserve").map((s) => [s.key, s.name, s.phone, s.phoneAlt ?? "", s.providerName, s.trainingTitle, s.level, s.location, s.sex, s.role, s.enumerator ?? "", s.status ?? ""] as string[]);
  return { name: `verification_run_${rid}.${format}`, xlsx: format === "xlsx", body: format === "xlsx" ? await toXlsx("Subjects", header, rows, header) : toCsv(header, rows) };
}
export async function koboImport(c: Ctx, rid: string, name: string, data: Buffer) {
  open(await runRow(c, rid));
  const { header, rows } = await readTable(name, data), key = header.find((h) => h === "subject_key" || h.endsWith("_subject_key")) ?? invalid("file", "The file needs a subject_key column.");
  return transaction(async (tx) => {
    let matched = 0, unmatched = 0, updated = 0;
    for (const r of rows) {
      const s = await one(tx, "SELECT * FROM verification_subjects WHERE run_id=? AND subject_key=? AND role<>'reserve'", [rid, r[key] ?? ""]);
      if (!s) { unmatched++; continue; }
      matched++;
      const uuid = r["_uuid"] || r["uuid"] || undefined, answers = Object.fromEntries(Object.entries(r).map(([k, v]) => [(/(?:^|_)(q\d+)(?:_|$)/.exec(k) ?? [])[1], v.trim().toLowerCase().replace(/ /g, "_")]).filter(([k, v]) => k && v)) as Record<string, string>;
      if (s["supervisor_status"] === "approved" && s["status_code"] && !s["is_auto_dropout"]) continue;
      if (uuid && (await one(tx, "SELECT 1 AS x FROM verification_responses WHERE kobo_submission_uuid=?", [uuid]))) continue;
      if (deriveStatus(answers)) { await record(tx, c, s, answers, "kobo_import", uuid); updated++; }
    }
    return { matched, unmatched, updated };
  });
}
export const EVIDENCE_TYPES = ["call_recording", "field_visit", "document", "photo", "other"];
export async function addEvidence(c: Ctx, sid: string, type: string | undefined, files: Incoming[]) {
  const s = await subject(c, sid);
  open({ status: s["run_status"] });
  if (!type || !EVIDENCE_TYPES.includes(type)) invalid("evidenceType", "Choose what kind of evidence this is.");
  if (!files.length) invalid("files", "Choose a file.");
  return transaction(async (tx) => {
    const items: { id: string; name: string; type: string }[] = [];
    for (const f of files) items.push({ id: await insert(tx, "verification_evidence", { subject_id: sid, evidence_type: type!, file_id: await storeEvidence(tx, { projectId: c.pid, purpose: "verification_evidence", file: f, userId: c.user.id }), uploaded_by: c.user.id }), name: f.name, type: type! });
    await audit(tx, c, { module: "verification", action: "evidence_added", entityType: "verification_subject", entityId: sid, summary: `Evidence ${type}: ${files.map((f) => f.name).join(", ")}`.slice(0, 480) });
    return { items };
  });
}
export async function evidence(c: Ctx, sid: string, fid: string) { await subject(c, sid); const e = (await one(pool, "SELECT file_id FROM verification_evidence WHERE id=? AND subject_id=?", [fid, sid])) ?? notFound("File"); return openFile(e["file_id"]); }
