import { DEFAULT_SAMPLING_Z } from "./sampling.rules.js";

export const STATUS = ["V-COMP", "V-NCOMP", "V-UNR", "V-REF", "V-INC"] as const;
export type StatusCode = (typeof STATUS)[number];
export interface SubjectFacts { id: string; role: string; status: string | null; replaces: string | null; supervisor: string }
const active = (s: SubjectFacts) => s.role === "primary" || s.role === "replacement";
const definite = (s: SubjectFacts) => s.status === "V-COMP" || s.status === "V-NCOMP";
/** Questionnaire answers to a protocol status code. */
export function deriveStatus(a: Record<string, string>): StatusCode | undefined {
  if (a["q1"] === "no") return "V-REF";
  if (a["q1"] !== "yes") return undefined;
  if (a["q2"] === "not_correct" && a["q3"] === "not_correct") return "V-INC";
  if (a["q10"] === "no") return "V-NCOMP";
  if (a["q10"] === "not_sure") return "V-INC";
  return a["q10"] === "yes" ? "V-COMP" : undefined;
}
/** Subjects that still block finalising: no result, not replaced, or not approved by the supervisor. */
export function blockers(all: SubjectFacts[]): string[] {
  const replaced = new Set(all.map((s) => s.replaces).filter(Boolean));
  return all.filter((s) => active(s) && (!s.status || (!definite(s) && !replaced.has(s.id)) || (definite(s) && s.supervisor !== "approved"))).map((s) => s.id);
}
const wilson = (x: number, n: number, z: number) => { if (!n) return { low: 0, high: 0 }; const p = x / n, z2 = z * z, d = 1 + z2 / n, c = p + z2 / (2 * n), m = z * Math.sqrt((p * (1 - p) + z2 / (4 * n)) / n); return { low: Math.max(0, (c - m) / d), high: Math.min(1, (c + m) / d) }; };
/** Exact binomial interval, found by bisection on the binomial tail. */
function clopper(x: number, n: number, z: number) {
  if (!n) return { low: 0, high: 0 };
  const alpha = 2 * (1 - cdf(z)), logC = (k: number) => { let s = 0; for (let i = 1; i <= k; i++) s += Math.log((n - k + i) / i); return s; };
  const atLeast = (k: number, p: number) => { let t = 0; for (let i = k; i <= n; i++) t += Math.exp(logC(i) + i * Math.log(p) + (n - i) * Math.log(1 - p)); return t; };
  const solve = (f: (p: number) => number, target: number) => { let a = 1e-12, b = 1 - 1e-12; for (let i = 0; i < 80; i++) { const m = (a + b) / 2; if (f(m) < target) a = m; else b = m; } return (a + b) / 2; };
  return { low: x === 0 ? 0 : solve((p) => atLeast(x, p), alpha / 2), high: x === n ? 1 : solve((p) => atLeast(x + 1, p), 1 - alpha / 2) };
}
function cdf(z: number): number { const t = 1 / (1 + 0.2316419 * z), d = 0.3989422804 * Math.exp((-z * z) / 2); return 1 - d * t * (0.31938153 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429)))); }
export interface Decision { rate: number; low: number; high: number; pathway: "clear_pass" | "clear_fail" | "inconclusive"; success: number; definite: number }
const r2 = (x: number) => Math.round(x * 10000) / 100;
export function decide(all: SubjectFacts[], target: number, plan: { estimator: string; ciZ: number; rule: string }): Decision {
  const mine = all.filter((s) => active(s) && definite(s)), x = mine.filter((s) => s.status === "V-COMP").length, n = mine.length;
  const ci = plan.estimator === "clopper_pearson" ? clopper(x, n, plan.ciZ) : plan.estimator === "simple_rate" ? { low: n ? x / n : 0, high: n ? x / n : 0 } : wilson(x, n, plan.estimator === "wilson_two_sided" ? DEFAULT_SAMPLING_Z : plan.ciZ);
  const rate = n ? Math.round((x / n) * 10000) / 100 : 0, low = r2(ci.low), high = r2(ci.high);
  const pathway = plan.rule === "point_vs_target" ? (rate >= target ? "clear_pass" : "clear_fail") : low > target ? "clear_pass" : high < target ? "clear_fail" : plan.estimator === "simple_rate" ? "clear_pass" : "inconclusive";
  return { rate, low, high, pathway, success: x, definite: n };
}
