#!/usr/bin/env node
// Verifier for "The Dictionary That Eats Itself".
// Recomputes the page's headline numbers, from the shipped lexicon.json, using the
// SAME parse + graph code the page runs in the browser (copied verbatim below).
// Prints "<pass>/<total> PASS" and exits non-zero on any mismatch.
//
// Data: research/the-dictionary-that-eats-itself/lexicon.json
//   = the 1200 most-frequent single-word content headwords of Webster's Revised
//     Unabridged Dictionary (1913), each with its first-sense gloss trimmed to 30
//     whitespace tokens. Public domain (Project Gutenberg #660-#670; text parsed: #29765).
//
// Convention: LOOKUP direction. Edge A -> B means "B appears in A's definition"
//   (to understand A you must look up B). SCC is invariant under edge reversal;
//   the Kernel pruning removes words with no incoming edge (never used in any
//   surviving definition), which is the lookup-direction image of the paper's
//   "Recursively removing all words that are reachable by definition but that do not
//   define any further words."  (Vincent-Lamarre et al. 2016.)

import fs from 'node:fs';

// ─────────────────────────── shared parse (verbatim in page) ───────────────────────────
const STOP = new Set(("a an the of to in on at by for from with without within into onto upon over under "+
"and or but nor so yet as if then than that this these those it its it's is are was were be been being am "+
"has have had do does did will would shall should can could may might must not no nor "+
"i you he she we they him her them his hers our your their my me us "+
"which who whom whose what when where why how there here "+
"any some each every all both either neither one ones other others another same such more most less least "+
"very much many few little own out up down off about again also too only just even ever never "+
"etc esp e.g i.e viz cf ie eg per vs "+
"said see used using use also hence thus like unto according manner way ways thereof "+
"o.f oe l.  ").split(/\s+/).filter(Boolean));

function stripToken(t){ return t.toLowerCase().replace(/[^a-z]/g,''); }

function lemmaCandidates(w){
  const c=[w];
  if(w.length>3&&w.endsWith('ies'))c.push(w.slice(0,-3)+'y');
  if(w.length>3&&w.endsWith('es'))c.push(w.slice(0,-2),w.slice(0,-1));
  if(w.length>2&&w.endsWith('s')&&!w.endsWith('ss'))c.push(w.slice(0,-1));
  if(w.length>4&&w.endsWith('ing')){c.push(w.slice(0,-3),w.slice(0,-3)+'e');if(w[w.length-4]===w[w.length-5])c.push(w.slice(0,-4));}
  if(w.length>3&&w.endsWith('ed')){c.push(w.slice(0,-2),w.slice(0,-1));if(w[w.length-3]===w[w.length-4])c.push(w.slice(0,-3));}
  if(w.length>4&&w.endsWith('ly'))c.push(w.slice(0,-2));
  if(w.length>4&&w.endsWith('er'))c.push(w.slice(0,-2),w.slice(0,-1));
  if(w.length>5&&w.endsWith('est'))c.push(w.slice(0,-3),w.slice(0,-2));
  return c;
}

// definition text -> ordered, de-duplicated list of resolved headwords in the vocabulary
function edgesFrom(defText, vocab){
  const toks = defText.split(/[^A-Za-z]+/);
  const out=[]; const seen=new Set();
  for(const raw of toks){
    const t=stripToken(raw);
    if(!t||t.length<2) continue;
    if(STOP.has(t)) continue;
    let hit=null;
    for(const cand of lemmaCandidates(t)){ if(vocab.has(cand)){ hit=cand; break; } }
    if(hit && !seen.has(hit)){ seen.add(hit); out.push(hit); }
  }
  return out;
}

// build adjacency (lookup direction), dropping self-loops
function buildGraph(words, defs){
  const vocab=new Set(words);
  const adj={};
  for(const w of words) adj[w]=edgesFrom(defs[w]||'', vocab).filter(t=>t!==w);
  return { vocab, adj };
}

// Kernel: recursively delete nodes with in-degree 0 (never used in any surviving definition)
function computeKernel(words, adj){
  const alive=new Set(words);
  const indeg={}; words.forEach(w=>indeg[w]=0);
  for(const w of words) for(const t of adj[w]) indeg[t]++;
  const q=words.filter(w=>indeg[w]===0);
  while(q.length){
    const w=q.pop(); if(!alive.has(w)) continue; alive.delete(w);
    for(const t of adj[w]){ if(alive.has(t)){ indeg[t]--; if(indeg[t]===0) q.push(t); } }
  }
  return alive;
}

// Tarjan strongly-connected components (iterative)
function tarjanSCC(words, adj){
  let idx=0; const stack=[]; const onStack=new Set(); const num={}, low={}; const comps=[];
  for(const s of words){
    if(s in num) continue;
    const S=[[s,0]]; num[s]=low[s]=idx++; stack.push(s); onStack.add(s);
    while(S.length){
      const frame=S[S.length-1]; const node=frame[0];
      if(frame[1] < adj[node].length){
        const w=adj[node][frame[1]++];
        if(!(w in num)){ num[w]=low[w]=idx++; stack.push(w); onStack.add(w); S.push([w,0]); }
        else if(onStack.has(w)){ low[node]=Math.min(low[node], num[w]); }
      } else {
        if(low[node]===num[node]){
          const c=[]; let x;
          do{ x=stack.pop(); onStack.delete(x); c.push(x); }while(x!==node);
          comps.push(c);
        }
        S.pop();
        if(S.length){ const p=S[S.length-1][0]; low[p]=Math.min(low[p], low[node]); }
      }
    }
  }
  return comps;
}

// exact minimum feedback vertex set of a small induced subgraph; returns {k, sols[]}
function minFeedbackVertexSet(nodes, adj){
  const idx=new Map(nodes.map((w,i)=>[w,i]));
  const set=new Set(nodes);
  const E=[];
  for(const a of nodes) for(const b of adj[a]) if(set.has(b)) E.push([idx.get(a), idx.get(b)]);
  const n=nodes.length;
  function acyclic(removedMask){
    const alive=[]; for(let i=0;i<n;i++) if(!(removedMask&(1<<i))) alive.push(i);
    const aset=new Set(alive); const indeg={}, out={};
    alive.forEach(i=>{ indeg[i]=0; out[i]=[]; });
    for(const [a,b] of E){ if(aset.has(a)&&aset.has(b)){ indeg[b]++; out[a].push(b); } }
    const q=alive.filter(i=>indeg[i]===0); let cnt=0;
    while(q.length){ const x=q.pop(); cnt++; for(const y of out[x]){ indeg[y]--; if(indeg[y]===0) q.push(y); } }
    return cnt===alive.length;
  }
  for(let k=0;k<=n;k++){
    const sols=[];
    const comb=(start,chosen)=>{
      if(chosen.length===k){ let mask=0; chosen.forEach(i=>mask|=(1<<i)); if(acyclic(mask)) sols.push(chosen.map(i=>nodes[i])); return; }
      for(let i=start;i<n;i++){ chosen.push(i); comb(i+1,chosen); chosen.pop(); }
    };
    comb(0,[]);
    if(sols.length) return { k, sols };
  }
  return { k:0, sols:[[]] };
}

function inducedEdgeCount(nodes, adj){
  const set=new Set(nodes); let e=0;
  for(const a of nodes) for(const b of adj[a]) if(set.has(b)) e++;
  return e;
}

// deterministic greedy feedback vertex set over the whole graph (an UPPER BOUND, not the
// minimum): repeatedly remove the surviving node maximising in-degree*out-degree until the
// remaining graph is acyclic. Tie-break by vocabulary order. Same code runs on the page.
function isAcyclicSet(alive, adj){
  const out={}, indeg={};
  for(const w of alive){ out[w]=[]; indeg[w]=0; }
  for(const w of alive) for(const t of adj[w]) if(alive.has(t)) out[w].push(t);
  for(const w of alive) for(const t of out[w]) indeg[t]++;
  const q=[...alive].filter(w=>indeg[w]===0); let cnt=0;
  while(q.length){ const x=q.pop(); cnt++; for(const y of out[x]){ indeg[y]--; if(indeg[y]===0) q.push(y); } }
  return cnt===alive.size;
}
function greedyGroundingSet(words, adj){
  const alive=new Set(words); const removed=[];
  while(!isAcyclicSet(alive, adj)){
    const indeg={}, outdeg={};
    for(const w of alive){ indeg[w]=0; outdeg[w]=0; }
    for(const w of alive) for(const t of adj[w]) if(alive.has(t)){ outdeg[w]++; indeg[t]++; }
    let best=null, bs=-1;
    for(const w of words){ if(!alive.has(w)) continue; const s=indeg[w]*outdeg[w]; if(s>bs){ bs=s; best=w; } }
    alive.delete(best); removed.push(best);
  }
  return removed;
}

// ─────────────────────────── run ───────────────────────────
const L = JSON.parse(fs.readFileSync(new URL('./lexicon.json', import.meta.url)));
const { adj } = buildGraph(L.words, L.defs);

const nNodes = L.words.length;
let nEdges=0; for(const w of L.words) nEdges += adj[w].length;
const kernel = computeKernel(L.words, adj);
const comps = tarjanSCC(L.words, adj).sort((a,b)=>b.length-a.length);
const core = comps[0];
const nSCC = comps.length;

// reachable closure from the default seed "word" (lookup direction)
function closure(seed){
  const seen=new Set([seed]); const q=[seed];
  while(q.length){ const w=q.shift(); for(const t of adj[w]) if(!seen.has(t)){ seen.add(t); q.push(t); } }
  return seen;
}
const wordClosure = closure('word').size;

// curated MinSet subgraph
const CURATED = ['cause','effect','result','act','power','make'];
const curatedEdges = inducedEdgeCount(CURATED, adj);
const fvs = minFeedbackVertexSet(CURATED, adj);

// core leakiness + SCC gap + grounded sinks + greedy upper bound
const coreSet = new Set(core);
let coreOut=0, coreLeak=0;
for(const w of core) for(const t of adj[w]){ coreOut++; if(!coreSet.has(t)) coreLeak++; }
const coreStay = +(100 - coreLeak/coreOut*100).toFixed(1);
const secondSCC = comps[1] ? comps[1].length : 0;
const grounded = L.words.filter(w=>adj[w].length===0).length;
const greedy = greedyGroundingSet(L.words, adj).length;

// ─────────────────────────── assertions ───────────────────────────
const checks = [];
function eq(name, got, want){ checks.push({ name, got, want, ok: JSON.stringify(got)===JSON.stringify(want) }); }
function ok(name, cond, got){ checks.push({ name, got, want:'(property)', ok: !!cond }); }

// graph size (recomputed, must equal what the page shows)
eq('nodes (vocabulary size)', nNodes, 1200);
eq('edges (lookup-direction, deduped, no self-loops)', nEdges, 5607);
eq('kernel size (recursive in-degree-0 pruning)', kernel.size, 755);
eq('core = largest SCC (Tarjan)', core.length, 724);
eq('number of SCCs', nSCC, 471);

// SCC sanity: every core word reaches and is reached-from every other (definition of SCC).
// Spot-check strong connectivity by confirming the two-way reachability of a probe pair.
(function(){
  const coreSet=new Set(core);
  function reach(a){ const s=new Set([a]),q=[a]; while(q.length){const x=q.shift(); for(const t of adj[x]) if(coreSet.has(t)&&!s.has(t)){s.add(t);q.push(t);}} return s; }
  const A=core[0], B=core[core.length-1];
  const rA=reach(A);
  ok('core is strongly connected (probe A->B reachable within core)', rA.has(B), rA.has(B));
})();

// the trap: from "word" the lookups reach the entire Core and never bottom out
eq('word is in the Core', core.includes('word'), true);
ok('closure(word) engulfs the whole Core (>= core size)', wordClosure >= core.length, wordClosure);

// shares shown on the page
const coreOfNodes = +(core.length/nNodes*100).toFixed(1);
const coreOfKernel = +(core.length/kernel.size*100).toFixed(1);
eq('Core as % of vocabulary', coreOfNodes, 60.3);
eq('Core as % of Kernel', coreOfKernel, 95.9);

// curated grounding-set subgraph
eq('curated subgraph edge count', curatedEdges, 11);
eq('minimum grounding set size (min feedback vertex set)', fvs.k, 2);
eq('minimum grounding set is NON-UNIQUE (# of size-2 solutions)', fvs.sols.length, 3);
// the three solutions, order-independent
(function(){
  const norm = s => s.map(x=>x.slice().sort().join('+')).sort();
  const want = norm([['cause','act'],['cause','power'],['act','make']]);
  const got  = norm(fvs.sols);
  eq('the three minimal grounding sets', got, want);
})();

// every curated edge is a REAL Webster reference (target word occurs in source's shipped gloss)
(function(){
  const vocab=new Set(L.words);
  let allReal=true;
  for(const a of CURATED){
    for(const b of adj[a]){
      if(!CURATED.includes(b)) continue;
      const toks=edgesFrom(L.defs[a], vocab);
      if(!toks.includes(b)) allReal=false;
    }
  }
  ok('every curated edge is a genuine gloss reference', allReal, allReal);
})();

// the published figures are LABELS, not our computation — assert we are NOT claiming them
ok('our Core share (95.9% of kernel) differs from the published 75% (other corpora)', Math.abs(coreOfKernel-75)>5, coreOfKernel);

// core is a near-perfect trap: fraction of lookups from a Core word that stay in the Core
eq('% of Core lookups that stay inside the Core', coreStay, 98.6);
// the "one very large SCC" fact: the runner-up component is tiny
eq('second-largest SCC size (dwarfed by the Core)', secondSCC, 3);
// the escape hatches that are not real grounding
eq('apparent sinks (out-degree 0 in this slice)', grounded, 47);
// greedy grounding set over all 1,200 words: an explicit UPPER BOUND
eq('greedy grounding set (upper bound) size', greedy, 465);

// ─────────────────────────── report ───────────────────────────
let pass=0;
for(const c of checks){
  if(c.ok) pass++;
  const line = (c.ok?'PASS':'FAIL')+'  '+c.name+'  ->  got '+JSON.stringify(c.got)+(c.want==='(property)'?'':'  want '+JSON.stringify(c.want));
  console.log(line);
}
console.log('');
console.log(pass+'/'+checks.length+' PASS');
process.exit(pass===checks.length ? 0 : 1);
