// verify.mjs — recompute, from scratch, the central claim of the Dunning–Kruger
// "statistical artefact" critique: the famous scissors-shaped chart (low performers
// wildly overestimate, high performers slightly underestimate) is produced by
// pure statistics — regression to the mean, the autocorrelation of plotting the
// sorting variable on both axes, and the better-than-average shift — and appears
// even when self-assessment is STATISTICALLY INDEPENDENT of skill.
//
//   node research/dunning-kruger/verify.mjs
//
// This proves the artefact is real and large. It does NOT claim the psychological
// effect is zero — that is a live, unsettled question (see the apparatus below).
//
// Method: a seeded Monte Carlo over synthetic test-takers. Each of the five
// central model claims is recomputed here; the page runs the model live in the
// browser with one seed, while this verifier also runs ensembles. Fixed seeds
// make the numerical results reproducible.
//
// Sources (claims, not data — the data is synthetic and generated here):
//   Kruger, J. & Dunning, D. (1999). "Unskilled and Unaware of It." JPSP 77(6):
//     1121–1134. (The original effect; the quartile chart; the bottom-quartile
//     ~12th-percentile performers estimating ~62nd is the canonical summary.)
//   Krueger, J. & Mueller, R. A. (2002). "Unskilled, unaware, or both?" JPSP 82(2).
//     (Regression to the mean + better-than-average as the deflationary account.)
//   Nuhfer, E. et al. (2016, 2017). Numeracy. (With statistically valid measures
//     the strong asymmetry largely vanishes.)
//   Gignac, G. E. & Zajenkowski, M. (2020). "The Dunning–Kruger effect is (mostly)
//     a statistical artefact." Intelligence 80. (Autocorrelation; RTM+BTA explain
//     most of it; a small residual may remain.)

import { writeFileSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const HERE = dirname(fileURLToPath(import.meta.url));

let fails = 0;
const ok  = (name, cond, extra='') => { console.log((cond?'  ok   ':'  FAIL ')+name+(extra?'  '+extra:'')); if(!cond) fails++; };
const sec = (s) => console.log('\n=== '+s+' ===');
const r2 = (x) => Math.round(x*100)/100;
const r1 = (x) => Math.round(x*10)/10;

/* ───────────────────────── seeded PRNG + Gaussian ───────────────────────── */
// mulberry32 — small, fast, fully deterministic given the seed.
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;
  };
}
function makeGaussian(rng){
  // Box–Muller, one fresh pair per call (no cached state to keep it reentrant).
  return function(){
    let u = 0, v = 0;
    while (u === 0) u = rng();
    while (v === 0) v = rng();
    return Math.sqrt(-2*Math.log(u)) * Math.cos(2*Math.PI*v);
  };
}

/* ───────────────────────── the model ─────────────────────────
   N people. Each has a true latent ability a ~ N(0,1).
   actual test score   x = a + N(0, sTest^2)   → ranked to an ACTUAL PERCENTILE
                                                 (0..100), exactly as the studies
                                                 scored people.
   Each person SELF-REPORTS a percentile (the studies asked precisely this — "what
   percentile are you in?"). We model that self-report on the 0..100 scale as a blend
   between "no insight" (a flat 50) and "perfect insight" (your TRUE ability
   percentile), plus a uniform bias and reporting noise:
     perceived_pct = clamp( rho*truePct + (1-rho)*50 + bta + noiseP*G , 0, 100 )
   rho = how well you actually know your own ability (self-insight, 0..1):
         rho=0 → target 50 regardless of skill; rho=1 → target true ability
         percentile, before bias, reporting noise and clipping to 0-100.
         bta = the better-than-average shift in percentile points
         (raises the whole self-report line; +15 ≈ the average person says "65th").
   People are sorted into 4 quartiles by ACTUAL percentile; per quartile we average
   the perceived and actual percentiles. The chart is those two 4-point lines.
   The famous ASYMMETRY (low performers "more wrong" than high) emerges from the
   UNIVERSAL bias bta — not from any deficit special to the unskilled.            */
const NOISEP = 8;   // reporting noise around the self-report target, in pct points
function percentileRanks(vals){
  // rank-based percentile: position in the sorted sample, scaled to 0..100.
  const n = vals.length;
  const order = vals.map((v,i)=>[v,i]).sort((p,q)=>p[0]-q[0]);
  const pct = new Array(n);
  for (let k=0;k<n;k++){ pct[order[k][1]] = (n===1)?50 : (k/(n-1))*100; }
  return pct;
}
const clamp = (v,lo,hi)=> v<lo?lo : v>hi?hi : v;
function simulate({ N, rho, bta, sTest, seed }){
  const rng = mulberry32(seed);
  const G = makeGaussian(rng);
  const a = new Array(N), x = new Array(N);
  for (let i=0;i<N;i++){
    const ai = G();
    a[i] = ai;
    x[i] = ai + sTest*G();                                  // noisy test score
  }
  const ap = percentileRanks(a);     // TRUE ability percentile
  const xp = percentileRanks(x);     // ACTUAL (noisy) score percentile — sorts people
  const sp = new Array(N);           // perceived (self-reported) percentile
  for (let i=0;i<N;i++){
    sp[i] = clamp(rho*ap[i] + (1-rho)*50 + bta + NOISEP*G(), 0, 100);
  }
  // quartiles by actual percentile
  const idx = xp.map((v,i)=>[v,i]).sort((p,q)=>p[0]-q[0]).map(p=>p[1]);
  const q = [[],[],[],[]];
  for (let r=0;r<N;r++){ const Qn = Math.min(3, Math.floor(r/(N/4))); q[Qn].push(idx[r]); }
  const mean = (arr,f)=> arr.reduce((t,i)=>t+f(i),0)/arr.length;
  const perceived = q.map(g=>mean(g,i=>sp[i]));
  const actual    = q.map(g=>mean(g,i=>xp[i]));
  // overestimation = perceived - actual per quartile
  const gap = perceived.map((p,i)=>p-actual[i]);
  // autocorrelation slope: regress (perceived - actual) on actual, per person
  const px = xp, py = sp.map((v,i)=>v-xp[i]);
  const mx = mean([...Array(N).keys()], i=>px[i]);
  const my = mean([...Array(N).keys()], i=>py[i]);
  let sxy=0, sxx=0;
  for (let i=0;i<N;i++){ sxy += (px[i]-mx)*(py[i]-my); sxx += (px[i]-mx)*(px[i]-mx); }
  const slope = sxy/sxx;
  // Pearson r between actual and perceived percentile (the "true" relationship)
  const psp = sp; const msp = mean([...Array(N).keys()], i=>psp[i]);
  let cxy=0, cxx=0, cyy=0;
  for (let i=0;i<N;i++){ const dx=px[i]-mx, dy=psp[i]-msp; cxy+=dx*dy; cxx+=dx*dx; cyy+=dy*dy; }
  const rXY = cxy/Math.sqrt(cxx*cyy);
  return { perceived, actual, gap, slope, rXY };
}
// average a stat over many seeds; return mean and a rough 95% half-width.
function trials(params, nSeeds, pick){
  const xs = [];
  for (let t=0;t<nSeeds;t++) xs.push(pick(simulate({ ...params, seed: 1000+t })));
  const m = xs.reduce((a,b)=>a+b,0)/xs.length;
  const sd = Math.sqrt(xs.reduce((a,b)=>a+(b-m)*(b-m),0)/(xs.length-1));
  return { m, ci: 1.96*sd/Math.sqrt(xs.length), min: Math.min(...xs), max: Math.max(...xs) };
}

const N = 4000, SEEDS = 200;

/* ── C1. Independence (rho=0) STILL produces the scissors ───────────────────
   self-assessment is statistically independent of skill; everyone guesses around
   a better-than-average centre. The chart still shows low quartiles overestimating
   and high quartiles underestimating, robustly across 200 seeds.                */
sec('C1 — rho=0 (confidence INDEPENDENT of skill) still yields the scissors');
const p0 = { N, rho: 0, bta: 15, sTest: 0.5 };
const botGap0 = trials(p0, SEEDS, r=>r.gap[0]);
const topGap0 = trials(p0, SEEDS, r=>r.gap[3]);
const perceivedSlope0 = trials(p0, SEEDS, r=>(r.perceived[3]-r.perceived[0]));
const actualSlope0    = trials(p0, SEEDS, r=>(r.actual[3]-r.actual[0]));
ok('bottom quartile OVERestimates (perceived − actual > 0), every seed',
   botGap0.m>0 && botGap0.min>0, `gap = +${r1(botGap0.m)} ± ${r1(botGap0.ci)} pts  (min +${r1(botGap0.min)})`);
ok('top quartile UNDERestimates (perceived − actual < 0), every seed',
   topGap0.m<0 && topGap0.max<0, `gap = ${r1(topGap0.m)} ± ${r1(topGap0.ci)} pts  (max ${r1(topGap0.max)})`);
ok('perceived line is ~FLAT across quartiles (slope ≈ 0)',
   Math.abs(perceivedSlope0.m) < 3, `Δperceived(Q4−Q1) = ${r1(perceivedSlope0.m)} ± ${r1(perceivedSlope0.ci)} pts`);
ok('actual line RISES ~75 pts across quartiles (the staircase ~12.5→~87.5)',
   actualSlope0.m > 60, `Δactual(Q4−Q1) = ${r1(actualSlope0.m)} ± ${r1(actualSlope0.ci)} pts`);
// The famous ASYMMETRY (bottom "more wrong" than top) comes from the universal
// better-than-average shift, NOT a deficit special to the unskilled.
ok('asymmetry (|bottom gap| > |top gap|) emerges from the universal bta shift alone',
   Math.abs(botGap0.m) > Math.abs(topGap0.m) + 10,
   `|bottom| ${r1(Math.abs(botGap0.m))} > |top| ${r1(Math.abs(topGap0.m))} pts`);
// kill the shift → the scissors becomes symmetric (no special deficit anywhere)
const sym = { N, rho: 0, bta: 0, sTest: 0.5 };
const botSym = trials(sym, 80, r=>r.gap[0]), topSym = trials(sym, 80, r=>r.gap[3]);
ok('with bta=0 the scissors is SYMMETRIC (|bottom| ≈ |top|) — asymmetry was the bias',
   Math.abs(Math.abs(botSym.m) - Math.abs(topSym.m)) < 5,
   `|bottom| ${r1(Math.abs(botSym.m))} ≈ |top| ${r1(Math.abs(topSym.m))} pts`);

/* ── C2. The pattern's SIZE is governed by (1 − rho), not by any deficit ────
   Sweep how well people know their own ability. There is NO low-performer-specific
   term anywhere in the model — yet at rho=0 the scissors is wide and at rho=1 it
   closes. The asymmetry is a plotting geometry, not an asymmetric psychology.    */
sec('C2 — the scissors closes monotonically as self-insight rho → 1');
const sweep = [0, 0.25, 0.5, 0.75, 1.0];
let prevBot = Infinity, monotone = true;
const c2rows = [];
for (const rho of sweep){
  const bg = trials({ N, rho, bta: 15, sTest: 0.5 }, 60, r=>r.gap[0]);
  const rr = trials({ N, rho, bta: 15, sTest: 0.5 }, 60, r=>r.rXY);
  c2rows.push({ rho, botGap: r1(bg.m), rXY: r2(rr.m) });
  if (bg.m > prevBot + 0.5) monotone = false;     // allow tiny noise
  prevBot = bg.m;
  console.log(`     rho=${rho.toFixed(2)}:  bottom-quartile overestimation = +${r1(bg.m)} pts   (true corr r=${r2(rr.m)})`);
}
ok('bottom-quartile overestimation shrinks monotonically as rho rises', monotone);
// with the bias present (bta=15) perfect insight still leaves the bias — so to show
// the scissors fully CLOSING, remove the bias too: rho=1, bta=0, a clean test.
const closed = trials({ N, rho: 1, bta: 0, sTest: 0.25 }, 60, r=>r.gap[0]);
ok('rho=1 AND bta=0 (perfect insight, no bias): the scissors essentially closes',
   Math.abs(closed.m) < 8, `bottom gap = ${r1(closed.m)} pts (only residual RTM from test noise)`);

/* ── C3. Autocorrelation: the famous "skill ↔ overconfidence" slope is built in ─
   Regress overestimation (perceived − actual) on actual. With perceived ⟂ actual,
   the slope is −1 BY CONSTRUCTION: actual sits on both axes with opposite sign.
   This is the Gignac & Zajenkowski / "autocorrelation" objection, made literal.  */
sec('C3 — autocorrelation: regress (perceived−actual) on actual → slope ≈ −1');
const slope0 = trials({ N, rho: 0, bta: 15, sTest: 0.5 }, SEEDS, r=>r.slope);
ok('slope ≈ −1 even though perceived is pure noise (the artefact is in the axes)',
   Math.abs(slope0.m + 1) < 0.05, `slope = ${r2(slope0.m)} ± ${r2(slope0.ci)}`);
const rXY0 = trials({ N, rho: 0, bta: 15, sTest: 0.5 }, SEEDS, r=>r.rXY);
ok('…while the HONEST correlation between actual & perceived is ≈ 0',
   Math.abs(rXY0.m) < 0.04, `Pearson r(actual,perceived) = ${r2(rXY0.m)} ± ${r2(rXY0.ci)}`);

/* ── C4. Regression to the mean ALONE (symmetric, unbiased self-assessor) ───
   No better-than-average shift (b=0), and self-assessment is an UNBIASED noisy
   reading of true ability with the SAME noise at every skill level. The chart
   still bows: bottom overestimates, top underestimates — pure RTM, because the
   quartiles are cut on the noisy actual score whose extremes regress.            */
sec('C4 — regression to the mean alone (b=0, symmetric noise) still bows the chart');
const p4 = { N, rho: 0.6, bta: 0, sTest: 0.7 };   // symmetric, unbiased, partial insight
const botGap4 = trials(p4, SEEDS, r=>r.gap[0]);
const topGap4 = trials(p4, SEEDS, r=>r.gap[3]);
ok('bottom still overestimates with a perfectly symmetric model',
   botGap4.m > 0 && botGap4.min > 0, `gap = +${r1(botGap4.m)} ± ${r1(botGap4.ci)} pts`);
ok('top still underestimates with a perfectly symmetric model',
   topGap4.m < 0 && topGap4.max < 0, `gap = ${r1(topGap4.m)} ± ${r1(topGap4.ci)} pts`);

/* ── C5. The artefact reproduces the published shape ────────────────────────
   With rho=0 and a realistic better-than-average shift, the bottom quartile lands
   tens of percentile points above its actual ~12th, and the top dips a little
   below — the qualitative shape of the K&D figure, from no real relationship.    */
sec('C5 — the artefact matches the published qualitative shape');
const shape = simulate({ ...p0, seed: 1234 });
console.log('     quartile chart (rho=0, bta=15):');
console.log('       Q1(bottom)  perceived '+r1(shape.perceived[0])+'   actual '+r1(shape.actual[0]));
console.log('       Q2          perceived '+r1(shape.perceived[1])+'   actual '+r1(shape.actual[1]));
console.log('       Q3          perceived '+r1(shape.perceived[2])+'   actual '+r1(shape.actual[2]));
console.log('       Q4(top)     perceived '+r1(shape.perceived[3])+'   actual '+r1(shape.actual[3]));
ok('bottom quartile lands well above its actual (tens of points)',
   shape.perceived[0]-shape.actual[0] > 25, `bottom perceived ${r1(shape.perceived[0])} vs actual ${r1(shape.actual[0])}`);
ok('lines CROSS once, near the middle (the scissors pivot)',
   (shape.perceived[0]-shape.actual[0])>0 && (shape.perceived[3]-shape.actual[3])<0);

/* ───────────────────────── emit the artefact ───────────────────────── */
const artefact = {
  generated: new Date().toISOString().slice(0,10),
  model: 'a~N(0,1); actual score x=a+N(0,sTest^2) ranked to percentile xp; true ability percentile ap=rank(a); perceived=clamp(rho*ap+(1-rho)*50+bta+N(0,8^2),0,100); quartiles cut on xp',
  N, seeds: SEEDS,
  c1_independence: {
    params: p0,
    bottomGap_pts: r1(botGap0.m), bottomGap_ci: r1(botGap0.ci), bottomGap_min: r1(botGap0.min),
    topGap_pts: r1(topGap0.m), topGap_ci: r1(topGap0.ci), topGap_max: r1(topGap0.max),
    perceivedSlope_pts: r1(perceivedSlope0.m), actualSlope_pts: r1(actualSlope0.m),
  },
  c2_sweep: c2rows,
  c3_autocorrelation: { slope: r2(slope0.m), honest_r: r2(rXY0.m) },
  c4_rtm_only: { bottomGap_pts: r1(botGap4.m), topGap_pts: r1(topGap4.m) },
  c5_shape: {
    perceived: shape.perceived.map(r1), actual: shape.actual.map(r1),
  },
  canonical_original: { source: 'Kruger & Dunning 1999', bottom_quartile_actual_pct: 12, bottom_quartile_perceived_pct: 62 },
  pass: null,
};
artefact.pass = fails === 0;
const out = join(HERE, 'artefact.json');
writeFileSync(out, JSON.stringify(artefact, null, 2));
// mirror to the reader-facing copy so the page's proof link resolves on the live site
try { writeFileSync(join(HERE, '..', '..', 'public', 'research', 'dunning-kruger', 'artefact.json'), JSON.stringify(artefact, null, 2)); } catch {}

sec('SUMMARY');
console.log(fails === 0
  ? `  ✓ all checks passed — the scissors is reproduced from pure statistics. Artefact → ${out}`
  : `  ✗ ${fails} check(s) FAILED`);
process.exit(fails === 0 ? 0 : 1);
