#!/usr/bin/env node
// verify.mjs — the check behind /strata/why-tattoos-permanent/
//
// WHAT IS PROVEN HERE (computed, reproducible, seed-fixed):
//   A. The capture–release retention law  R(t) = exp(-c · t/τ)  falls out of a
//      Poisson handoff process, and a Monte-Carlo agent simulation reproduces it.
//   B. The Baranska "ablation" experiment: force EVERY carrier macrophage to die
//      at once. Retention drops by exactly one handoff's loss (factor ~ (1-c)),
//      then the pattern persists — because recapture is LOCAL. The tattoo survives
//      total turnover of its carrier cells. This is the paper's central result,
//      shown as a self-consistent model.
//   C. Spatial sharpness: a rendered "tattoo" stays legible across many full
//      generations of cell turnover when recapture is LOCAL, and dissolves when
//      it is not. Same dynamics also give the slow real-world BLUR (small drift).
//
// WHAT IS *NOT* PROVEN HERE — it is CITED from the literature, not derived:
//   • that dermal macrophages are the long-term pigment reservoir, and that on
//     macrophage death the pigment is released and RE-captured by incoming
//     macrophages, so the tattoo persists  ...........  Baranska et al., J Exp Med 2018 (MOUSE tail).
//   • that tattoo pigment migrates to regional lymph nodes  ....  Schreiver et al., Sci Rep 2017.
//   • epidermal turnover time, dermal stability, needle depth  ..  see page sources.
//
// The MECHANISM is the science; the RETENTION LAW and its parameters (τ, c) are a
// transparent MODEL of that mechanism with ILLUSTRATIVE constants. The model's only
// honest quantitative claims are (1) permanence and slow fade come from the SAME
// handoff dynamics, and (2) the fade timescale is set by macrophage lifespan, not by
// any cell being permanent. Absolute half-lives shown are model outputs, not measured.

'use strict';

let pass = 0, fail = 0;
const approx = (a, b, tol, msg) => {
  const ok = Math.abs(a - b) <= tol;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${msg}  (got ${a.toFixed(5)}, want ${b.toFixed(5)}, tol ${tol})`);
  ok ? pass++ : fail++;
};
const ok = (cond, msg) => { console.log(`${cond ? 'PASS' : 'FAIL'}  ${msg}`); cond ? pass++ : fail++; };

// ---- a tiny deterministic RNG so the Monte-Carlo is reproducible ----
function mulberry32(seed) {
  let a = seed >>> 0;
  return function () {
    a |= 0; a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

console.log('\n=== A. The retention law R(t) = exp(-c·t/τ) ===\n');

// The analytic model. τ = mean time a pigment packet is held before its carrier
// macrophage dies (a handoff). On each handoff a fraction c of packets escape to
// the lymphatics and are cleared; the rest are recaptured locally and stay.
// Clearance is a thinned Poisson process of rate c/τ, so retention decays as
// R(t) = exp(-c·t/τ), with half-life t½ = τ·ln2/c.
const analyticR = (t, tau, c) => Math.exp(-c * t / tau);
const halfLife  = (tau, c) => tau * Math.LN2 / c;

// ILLUSTRATIVE parameters (labelled as such on the page):
const TAU = 1.0;    // years per handoff (illustrative)
const C   = 0.02;   // 2% of packets lost to lymph per handoff (illustrative)

// Monte-Carlo: many packets, each cleared by a Poisson process of rate c/τ.
// Simulate to time T in small steps; probability of a clearance event in dt is
// (c/τ)·dt (kept small). Confirm the surviving fraction matches exp(-c·t/τ).
function mcRetention(T, tau, c, N, dt, seed) {
  const rng = mulberry32(seed);
  let alive = new Array(N).fill(true);
  const rate = c / tau;
  const steps = Math.round(T / dt);
  for (let s = 0; s < steps; s++) {
    for (let i = 0; i < N; i++) {
      if (alive[i] && rng() < rate * dt) alive[i] = false; // this handoff leaked
    }
  }
  return alive.filter(Boolean).length / N;
}

for (const T of [10, 34.66, 50, 100]) {
  const a = analyticR(T, TAU, C);
  const m = mcRetention(T, TAU, C, 40000, 0.02, 12345 + Math.round(T));
  approx(m, a, 0.01, `MC retention at t=${T}y matches analytic exp(-c·t/τ)`);
}

const HL = halfLife(TAU, C);
approx(analyticR(HL, TAU, C), 0.5, 1e-9, `at t = t½ retention is exactly 1/2`);
console.log(`\n  → illustrative half-life t½ = τ·ln2/c = ${HL.toFixed(2)} "years"`);
console.log(`  → retention after 40y = ${(analyticR(40, TAU, C) * 100).toFixed(1)}%  (still a legible tattoo)`);
console.log(`  → note: HALVING c or DOUBLING τ ~doubles the half-life — the timescale`);
console.log(`    is set by macrophage turnover and leak, NOT by any cell being permanent.`);

console.log('\n=== B. The ablation experiment (Baranska et al. 2018, as a model) ===\n');
// Kill EVERY carrier macrophage at once. Each held packet undergoes one forced
// handoff: fraction c leaks, the rest are recaptured by incoming macrophages and
// stay. Prediction: retention drops by factor (1-c) in a single step, then the
// tattoo persists. (In the mouse the tattoo was reported to remain fully visible.)
{
  const before = 1.0;
  const after = before * (1 - C);
  approx(after, 0.98, 1e-9, `single mass ablation removes exactly c = ${C} of pigment`);
  ok(after > 0.95, `after wiping out 100% of carrier cells, >95% of pigment is recaptured & stays`);
  console.log(`  → carrier cells replaced: 100%.  Pigment retained: ${(after * 100).toFixed(0)}%.`);
  console.log(`    Permanence is a DYNAMIC steady state, not static trapping.`);
}

console.log('\n=== C. Spatial: local recapture keeps the line sharp ===\n');
// Render a small "tattoo" on a grid, then run G generations of TOTAL cell turnover.
// LOCAL model: on a handoff, survivors stay on their own site (+ rare 1-cell drift → slow blur).
// NON-LOCAL model: survivors are re-captured at a random site → the pattern dissolves.
const W = 24, H = 9;
// a simple glyph pattern: the letters "AW"
const ART = [
  '  ###    ####   ####   ',
  ' #   #   #  #   #  #    ',
  ' #   #   #  #   #  #    ',
  ' #####   #  #   #  #    ',
  ' #   #   # ## ## #      ',
  ' #   #   ## #  # #      ',
  ' #   #   #      #       ',
];
function seedField() {
  const f = [];
  for (let y = 0; y < H; y++) {
    const row = (ART[y] || '').padEnd(W, ' ');
    for (let x = 0; x < W; x++) if (row[x] === '#') f.push({ x, y, ox: x, oy: y });
  }
  return f;
}
function corrToOriginal(field) {
  // fraction of surviving packets still on (or adjacent to) their ORIGINAL site
  if (!field.length) return 0;
  let onSite = 0;
  for (const p of field) {
    const d = Math.abs(p.x - p.ox) + Math.abs(p.y - p.oy);
    if (d <= 1) onSite++;
  }
  return onSite / field.length;
}
function turnover(field, { local, c, driftP, gens, seed }) {
  const rng = mulberry32(seed);
  let f = field.map(p => ({ ...p }));
  for (let g = 0; g < gens; g++) {
    const next = [];
    for (const p of f) {
      if (rng() < c) continue; // leaked to lymph, cleared
      if (local) {
        // recaptured locally; rare single-cell drift (the slow real-world blur)
        let nx = p.x, ny = p.y;
        if (rng() < driftP) { nx += (rng() < 0.5 ? -1 : 1); }
        if (rng() < driftP) { ny += (rng() < 0.5 ? -1 : 1); }
        next.push({ x: Math.max(0, Math.min(W - 1, nx)), y: Math.max(0, Math.min(H - 1, ny)), ox: p.ox, oy: p.oy });
      } else {
        // recaptured somewhere random — pattern information is lost
        next.push({ x: Math.floor(rng() * W), y: Math.floor(rng() * H), ox: p.ox, oy: p.oy });
      }
    }
    f = next;
  }
  return f;
}
function render(field) {
  const grid = Array.from({ length: H }, () => new Array(W).fill(' '));
  for (const p of field) grid[p.y][p.x] = '#';
  return grid.map(r => '    |' + r.join('') + '|').join('\n');
}

const original = seedField();
console.log('  original tattoo:');
console.log(render(original));

const GENS = 25; // 25 full generations = the carrier cells replaced 25 times over
const localF = turnover(original, { local: true,  c: C, driftP: 0.004, gens: GENS, seed: 7 });
const nonlocF = turnover(original, { local: false, c: C, driftP: 0,     gens: GENS, seed: 7 });

console.log(`\n  after ${GENS} full generations of cell turnover — LOCAL recapture (the real mechanism):`);
console.log(render(localF));
console.log(`\n  after ${GENS} full generations — NON-LOCAL recapture (counterfactual):`);
console.log(render(nonlocF));

const corrLocal = corrToOriginal(localF);
const corrNon   = corrToOriginal(nonlocF);
console.log(`\n  packets still on/adjacent to their original site:  local ${(corrLocal * 100).toFixed(0)}%  ·  non-local ${(corrNon * 100).toFixed(0)}%`);
ok(corrLocal > 0.85, `LOCAL recapture keeps >85% of pigment on its original site → tattoo stays sharp`);
ok(corrNon < 0.15, `NON-LOCAL recapture scatters pigment (<15% on site) → tattoo dissolves`);
ok(localF.length / original.length > 0.25, `after ${GENS} generations the LOCAL tattoo still retains a quarter+ of its pigment`);

// ---- the numbers the page prints (kept in sync with the on-page instrument) ----
console.log('\n=== NUMBERS THE PAGE SHOWS ===\n');
const page = {
  law: 'R(t) = exp(-c·t/τ)',
  tau_illustrative_years: TAU,
  c_illustrative: C,
  halfLife_years: +HL.toFixed(1),
  retention_40y_pct: +(analyticR(40, TAU, C) * 100).toFixed(1),
  ablation_retained_pct: +((1 - C) * 100).toFixed(0),
  spatial_local_onsite_pct: +(corrLocal * 100).toFixed(0),
  spatial_nonlocal_onsite_pct: +(corrNon * 100).toFixed(0),
  epidermal_turnover_days: '~36–40 (cited: Maeda 2017 36.2d; Weinstein 1984 39d; not derived here)',
  needle_depth_mm: '~1–2 into the dermis (cited, approximate)',
};
console.log(JSON.stringify(page, null, 2));

console.log(`\n${pass} passed, ${fail} failed\n`);
process.exit(fail ? 1 : 0);
