// verify-why-horoscopes-feel-accurate-barnum-effect.mjs
// The check behind the stratum "The Reading Everyone Got"
// (/strata/why-horoscopes-feel-accurate-barnum-effect/).
//
// The page PERFORMS Bertram Forer's 1949 demonstration on the visitor: it hands
// them a warm, "personalized" reading whose substance is Forer's 13 verbatim
// statements (assembled 1948 from a newsstand astrology book), lets them rate it
// on Forer's own 0-5 scale, then proves the intake controls were decorative by
// re-running the SAME reading-generator on opposite inputs and getting
// byte-identical substantive text. Forer's 39 students rated the identical sketch
// a mean 4.26/5 (Forer, 1949).
//
// This script recomputes EVERY number the page shows, from first principles, and
// exits 0 only if all pass. Where possible it checks a quantity two independent
// ways. It also mirrors the page's reading-generator VERBATIM (the same source is
// pasted into index.html), so the twin-panel invariance is a real test, not an
// assertion.
//
//   run:  node research/why-horoscopes-feel-accurate-barnum-effect/verify-why-horoscopes-feel-accurate-barnum-effect.mjs
//
// Sources:
//   Forer, B. R. (1949). "The Fallacy of Personal Validation." J. Abnormal & Social
//     Psychology 44(1): 118-123.  N=39; one identical 13-statement sketch; mean 4.26/5.
//   Meehl, P. E. (1956). "Wanted, a Good Cookbook." American Psychologist 11(6): 263-272.
//     Coins the "Barnum effect."
//   Statements text: Skeptic's Dictionary (skepdic.com/forer.html); Wikipedia (orientation only,
//     whose 4.30 rendering conflicts with the 4.26 primary and is NOT the headline number here).
//
// No dependencies.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ══ SOURCE OF TRUTH (mirrors index.html) ═══════════════════════════════════
const FORER = [
  { text: "You have a great need for other people to like and admire you.", tag: "near-universal", uni: 90 },
  { text: "You have a tendency to be critical of yourself.", tag: "near-universal", uni: 85 },
  { text: "You have a great deal of unused capacity which you have not turned to your advantage.", tag: "vague-positive", uni: 88 },
  { text: "While you have some personality weaknesses, you are generally able to compensate for them.", tag: "vague-positive", uni: 86 },
  { text: "Your sexual adjustment has presented problems for you.", tag: "near-universal", uni: 75 },
  { text: "Disciplined and self-controlled outside, you tend to be worrisome and insecure inside.", tag: "double-headed", uni: 80 },
  { text: "At times you have serious doubts as to whether you have made the right decision or done the right thing.", tag: "near-universal", uni: 92 },
  { text: "You prefer a certain amount of change and variety and become dissatisfied when hemmed in by restrictions and limitations.", tag: "near-universal", uni: 84 },
  { text: "You pride yourself as an independent thinker and do not accept others' statements without satisfactory proof.", tag: "vague-positive", uni: 82 },
  { text: "You have found it unwise to be too frank in revealing yourself to others.", tag: "near-universal", uni: 78 },
  { text: "At times you are extroverted, affable, sociable, while at other times you are introverted, wary, reserved.", tag: "double-headed", uni: 93 },
  { text: "Some of your aspirations tend to be pretty unrealistic.", tag: "near-universal", uni: 76 },
  { text: "Security is one of your major goals in life.", tag: "near-universal", uni: 88 }
];

const FORER_N = 39;
const FORER_MEAN = 4.26;
const FORER_SUM = FORER_MEAN * FORER_N;   // = 166.14

const MONTHS = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const SIGNS  = ["Capricorn","Aquarius","Pisces","Aries","Taurus","Gemini","Cancer","Leo","Virgo","Libra","Scorpio","Sagittarius"];
const FOCI   = ["Love","Work","Purpose","Money"];

// ── THE READING GENERATOR (pasted verbatim from index.html) ─────────────────
function leanLabel(inp) { return inp.s[1] >= 50 ? "Thinking" : "Feeling"; }
function cosmeticOpener(inp) {
  const who = inp.name ? (inp.name + ", as ") : "As ";
  return who + "a " + MONTHS[inp.month] + " " + SIGNS[inp.month] + ", with your " +
    leanLabel(inp) + " lean and your focus on " + inp.focus +
    ", the reading came through with unusual clarity. ";
}
function cosmeticMid(inp) {
  return "Where " + inp.focus + " is concerned, the alignment is especially strong for you right now. ";
}
function cosmeticCloser(inp) {
  return "The heavens were unusually kind to " + SIGNS[inp.month] + " this month" +
    (inp.name ? ", " + inp.name : "") + ".";
}
function joinConnector() { return " "; }
function buildReading(inp) {
  const segments = [];
  const subParts = [];
  segments.push({ t: "cos", s: cosmeticOpener(inp) });
  for (let i = 0; i < FORER.length; i++) {
    const conn = (i === 0) ? "" : joinConnector();
    const s = conn + FORER[i].text;
    subParts.push(s);
    segments.push({ t: "sub", s: s, idx: i });
    if (i === 5) segments.push({ t: "cos", s: " " + cosmeticMid(inp) });
  }
  segments.push({ t: "cos", s: " " + cosmeticCloser(inp) });
  const cosmetic = segments.filter((x) => x.t === "cos").map((x) => x.s).join("|");
  return { substantive: subParts.join(""), cosmetic, segments };
}
function oppositeOf(inp) {
  return {
    month: (inp.month + 6) % 12,
    s: inp.s.map((v) => 100 - v),
    focus: FOCI[(FOCI.indexOf(inp.focus) + 2) % 4],
    name: ""
  };
}
function faPercent(d, f, v) {
  const raw = 12 + 0.30 * d + 0.26 * f + 0.30 * v;
  return Math.max(3, Math.min(98, Math.round(raw)));
}

// ══ 1. SOURCE LEDGER ═══════════════════════════════════════════════════════
console.log('\n— 1. source ledger: the 13 Forer statements —');
ok('exactly 13 statements', FORER.length === 13, `${FORER.length}`);
ok('every statement is non-empty', FORER.every((f) => f.text && f.text.length > 10));
ok('first statement is the classic "need to be liked" line',
   FORER[0].text === "You have a great need for other people to like and admire you.");
ok('the double-headed extrovert/introvert line is present verbatim',
   FORER[10].text === "At times you are extroverted, affable, sociable, while at other times you are introverted, wary, reserved.");
ok("Forer's constants pinned (N=39, scale 0..5, mean 4.26)",
   FORER_N === 39 && FORER_MEAN === 4.26, `N=${FORER_N}, mean=${FORER_MEAN}`);
const MEEHL_YEAR = 1956, MEEHL_TERM = "Barnum effect";
ok('naming: coined by Meehl in 1956 as the "Barnum effect"', MEEHL_YEAR === 1956 && MEEHL_TERM === "Barnum effect");

// ══ 2. ARITHMETIC OF THE MEAN ══════════════════════════════════════════════
console.log('\n— 2. arithmetic of the mean —');
ok('4.26 × 39 = 166.14 (implied rating sum)', approx(FORER_SUM, 166.14, 1e-9), `${FORER_SUM.toFixed(2)}`);
// 85% of the 195 maximum → overwhelmingly 4s-and-5s
const pctOfMax = FORER_SUM / (5 * FORER_N) * 100;
ok('mean is ~85% of the scale maximum (a 4s-and-5s skew)', approx(pctOfMax, 85.2, 0.1), `${pctOfMax.toFixed(1)}%`);
// the true integer sum nearest the rounded mean is 166 → mean 4.256 (rounds to 4.26)
ok('nearest integer rating sum (166) reproduces the rounded 4.26 mean',
   Math.round(166 / FORER_N * 100) / 100 === 4.26, `${(166 / FORER_N).toFixed(4)}`);

// the running mean, folded from Forer, TWO agreeing ways, for several ratings
console.log('  running mean = (166.14 + r) / 40, "Forer\'s 39 + you":');
for (const r of [0, 1, 2, 3, 4, 5]) {
  const wayA = (FORER_SUM + r) / (FORER_N + 1);
  const wayB = (FORER_N * FORER_MEAN + 1 * r) / (FORER_N + 1);
  console.log(`    r=${r}:  A=${wayA.toFixed(4)}  B=${wayB.toFixed(4)}`);
  ok(`running mean agrees two ways (r=${r})`, approx(wayA, wayB, 1e-12), `${wayA.toFixed(6)}`);
  ok(`pool mean stays near ~4.2 (r=${r})`, wayA >= 4.15 && wayA <= 4.28, `${wayA.toFixed(3)}`);
}
// the headline "you rated it 4/5" default
ok('default rating 4 folds to pool mean 4.2535', approx((FORER_SUM + 4) / 40, 4.2535, 1e-4), `${((FORER_SUM + 4) / 40).toFixed(4)}`);

// ══ 3. TWIN-PANEL INVARIANCE ═══════════════════════════════════════════════
console.log('\n— 3. twin-panel invariance: the controls are decorative —');
const trials = [
  { month: 6, s: [35, 68, 55, 42], focus: "Love", name: "Sam" },
  { month: 0, s: [0, 0, 0, 0], focus: "Money", name: "" },
  { month: 11, s: [100, 100, 100, 100], focus: "Work", name: "Alex" },
  { month: 3, s: [10, 90, 50, 20], focus: "Purpose", name: "Jo" }
];
for (const inp of trials) {
  const a = buildReading(inp);
  const b = buildReading(oppositeOf(inp));
  ok(`substantive byte-identical for opposite inputs (${MONTHS[inp.month]}/${inp.focus})`,
     a.substantive === b.substantive, `${a.substantive.length} chars`);
  ok(`cosmetic callbacks DO differ (${MONTHS[inp.month]}/${inp.focus})`,
     a.cosmetic !== b.cosmetic);
}
// the substantive text contains all 13 verbatim statements, in order
const ref = buildReading(trials[0]).substantive;
ok('the substantive reading contains all 13 statements verbatim',
   FORER.every((f) => ref.includes(f.text)));
// invariance across ALL 12 months × the 4 foci (exhaustive)
let allSame = true;
const base = buildReading({ month: 0, s: [50, 50, 50, 50], focus: "Love", name: "" }).substantive;
for (let m = 0; m < 12; m++) for (const focus of FOCI) for (const s of [[0,0,0,0],[100,100,100,100],[25,75,10,90]]) {
  if (buildReading({ month: m, s, focus, name: "X" }).substantive !== base) allSame = false;
}
ok('substantive text is invariant across all 12 months × 4 foci × slider extremes', allSame);

// ══ 4. BARNUM-INGREDIENT TAGGING ═══════════════════════════════════════════
console.log('\n— 4. ingredient tagging (audited against the source text) —');
const ALLOWED = new Set(["double-headed", "vague-positive", "near-universal"]);
const counts = { "double-headed": 0, "vague-positive": 0, "near-universal": 0 };
let oneEach = true;
for (const f of FORER) {
  if (!ALLOWED.has(f.tag)) oneEach = false; else counts[f.tag]++;
}
console.log(`    double-headed=${counts["double-headed"]}  vague-positive=${counts["vague-positive"]}  near-universal=${counts["near-universal"]}`);
ok('every clause carries exactly one of the three mechanisms', oneEach);
ok('counts sum to 13', counts["double-headed"] + counts["vague-positive"] + counts["near-universal"] === 13);
ok('double-headed count = 2', counts["double-headed"] === 2);
ok('vague-positive count = 3', counts["vague-positive"] === 3);
ok('near-universal count = 8', counts["near-universal"] === 8);
// per-clause universality bars are ESTIMATES in a sane band
ok('every universality estimate is in [50,99]', FORER.every((f) => f.uni >= 50 && f.uni <= 99));

// ══ 4b. BARNUM-BUILDER METER (stated toy model) ════════════════════════════
console.log('\n— 4b. the Barnum-builder meter (monotone; bounded) —');
ok('all dials at 0 → 12%', faPercent(0, 0, 0) === 12, `${faPercent(0,0,0)}`);
ok('all dials at 100 → 98% (clamped)', faPercent(100, 100, 100) === 98, `${faPercent(100,100,100)}`);
ok('midpoints (50/50/50) → 55%', faPercent(50, 50, 50) === 55, `${faPercent(50,50,50)}`);
// monotone non-decreasing in each dimension
let mono = true;
for (let x = 0; x <= 100; x += 5) {
  if (faPercent(x, 30, 30) < faPercent(x - 5 < 0 ? 0 : x - 5, 30, 30)) mono = false;
  if (faPercent(30, x, 30) < faPercent(30, x - 5 < 0 ? 0 : x - 5, 30)) mono = false;
  if (faPercent(30, 30, x) < faPercent(30, 30, x - 5 < 0 ? 0 : x - 5)) mono = false;
}
ok('meter is monotone non-decreasing in every dial', mono);
ok('a maximally accurate-feeling line beats a maximally specific one',
   faPercent(100, 100, 100) > faPercent(0, 0, 0));

// ══ 5. NUMBER HYGIENE (guard the Wikipedia 4.30 drift) ═════════════════════
console.log('\n— 5. number hygiene —');
ok('primary figure is 4.26', FORER_MEAN === 4.26);
ok('primary figure is NOT 4.30', FORER_MEAN !== 4.30);
// scan the shipped page: 4.26 must be present; the headline must not read 4.30 / 4.3
const HERE = path.dirname(fileURLToPath(import.meta.url));
const PAGE = path.resolve(HERE, '../../public/strata/why-horoscopes-feel-accurate-barnum-effect/index.html');
let html = '';
try { html = fs.readFileSync(PAGE, 'utf8'); } catch { /* optional */ }
if (html) {
  ok('page prints 4.26 (the primary figure)', html.includes('4.26'));
  // The spec ALLOWS mentioning Wikipedia's 4.30, but only as flagged tertiary drift,
  // never as the headline. So: (a) no 4.30 / bare 4.3 in any headline surface, and
  // (b) every 4.30 elsewhere sits next to a flag word (Wikipedia / tertiary / rounding / conflict).
  const headBlock = html.slice(0, html.indexOf('</head>'));
  ok('no 4.30 in any headline surface (title / meta / og / json-ld)', !headBlock.includes('4.30'));
  ok('no bare 4.3 in any headline surface', !/\b4\.3\b/.test(headBlock));
  ok('page never prints a bare 4.3 as a figure anywhere', !/\b4\.3\b/.test(html));
  const hits430 = [...html.matchAll(/4\.30/g)];
  ok('every 4.30 on the page is flagged as Wikipedia / tertiary drift (never the headline)',
     hits430.every((m) => /(Wikipedia|tertiary|rounding|conflict)/i.test(
       html.slice(Math.max(0, m.index - 130), m.index + 130))), `${hits430.length} mention(s)`);
  ok('4.26 is cited more than 4.30 (primary dominates)',
     (html.match(/4\.26/g) || []).length > hits430.length,
     `4.26×${(html.match(/4\.26/g) || []).length} vs 4.30×${hits430.length}`);
  ok('page labels the aggregate "Forer\'s 39 + you"', /Forer's 39 \+ you/.test(html));
  ok('page carries no fabricated global visitor count',
     !/[0-9][0-9,]{3,}\s*(visitors|readers|people rated)/i.test(html));
} else {
  ok('page file found for scan', false, PAGE);
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
