#!/usr/bin/env node
// verify.mjs — The mirror flips depth, not left–right.
//
// Everything this page asserts is a statement about one 3×3 matrix and a few
// small bitmaps. No physics engine, no measurement — reflection in a plane is
// exactly a linear map, so the whole claim is checkable arithmetic. We recompute
// it here and the page recomputes the same things live.
//
// Run: node research/mirror-reversal/verify.mjs   (exit 0 = all pass)

let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  ✓ ${name}${detail ? ' — ' + detail : ''}`); }
  else { fail++; console.log(`  ✗ ${name}${detail ? ' — ' + detail : ''}`); }
}

// ---- tiny 3×3 matrix helpers (row-major, exact integer arithmetic) ----
const I = [[1,0,0],[0,1,0],[0,0,1]];
function mul(A, B) {
  const C = [[0,0,0],[0,0,0],[0,0,0]];
  for (let i=0;i<3;i++) for (let j=0;j<3;j++) for (let k=0;k<3;k++) C[i][j]+=A[i][k]*B[k][j];
  return C;
}
function apply(M, v){ return [0,1,2].map(i => M[i][0]*v[0]+M[i][1]*v[1]+M[i][2]*v[2]); }
function det3(M){
  return M[0][0]*(M[1][1]*M[2][2]-M[1][2]*M[2][1])
       - M[0][1]*(M[1][0]*M[2][2]-M[1][2]*M[2][0])
       + M[0][2]*(M[1][0]*M[2][1]-M[1][1]*M[2][0]);
}
function eq(A,B){ return JSON.stringify(A)===JSON.stringify(B); }
function cross(a,b){ return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]; }

console.log('\n=== The mirror flips depth, not left–right ===\n');

// Frame convention: x = your RIGHT, y = UP, z = FRONT (out of the mirror, toward you).
// A plane mirror you FACE lies in the x–y plane; its single normal is z (depth).
console.log('1. A plane mirror negates exactly one axis — the one perpendicular to it.');
const Mface = [[1,0,0],[0,1,0],[0,0,-1]];   // mirror you face: negate z (depth)
const Mfloor= [[1,0,0],[0,-1,0],[0,0,1]];   // mirror on the floor: negate y (up/down)
const Mside = [[-1,0,0],[0,1,0],[0,0,1]];   // mirror at your side: negate x (left/right)

check('mirror-you-face flips FRONT↔BACK only', eq(apply(Mface,[0,0,1]),[0,0,-1]) && eq(apply(Mface,[1,0,0]),[1,0,0]) && eq(apply(Mface,[0,1,0]),[0,1,0]),
      'RIGHT stays right, UP stays up, FRONT→back');
check('mirror-on-floor flips UP↔DOWN only', eq(apply(Mfloor,[0,1,0]),[0,-1,0]) && eq(apply(Mfloor,[1,0,0]),[1,0,0]),
      'a mirror underfoot reverses up/down, not left/right');
check('mirror-at-side flips LEFT↔RIGHT only', eq(apply(Mside,[1,0,0]),[-1,0,0]) && eq(apply(Mside,[0,1,0]),[0,1,0]),
      'so left/right is in no way special — it is whatever axis the mirror faces');
// the point made arithmetic: in the mirror-you-face, neither x nor y is touched.
check('facing a mirror, LEFT–RIGHT is left untouched', eq(apply(Mface,[1,0,0]),[1,0,0]),
      'the everyday "it swaps my left and right" is, literally, false');

// ---- determinant: orientation / chirality ----
console.log('\n2. Reflection reverses handedness (chirality) — a right hand maps to a left hand.');
for (const [name, M] of [['face',Mface],['floor',Mfloor],['side',Mside]]) {
  check(`det(mirror-${name}) = -1`, det3(M) === -1, 'orientation-reversing, so it cannot be a rotation (every rotation has det +1)');
}
// concretely: the standard right-handed basis maps to a LEFT-handed image.
// right-handed means e1×e2 = e3. After reflection, is (M e1)×(M e2) = +M e3 or −M e3?
{
  const e1=[1,0,0], e2=[0,1,0], e3=[0,0,1];
  const r1=apply(Mface,e1), r2=apply(Mface,e2), r3=apply(Mface,e3);
  const c = cross(r1,r2);                 // what the image's x,y demand for a right-handed z
  check('reflected frame is LEFT-handed', eq(c, r3.map(t=>-t)),
        '(image x)×(image y) = −(image z): the image obeys the left-hand rule');
}

// ---- the composition identity: where the "180° turn" hides ----
console.log('\n3. "It swaps left–right" = the SAME depth-flip, plus the half-turn YOU add to face the image.');
// You can't walk behind the glass, so to read the image "as a person" you mentally TURN.
// Which turn you make decides which axis you then blame. (x=right, y=up, z=front.)
const Ry180 = [[-1,0,0],[0,1,0],[0,0,-1]];   // turn in place about the VERTICAL (up) axis
const Rx180 = [[1,0,0],[0,-1,0],[0,0,-1]];   // a forward somersault about the HORIZONTAL (left-right) axis
const Rz180 = [[-1,0,0],[0,-1,0],[0,0,1]];   // a roll about the line of sight (the mirror's normal)
const P     = [[-1,0,0],[0,-1,0],[0,0,-1]];  // point inversion (full parity), det = -1
check('both turns are genuine rotations (det +1)', det3(Ry180)===1 && det3(Rx180)===1,
      'a real turn of your body, not a second mirror');
check('depth-flip + VERTICAL half-turn = a LEFT–RIGHT flip', eq(mul(Mface,Ry180), Mside),
      'Mface · Ry(180°) = Mside — turn in place to "face" the image and it reads left↔right reversed');
check('depth-flip + HORIZONTAL half-turn = an UP–DOWN flip', eq(mul(Mface,Rx180), Mfloor),
      'Mface · Rx(180°) = Mfloor — the somersault you never do would read up↔down reversed instead');
// same glass, opposite blame: left–right wins only because the vertical turn is the natural one.
check('reflection in a plane = point-inversion ∘ half-turn about its normal', eq(mul(P,Rz180), Mface),
      'Mface = P · Rz(180°): a clean group fact — every plane reflection factors this way');

// ---- the bitmap heart: why text "reverses" the way it does ----
console.log('\n4. A flat letter held to a mirror: which way it reads is the edge YOU flipped it about.');
// An asymmetric 5×5 glyph (a blocky 'R'), 1 = ink.
const R = [
  [1,1,1,1,0],
  [1,0,0,0,1],
  [1,1,1,1,0],
  [1,0,0,1,0],
  [1,0,0,0,1],
];
const flipX = g => g.map(row => [...row].reverse());          // flip about the VERTICAL edge → mirror-writing
const flipY = g => [...g].reverse();                          // flip about the HORIZONTAL edge → upside down
const rot180 = g => g.map(row => [...row].reverse()).reverse();
function gEq(a,b){ return JSON.stringify(a)===JSON.stringify(b); }
check('flipX ≠ flipY for an asymmetric glyph', !gEq(flipX(R), flipY(R)),
      'mirror-writing and upside-down are different images — the glass shows the back; you pick which');
check('flipX ∘ flipY = rotate 180°', gEq(flipX(flipY(R)), rot180(R)),
      'the two presentations differ by exactly a half-turn — the same half-turn from §3');
check('flipX(flipX(R)) = R and flipY(flipY(R)) = R', gEq(flipX(flipX(R)),R) && gEq(flipY(flipY(R)),R),
      'each reflection is its own inverse (involution)');

// ---- a 2-D sanity pass over MANY random glyphs (the identities are not a fluke of one R) ----
console.log('\n5. The flip identities hold for every bitmap, not just the R (deterministic sweep).');
{
  // a small LCG so the sweep is reproducible without Math.random()
  let s = 0x2545F491, N = 20000, allOK = true, anyAsym = 0;
  const rnd = () => (s = (s*1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
  for (let t=0;t<N;t++){
    const g = Array.from({length:4}, () => Array.from({length:4}, () => rnd()<0.5?1:0));
    if (!gEq(flipX(flipY(g)), rot180(g))) allOK = false;
    if (!gEq(flipX(g), flipY(g))) anyAsym++;
  }
  check(`flipX∘flipY = rot180 over ${N} random 4×4 glyphs`, allOK);
  check('most glyphs are flip-asymmetric (mirror-writing ≠ upside-down)', anyAsym > N*0.9,
        `${anyAsym}/${N} differ under the two flips`);
}

console.log(`\n${fail===0 ? 'ALL PASS' : 'FAILED'} — ${pass} passed, ${fail} failed.\n`);
process.exit(fail===0 ? 0 : 1);
