#!/usr/bin/env node
// Offline gate for /strata/does-incognito-mode-make-you-anonymous/.
// Reproduces the page's deterministic "who can see this session?" model AND the
// settlement arithmetic, then asserts every number the page shows. Exit 0 iff all pass.
//
// Run: node research/does-incognito-mode-make-you-anonymous/verify-does-incognito-mode-make-you-anonymous.mjs

'use strict';

let failures = 0;
function check(name, got, want, note) {
  const ok = got === want;
  if (!ok) failures++;
  const g = typeof got === 'number' ? got : JSON.stringify(got);
  const w = typeof want === 'number' ? want : JSON.stringify(want);
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}: ${g}${ok ? '' : `  (expected ${w})`}${note ? '  — ' + note : ''}`);
}
function approx(name, got, want, tol, note) {
  const ok = Math.abs(got - want) <= tol;
  if (!ok) failures++;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}: ${got}${ok ? '' : `  (expected ${want} ±${tol})`}${note ? '  — ' + note : ''}`);
}

// ─────────────────────────────────────────────────────────────────────────
//  THE MODEL — copied verbatim from public/strata/.../index.html.
//  If these two diverge, the check is meaningless; keep them identical.
// ─────────────────────────────────────────────────────────────────────────
function visibility(incognito, network, vpn, era) {
  const onDevice = incognito
    ? { state: 'blind' }
    : { state: 'sees' };

  const website = { state: 'sees' };

  let google;
  if (!incognito) google = { state: 'sees' };
  else if (era === 'pre') google = { state: 'sees' };
  else google = { state: 'partial' };

  let isp;
  if (vpn) isp = { state: 'blind' };
  else isp = { state: 'partial' };

  let admin;
  if (network === 'home') admin = { state: 'na' };
  else if (network === 'work' || network === 'school') admin = vpn ? { state: 'partial' } : { state: 'sees' };
  else admin = vpn ? { state: 'blind' } : { state: 'sees' };

  return [
    { key: 'device', v: onDevice },
    { key: 'website', v: website },
    { key: 'google', v: google },
    { key: 'isp', v: isp },
    { key: 'admin', v: admin },
  ];
}

const NETWORKS = ['home', 'work', 'school', 'public'];
const BOOLS = [false, true];
const ERAS = ['pre', 'post'];

function stateOf(rows, key) { return rows.find(r => r.key === key).v.state; }

console.log('── model invariants (all 32 configurations) ─────────────────────');

// 1) On-device row is blind IFF Incognito is on — the one thing it does.
{
  let ok = true;
  for (const net of NETWORKS) for (const vpn of BOOLS) for (const era of ERAS) for (const inc of BOOLS) {
    const s = stateOf(visibility(inc, net, vpn, era), 'device');
    if ((s === 'blind') !== inc) ok = false;
  }
  check('on-device blind ⇔ incognito on', ok, true, 'across all 32 configs');
}

// 2) The website always sees you, in every configuration.
{
  let ok = true;
  for (const inc of BOOLS) for (const net of NETWORKS) for (const vpn of BOOLS) for (const era of ERAS) {
    if (stateOf(visibility(inc, net, vpn, era), 'website') !== 'sees') ok = false;
  }
  check('website always sees', ok, true, 'Incognito hides nothing from the far end');
}

// 3) ISP is PARTIAL without a VPN (domains/metadata, not contents), BLIND with one.
{
  let okNo = true, okVpn = true;
  for (const inc of BOOLS) for (const net of NETWORKS) for (const era of ERAS) {
    if (stateOf(visibility(inc, net, false, era), 'isp') !== 'partial') okNo = false;
    if (stateOf(visibility(inc, net, true, era), 'isp') !== 'blind') okVpn = false;
  }
  check('ISP = partial with no VPN', okNo, true, 'sees domains via DNS/SNI, not contents');
  check('ISP = blind with VPN', okVpn, true, 'trust relocated to the VPN operator');
}

// 4) Home network admin is n/a ("that's you"); work/school/public admin sees w/o VPN.
{
  let okHome = true, okInst = true;
  for (const inc of BOOLS) for (const vpn of BOOLS) for (const era of ERAS) {
    if (stateOf(visibility(inc, 'home', vpn, era), 'admin') !== 'na') okHome = false;
  }
  for (const inc of BOOLS) for (const era of ERAS) for (const net of ['work', 'school', 'public']) {
    if (stateOf(visibility(inc, net, false, era), 'admin') !== 'sees') okInst = false;
  }
  check('home admin = n/a (that is you)', okHome, true);
  check('work/school/public admin sees (no VPN)', okInst, true);
}

console.log('\n── the load-bearing count: rows the Incognito toggle changes ─────');

// 5) THE THESIS, COUNTED. Diff ON vs OFF for each (network, vpn, era).
//    pre-2024:  exactly 1 row changes — the on-device row.
//    2024+   :  exactly 2 rows change — on-device AND the third-party-cookie (google) row.
function flippedKeys(net, vpn, era) {
  const on = visibility(true, net, vpn, era);
  const off = visibility(false, net, vpn, era);
  const out = [];
  for (let i = 0; i < on.length; i++) if (on[i].v.state !== off[i].v.state) out.push(on[i].key);
  return out;
}
{
  let okPre = true, okPost = true;
  for (const net of NETWORKS) for (const vpn of BOOLS) {
    const pre = flippedKeys(net, vpn, 'pre');
    const post = flippedKeys(net, vpn, 'post');
    if (!(pre.length === 1 && pre[0] === 'device')) okPre = false;
    if (!(post.length === 2 && post.includes('device') && post.includes('google'))) okPost = false;
  }
  check('pre-2024: incognito flips exactly {device}', okPre, true, 'the whole thesis, counted');
  check('2024+: incognito flips exactly {device, google}', okPost, true, 'the settlement twist, counted');
}

console.log('\n── settlement arithmetic (cross-checked two ways) ───────────────');

// Sourced constants (see README.md).
const DAMAGES_SOUGHT = 5e9;   // $5B sought
const CLASS_CASH = 0;         // $0 to class
const CLASS_SIZE = 136e6;     // >136M people
const LODESTAR = 62e6;        // ~$62M lodestar (Bloomberg Law)
const MULTIPLIER = 3.5;       // 3.5x
const FEE_ASK = 217e6;        // ~$217M requested

// 6) Fee cross-check: lodestar × multiplier reproduces the reported ask.
approx('lodestar × 3.5 = fee ask', LODESTAR * MULTIPLIER, FEE_ASK, 6e6,
  '62M × 3.5 = 217M within rounding of the reported request');

// 7) $0-to-class made concrete: $5B ÷ 136M ≈ $36.76/head — and $0 actually paid.
const perHead = DAMAGES_SOUGHT / CLASS_SIZE;
approx('$5B ÷ 136M per head', perHead, 36.76, 0.1, 'the ~$37/head nobody received');
check('page rounds per-head to $37', Math.round(perHead), 37);
check('cash actually paid to class', CLASS_CASH, 0, 'relief was record destruction + injunctions');

// 8) Independent second route to the same per-head figure (unit sanity).
approx('per-head via reciprocal', 1 / (CLASS_SIZE / DAMAGES_SOUGHT), perHead, 1e-6);

console.log('\n────────────────────────────────────────────────────────────────');
if (failures === 0) {
  console.log('ALL CHECKS PASSED');
  process.exit(0);
} else {
  console.log(`${failures} CHECK(S) FAILED`);
  process.exit(1);
}
