export type VerificationPathwayLabel = "clear_pass" | "clear_fail" | "inconclusive";

export type VerificationCiResult = {
  verifiedCount: number;
  definiteCount: number;
  verifiedRatePct: number;
  ciLowerPct: number;
  ciUpperPct: number;
  pathwayLabel: VerificationPathwayLabel;
};

export const VERIFICATION_STATUS_CODES = [
  "V-COMP",
  "V-NCOMP",
  "V-UNR",
  "V-REF",
  "V-INC",
] as const;

export type VerificationStatusCode = (typeof VERIFICATION_STATUS_CODES)[number];

export const DEFINITE_VERIFICATION_STATUS_CODES = new Set<VerificationStatusCode>(["V-COMP", "V-NCOMP"]);

export function verifiedValueFromStatus(code: VerificationStatusCode | null | undefined): boolean | null {
  if (code === "V-COMP") return true;
  if (code === "V-NCOMP") return false;
  return null;
}

/** Wilson score interval for binomial proportion at 95% confidence.
 * Default z=1.645 per ICOS protocol Section 7 (one-sided 95% CI). */
export function wilsonInterval(successes: number, n: number, z = 1.645): { lower: number; upper: number } {
  if (n <= 0) return { lower: 0, upper: 0 };
  const p = successes / n;
  const z2 = z * z;
  const denom = 1 + z2 / n;
  const center = p + z2 / (2 * n);
  const margin = z * Math.sqrt((p * (1 - p) + z2 / (4 * n)) / n);
  const lower = Math.max(0, (center - margin) / denom);
  const upper = Math.min(1, (center + margin) / denom);
  return { lower, upper };
}

/** Section 7 / Table 3 decision framework (display only — payment decided externally). */
export function evaluateVerificationPathway(
  successes: number,
  definiteCount: number,
  thresholdPct: number,
): VerificationCiResult {
  const verifiedRatePct = definiteCount > 0 ? (successes / definiteCount) * 100 : 0;
  const { lower, upper } = wilsonInterval(successes, definiteCount);
  const ciLowerPct = Math.round(lower * 10000) / 100;
  const ciUpperPct = Math.round(upper * 10000) / 100;

  let pathwayLabel: VerificationPathwayLabel;
  if (ciLowerPct > thresholdPct) pathwayLabel = "clear_pass";
  else if (ciUpperPct < thresholdPct) pathwayLabel = "clear_fail";
  else pathwayLabel = "inconclusive";

  return {
    verifiedCount: successes,
    definiteCount,
    verifiedRatePct: Math.round(verifiedRatePct * 100) / 100,
    ciLowerPct,
    ciUpperPct,
    pathwayLabel,
  };
}

export function pathwayDisplayLabel(label: VerificationPathwayLabel): string {
  switch (label) {
    case "clear_pass":
      return "Clear pass";
    case "clear_fail":
      return "Clear fail";
    default:
      return "Inconclusive";
  }
}
