// verify-mites-that-live-on-your-face.mjs — the arithmetic behind the stratum
// "The Census on Your Face" (/strata/mites-that-live-on-your-face/).
//
// The claim the page makes: Demodex mites are near-universal on adult human
// skin, but the measured prevalence depends entirely on the DETECTION METHOD.
// Every percentage the page displays is recomputed here from the raw counts
// published in:
//
//   Thoemmes MS, Fergus DJ, Urban J, Trautwein M, Dunn RR.
//   "Ubiquity and Diversity of Human-Associated Demodex Mites."
//   PLOS ONE 9(8):e106265 (2014). doi:10.1371/journal.pone.0106265
//
// What this script proves, offline and from scratch:
//   1. DNA (16S rDNA PCR) detection in adults over 18   = 19/19 = 100.0%
//   2. DNA detection in 18-year-olds                    =  7/10 =  70.0%
//   3. Combined DNA positivity across everyone tested   = 26/29 =  89.7%
//   4. Visual microscopy prevalence in adults           = "14% (n=253)"
//      (REPORTED, not derived — exact positive count not published; the
//       inferred 35/253 = 13.8% brackets the reported 14%.)
//   5. Method gap DNA vs visual = 100 - 14 = 86 pp; ratio 100/14 = 7.1x
//   6. The honest floor under "100%" on n=19, three ways:
//        rule of three           1 - 3/19            = 84.2%
//        exact one-sided 95%     0.05^(1/19)         = 85.4%   (Clopper-Pearson)
//        Wilson two-sided lower  (score interval)    = 83.2%
//   7. Cross-check that the inferred visual numerator (35) really rounds to the
//      paper's reported 14%, and that 36 does too (the count is 35 or 36).
//
//   run:  node research/mites-that-live-on-your-face/verify-mites-that-live-on-your-face.mjs
//
// No dependencies. Every number the page displays is recomputed here.

let pass = 0, total = 0;
const check = (name, cond, extra = '') => {
  total++;
  if (cond) pass++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── the raw counts (the ONLY inputs) ───────────────────────────────────────
const RAW = {
  dna_over18:   { pos: 19, n: 19 },   // "every adult over 18 ... had detectable Demodex 16S rDNA"
  dna_eighteen: { pos: 7,  n: 10 },   // "of the ten 18 year olds ... only seven samples"
  visual_n:     253,                  // "the prevalence of mites in adults was 14% (n = 253)"
  visual_reported_pct: 14,            // reported verbatim; exact positive count NOT published
};
const pct = (pos, n) => (pos / n) * 100;

// ── 1-3. DNA detection rates, recomputed ────────────────────────────────────
console.log('\n— DNA (16S rDNA PCR) detection, recomputed from raw counts —');
const over18 = pct(RAW.dna_over18.pos, RAW.dna_over18.n);
const eighteen = pct(RAW.dna_eighteen.pos, RAW.dna_eighteen.n);
const combinedPos = RAW.dna_over18.pos + RAW.dna_eighteen.pos;   // 19 + 7
const combinedN = RAW.dna_over18.n + RAW.dna_eighteen.n;         // 19 + 10
const combined = pct(combinedPos, combinedN);

check('adults over 18: 19/19 = 100.0%', approx(over18, 100.0, 1e-9), `${over18.toFixed(1)}%`);
check('18-year-olds: 7/10 = 70.0%', approx(eighteen, 70.0, 1e-9), `${eighteen.toFixed(1)}%`);
check('everyone tested: (19+7)/29 = 26/29 = 89.7%',
  combinedPos === 26 && combinedN === 29 && approx(combined, 89.655, 0.01),
  `${combined.toFixed(4)}%`);

// ── 4. Visual prevalence: reported, and the inferred numerator brackets it ──
console.log('\n— visual microscopy prevalence (reported, numerator inferred) —');
const inferredPos = 35;
const inferredPct = pct(inferredPos, RAW.visual_n);
check('inferred 35/253 rounds to the reported 14%',
  Math.round(inferredPct) === RAW.visual_reported_pct,
  `35/253 = ${inferredPct.toFixed(2)}%`);
check('inferred visual prevalence sits in the 13.8–14.2% band', inferredPct >= 13.8 && inferredPct <= 14.2,
  `${inferredPct.toFixed(2)}%`);
// the true count is 35 or 36 — both round to 14%, 34 and 37 do not:
check('exact positive count is 35 or 36 (34 and 37 do NOT round to 14%)',
  Math.round(pct(35, 253)) === 14 && Math.round(pct(36, 253)) === 14 &&
  Math.round(pct(34, 253)) !== 14 && Math.round(pct(37, 253)) !== 14,
  `34→${pct(34,253).toFixed(1)} 35→${pct(35,253).toFixed(1)} 36→${pct(36,253).toFixed(1)} 37→${pct(37,253).toFixed(1)}`);

// ── 5. The method gap ───────────────────────────────────────────────────────
console.log('\n— the method gap: DNA vs visual —');
const gapPP = over18 - RAW.visual_reported_pct;         // 100 - 14
const ratio = over18 / RAW.visual_reported_pct;         // 100 / 14
check('gap = 100% − 14% = 86 percentage points', approx(gapPP, 86, 1e-9), `${gapPP} pp`);
check('ratio = 100/14 ≈ 7.1×', approx(ratio, 7.142857, 0.001), `${ratio.toFixed(4)}×`);

// ── 6. The honest floor under "100%" on n = 19, three ways ──────────────────
console.log('\n— the confidence floor under 19/19 (small-n honesty) —');
const n = 19;

// (a) rule of three: for 0 failures in n trials, upper bound on failure rate ≈ 3/n
const ruleOfThree = 1 - 3 / n;

// (b) exact Clopper–Pearson one-sided 95% lower bound for pos===n:
//     the lower limit p_L solves p_L^n = alpha = 0.05  →  p_L = 0.05^(1/n)
const clopper = Math.pow(0.05, 1 / n);

// (c) Wilson score interval (two-sided 95%), lower bound
function wilson(pos, N, z) {
  const p = pos / N, z2 = z * z, denom = 1 + z2 / N;
  const centre = (p + z2 / (2 * N)) / denom;
  const half = (z / denom) * Math.sqrt((p * (1 - p)) / N + z2 / (4 * N * N));
  return [Math.max(0, centre - half), Math.min(1, centre + half)];
}
const Z95 = 1.959963985;
const [wLow] = wilson(19, 19, Z95);

check('rule of three: 1 − 3/19 ≈ 84.2%', approx(ruleOfThree * 100, 84.21, 0.05), `${(ruleOfThree * 100).toFixed(2)}%`);
check('exact binomial one-sided 95% lower: 0.05^(1/19) ≈ 85.4%',
  approx(clopper * 100, 85.41, 0.1), `${(clopper * 100).toFixed(2)}%`);
check('Wilson two-sided 95% lower bound ≈ 83.2%', approx(wLow * 100, 83.18, 0.1), `${(wLow * 100).toFixed(2)}%`);
check('all three floors land in the low-to-mid 80s (not 100%)',
  wLow * 100 > 82 && wLow * 100 < 86 && clopper * 100 > 84 && clopper * 100 < 87 && ruleOfThree * 100 > 83 && ruleOfThree * 100 < 86,
  'the "100%" headline has an honest floor well below 100%');

// ── 7. Sanity: the internal consistency of the combined figure ──────────────
console.log('\n— internal consistency —');
check('combined positives = over-18 positives + 18-year-old positives',
  combinedPos === RAW.dna_over18.pos + RAW.dna_eighteen.pos, `${combinedPos} = 19 + 7`);
check('combined N = over-18 tested + 18-year-olds tested',
  combinedN === RAW.dna_over18.n + RAW.dna_eighteen.n, `${combinedN} = 19 + 10`);

// ── report ──────────────────────────────────────────────────────────────────
console.log(`\n${pass}/${total} checks passed`);
process.exit(pass === total ? 0 : 1);
