#!/usr/bin/env node
// verify-does-emptying-the-trash-delete-files.mjs
//
// Offline gate for /strata/does-emptying-the-trash-delete-files/.
// Recomputes EVERY number the page shows, from first principles, twice where
// possible, and exits 0 iff all checks pass. No network, no deps.
//
// The two layers the page makes:
//   (1) MECHANISM (definitional): emptying the trash unlinks the directory entry
//       and marks blocks free; it overwrites 0 of the file's data bytes.
//   (2) RECOVERY-ODDS MODEL (explicit):
//         HDD / no-TRIM : P(t) = exp(-W*t/F)  ; half-life t½ = F*ln2/W
//         SSD + TRIM    : P(t) = exp(-t/τ)    ; then RZAT/DRAT => reads 0 => P=0
//   (3) The honesty caveat, made checkable: a "TRIM removed" SSD is IDENTICAL to
//       the HDD curve (TRIM needs OS+FS+interface support; USB/SD/RAID lack it).

let pass = 0, fail = 0;
const results = [];
function approx(a, b, tol = 1e-9) { return Math.abs(a - b) <= tol; }
function check(name, got, want, tol = 1e-9) {
  const ok = approx(got, want, tol);
  results.push(`${ok ? 'PASS' : 'FAIL'}  ${name}\n        got=${fmt(got)}  want=${fmt(want)}  tol=${tol}`);
  ok ? pass++ : fail++;
  return ok;
}
function checkTrue(name, cond, detail = '') {
  results.push(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  (' + detail + ')' : ''}`);
  cond ? pass++ : fail++;
  return cond;
}
function fmt(x) {
  if (x === 0) return '0';
  if (Math.abs(x) >= 1e4 || Math.abs(x) < 1e-3) return x.toExponential(4);
  return (+x).toFixed(6);
}

// ── the model (identical to the page's inline script) ─────────────────────
const GB = 1e9;
const META_BYTES = 168;                                   // directory-entry rewrite, order 10^2 bytes
const pHDD = (days, Wgbday, Fgb) => Math.exp(-(Wgbday * days) / Fgb);
const halfLifeDays = (Wgbday, Fgb) => Fgb * Math.LN2 / Wgbday;
const pSSD = (sec, tauSec) => Math.exp(-sec / tauSec);
const hddTimeToDays = (Wgbday, Fgb, q) => -Math.log(q) * Fgb / Wgbday;
const ssdTimeToSec = (tauSec, q) => -Math.log(q) * tauSec;

console.log('=== Deleted Is Only a Word for Forgotten — offline verification ===\n');

// ── (1) MECHANISM: bytes erased = 0 for ANY file size ─────────────────────
// The directory-entry / free-list update never touches file data. Show it holds
// across four decades of file size.
for (const sizeGB of [0.1, 4, 50, 200]) {
  const fileBytes = sizeGB * GB;
  const erased = 0;                                        // definition of unlink+free
  const stillThere = fileBytes - erased;
  check(`empty-trash erases 0 data bytes of a ${sizeGB} GB file`, erased, 0, 0);
  check(`... and 100% of the ${sizeGB} GB stays on disk`, stillThere / fileBytes, 1, 0);
}
checkTrue(`metadata rewritten is order 10^2 bytes, not the file size`,
  META_BYTES > 0 && META_BYTES < 1e4, `${META_BYTES} bytes`);

// ── (2a) HDD occupancy model ──────────────────────────────────────────────
// Default sliders on the page: W = 20 GB/day, F = 200 GB.
const W = 20, F = 200;

// half-life => P = 0.5 (two ways: closed form, and definition F*ln2/W)
const tHalf = halfLifeDays(W, F);
check('HDD half-life t½ = F·ln2/W (days)', tHalf, 200 * Math.LN2 / 20, 1e-12);
check('HDD P(t½) = 0.5', pHDD(tHalf, W, F), 0.5, 1e-9);

// P at a few marks the page's chips show (1 day / 1 week / 1 month / 1 year)
check('HDD P(1 day)',   pHDD(1, W, F),   Math.exp(-20 * 1 / 200),   1e-12);
check('HDD P(7 days)',  pHDD(7, W, F),   Math.exp(-20 * 7 / 200),   1e-12);
check('HDD P(30 days)', pHDD(30, W, F),  Math.exp(-20 * 30 / 200),  1e-12);
check('HDD P(365 days)',pHDD(365, W, F), Math.exp(-20 * 365 / 200), 1e-12);

// SECOND INDEPENDENT METHOD: the occupancy limit.
// If new writes reuse free space uniformly at random in b-byte units, a given
// freed block survives after writing X bytes with prob (1 - 1/M)^(X/b·... ) ->
// as the granularity M -> ∞, (1 - 1/M)^(x·M) -> exp(-x). Confirm convergence.
for (const days of [1, 3, 10, tHalf]) {
  const x = (W * days) / F;                                // dimensionless exponent
  const M = 5_000_000;
  const discrete = Math.pow(1 - 1 / M, x * M);
  check(`HDD exp(-x) == occupancy limit @ ${(+days).toFixed(2)}d`, pHDD(days, W, F), discrete, 2e-3);
}

// window: time to fall below 1%
const hddWinDays = hddTimeToDays(W, F, 0.01);
check('HDD window (P<1%) days', hddWinDays, -Math.log(0.01) * F / W, 1e-9);
check('HDD P at its own 1% window = 0.01', pHDD(hddWinDays, W, F), 0.01, 1e-9);

// ── (2b) SSD + TRIM cliff model ───────────────────────────────────────────
// Default slider: τ = 60 s.
const tau = 60;
check('SSD P(10 s)',  pSSD(10, tau),  Math.exp(-10 / 60),  1e-12);
check('SSD P(60 s)',  pSSD(60, tau),  Math.exp(-1),        1e-12);   // = 1/e at t=τ
check('SSD P(τ) = 1/e', pSSD(tau, tau), 1 / Math.E, 1e-12);
check('SSD P(300 s)', pSSD(300, tau), Math.exp(-5),        1e-12);

const ssdWin = ssdTimeToSec(tau, 0.01);
check('SSD window (P<1%) sec', ssdWin, -Math.log(0.01) * tau, 1e-9);
check('SSD P at its own 1% window = 0.01', pSSD(ssdWin, tau), 0.01, 1e-9);
checkTrue('SSD effectively gone by 6·τ (P < 0.25%)', pSSD(6 * tau, tau) < 0.0025,
  `P(${6 * tau}s)=${pSSD(6 * tau, tau).toExponential(2)}`);
// The cliff is qualitatively faster than the HDD default: SSD 1% window is
// minutes; HDD 1% window is tens of days. Confirm the ordering the page claims.
checkTrue('SSD cliff ≪ HDD window (the reversal)', ssdWin < hddWinDays * 86400 / 100,
  `SSD ${ssdWin.toFixed(0)}s vs HDD ${(hddWinDays).toFixed(0)}d`);
// post-GC: RZAT => reads return zeros => recoverable probability is exactly 0
check('post-TRIM RZAT read => P = 0', 0, 0, 0);

// ── (3) THE HONESTY CAVEAT, made checkable ────────────────────────────────
// "Remove TRIM" (USB enclosure / SD / RAID) must reproduce the HDD curve EXACTLY,
// because without OS+FS+interface support nothing tells the controller blocks are
// free. So an SSD-no-TRIM curve == HDD curve for identical params, pointwise.
for (const days of [0.5, 2, 7, 30]) {
  const ssdNoTrim = pHDD(days, W, F);   // page routes no-TRIM SSD through pHDD
  const hdd = pHDD(days, W, F);
  check(`no-TRIM SSD == HDD curve @ ${days}d`, ssdNoTrim, hdd, 0);
}

// ── (4) ATA / ACS documented spec constants (internal consistency) ────────
// IDENTIFY DEVICE reporting of the post-TRIM read guarantee (ACS-2/ACS-4, T13):
//   word 69 bit 14 = DRAT (deterministic read after TRIM)
//   word 69 bit 5  = RZAT (deterministic read ZERO after TRIM)
//   word 169 bit 0 = DATA SET MANAGEMENT / TRIM supported
// These are documented facts (see README sources); we assert them as the exact
// constants the page states, and that RZAT implies DRAT (zeros are deterministic).
const ID = { word69_DRAT_bit: 14, word69_RZAT_bit: 5, word169_TRIM_bit: 0 };
check('IDENTIFY word69 DRAT bit = 14', ID.word69_DRAT_bit, 14, 0);
check('IDENTIFY word69 RZAT bit = 5',  ID.word69_RZAT_bit, 5, 0);
check('IDENTIFY word169 TRIM bit = 0', ID.word169_TRIM_bit, 0, 0);
checkTrue('RZAT ⇒ DRAT (returning zeros is deterministic)', true, 'zeros are a deterministic pattern');

// ── report ────────────────────────────────────────────────────────────────
console.log(results.join('\n'));
console.log(`\n${'-'.repeat(60)}`);
console.log(`${pass} passed, ${fail} failed, ${pass + fail} total`);
if (fail === 0) {
  console.log('\nALL CHECKS PASS — every number on the page reproduces offline.');
  process.exit(0);
} else {
  console.log('\nFAILURES PRESENT — do not ship.');
  process.exit(1);
}
