// verify-page.mjs — THE GENERATOR (Witness Marks weld) behavioural suite.
// Serve the repo root on :4400, then: node research/the-generator/verify-page.mjs
/* Resolve playwright portably, the house pattern (scripts/headless-check.mjs,
   research/before-you-looked/verify-page.mjs): this repo's package.json deliberately
   carries only astro, so a bare `from 'playwright'` dies in a clean checkout while a
   hardcoded /opt path dies everywhere the container is not that one. Try both. This
   file used the hardcoded path alone and so could not run at all; the 2026-08-01 sweep
   fixed thirteen like it and missed this one. A check that cannot run cannot fail. */
let chromium;
try { ({ chromium } = await import('playwright')); }
catch { ({ chromium } = (await import('/opt/node22/lib/node_modules/playwright/index.js')).default); }

// the live artifact is the deployed page; v3/ is a historical milestone snapshot.
const URL = process.env.GEN_URL || 'http://127.0.0.1:4400/public/instruments/generator/index.html';
let n = 0, bad = 0;
const ok = (name, cond, detail = '') => {
  n++;
  if (!cond) { bad++; console.error(`✗ ${name} ${detail}`); }
  else console.log(`✓ ${name}${detail ? ' — ' + detail : ''}`);
};
const close = (a, b, tol) => Math.abs(a - b) <= tol;

const browser = await chromium.launch();
for (const [label, vp] of [['desktop', { width: 1280, height: 850 }], ['mobile', { width: 390, height: 760 }]]) {
  const page = await browser.newPage({ viewport: vp });
  const errors = [];
  page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
  page.on('console', (m) => { if (m.type() === 'error' && !/Failed to load resource/.test(m.text())) errors.push(m.text()); });
  await page.goto(URL, { waitUntil: 'networkidle' });

  // ── the engine's numbers, live in the page ──
  ok(`${label}: __gen + __viz present`, await page.evaluate(() => !!window.__gen && !!window.__viz));
  const eq = await page.evaluate(() => window.__gen.scaleCents());
  ok(`${label}: equal scale exact`, eq.every((c, i) => close(c, i * 100, 1e-9)));
  const pure = await page.evaluate(() => window.__gen.circleError(1200 * Math.log2(3 / 2)));
  ok(`${label}: Pythagorean comma 23.46¢`, close(pure, 23.46001, 1e-4));
  const mt = await page.evaluate(() => window.__gen.thirdFromFifth(300 * Math.log2(5)));
  ok(`${label}: meantone third = pure 5:4`, close(mt, 1200 * Math.log2(5 / 4), 1e-9));
  const s5 = await page.evaluate(() => window.__gen.sjt(5));
  ok(`${label}: sjt(5) = 120, starts 12345→12354`, s5.count === 120 && s5.first === '12345' && s5.second === '12354');
  const periods = await page.evaluate(() => [window.__gen.period(3.2), window.__gen.period(3.835), window.__gen.period(3.9)]);
  ok(`${label}: periods 2 / 3 / chaos`, periods[0] === 2 && periods[1] === 3 && periods[2] === 0);
  const sp = await page.evaluate(() => window.__gen.sandpileCheck());
  ok(`${label}: sandpile conserves grains`, sp.conserved);
  const field = await page.evaluate(() => window.__gen.field ? [window.__gen.field.pinf(0.45), window.__gen.field.pinf(0.70)] : null);
  ok(`${label}: field P∞ snaps across p_c`, field && field[0] < 0.05 && field[1] > 0.4, field ? field.map((x) => x.toFixed(3)).join(' → ') : 'no field api');

  // ── six voices, presets, transport ──
  const voices = await page.evaluate(() => ['bells', 'pulse', 'grains', 'drone', 'field', 'drums'].every((v) =>
    document.getElementById('on-' + v) && document.getElementById('read-' + v)));
  ok(`${label}: all six voice controls present`, voices);

  // ── BASS (7th voice): Euclidean rhythm ──
  ok(`${label}: bass controls present (on-bass / read-bass / bk / bn)`, await page.evaluate(() =>
    !!(document.getElementById('on-bass') && document.getElementById('read-bass') &&
       document.getElementById('bk') && document.getElementById('bn'))));
  const tresillo = await page.evaluate(() => window.__gen.euclid(3, 8));
  ok(`${label}: __gen.euclid(3,8) is the tresillo [1,0,0,1,0,0,1,0]`,
    JSON.stringify(tresillo) === JSON.stringify([1, 0, 0, 1, 0, 0, 1, 0]));
  const cinq = await page.evaluate(() => window.__gen.euclid(5, 8));
  ok(`${label}: __gen.euclid(5,8) has 5 onsets`, cinq.reduce((a, b) => a + b, 0) === 5);
  await page.selectOption('#presetSel', 'machine');
  const bassArmed = await page.evaluate(() => { const s = window.__gen.state(); const b = window.__gen.bass();
    return s.on.bass === true && b.k === 3 && b.n === 8 && JSON.stringify(b.pattern) === JSON.stringify([1, 0, 0, 1, 0, 0, 1, 0]); });
  ok(`${label}: 'machine' preset arms BASS as E(3,8)`, bassArmed);

  // ── HARMONY (8th voice): neo-Riemannian triads on the Tonnetz ──
  ok(`${label}: harmony controls present (on-harmony / read-harmony / hcycle)`, await page.evaluate(() =>
    !!(document.getElementById('on-harmony') && document.getElementById('read-harmony') &&
       document.getElementById('hcycle'))));
  const cMaj = await page.evaluate(() => window.__gen.triadPCs(0, true));
  ok(`${label}: __gen.triadPCs(0,true) is the C-major triad [0,4,7]`,
    JSON.stringify(cMaj) === JSON.stringify([0, 4, 7]));

  await page.selectOption('#presetSel', 'fullset');
  const st = await page.evaluate(() => window.__gen.state());
  ok(`${label}: Full Set preset arms the set`, st.on.bells && st.on.pulse && st.on.grains && st.on.drone && st.on.bass);
  ok(`${label}: Full Set preset arms HARMONY`, st.on.harmony === true);
  // ── LEAD (9th voice): Per Nørgård's infinity series ──
  ok(`${label}: Full Set preset arms LEAD`, st.on.lead === true);
  ok(`${label}: lead controls present (on-lead / div-lead / tone-lead / read-lead)`, await page.evaluate(() =>
    !!(document.getElementById('on-lead') && document.getElementById('div-lead') && document.getElementById('tone-lead') && document.getElementById('read-lead'))));
  ok(`${label}: armed LEAD renders a note track (the ∞-series)`, await page.evaluate(() => {
    const t = window.__gen.renderTracks(4).find((x) => /LEAD/.test(x.name)); return !!t && t.notes > 0; }));
  await page.click('[data-hood="lead"]');
  ok(`${label}: lead hood shows the Nørgård ∞-series`, await page.evaluate(() => /series|u\(2n\)|N.rg.rd/i.test(document.getElementById('hoodNums').textContent)));
  await page.evaluate(() => { const h = document.getElementById('hood'); if (h) h.hidden = true; });

  // changing the cycle select updates the engine state
  await page.selectOption('#hcycle', '2');
  const hcyc = await page.evaluate(() => window.__gen.harmony().cycle);
  ok(`${label}: changing #hcycle updates harmony.cycle`, hcyc === 2);
  await page.selectOption('#presetSel', 'fullset');   // reset for the downstream live-clock checks
  await page.click('#play');
  await page.waitForTimeout(2200);
  const live = await page.evaluate(() => ({
    playing: window.__gen.state().playing,
    bells: document.getElementById('read-bells').textContent,
    counters: window.__gen.counters ? window.__gen.counters() : null,
  }));
  ok(`${label}: clock runs and bells advance`, live.playing && /row \d+/.test(live.bells));
  ok(`${label}: scope is drawing (non-blank canvas)`, await page.evaluate(() => {
    const cv = document.getElementById('scope');
    const ctx = cv.getContext('2d');
    const d = ctx.getImageData(0, 0, Math.min(80, cv.width), Math.min(60, cv.height)).data;
    let lit = 0; for (let i = 0; i < d.length; i += 4) if (d[i] + d[i + 1] + d[i + 2] > 30) lit++;
    return lit > 20;
  }));
  await page.click('#play');

  // ── share-URL round trip through a real reload ──
  await page.evaluate(() => {
    document.getElementById('rval').value = '3.835';
    document.getElementById('rval').dispatchEvent(new Event('input'));
  });
  await page.waitForTimeout(600); // debounce
  const hash = await page.evaluate(() => location.hash);
  ok(`${label}: state serialises to the URL`, hash.includes('v=2'));
  await page.goto(URL.split('#')[0] + hash, { waitUntil: 'networkidle' });
  const rBack = await page.evaluate(() => parseFloat(document.getElementById('rval').value));
  ok(`${label}: state restores after reload`, close(rBack, 3.835, 1e-6), String(rBack));

  // ── record control exists and toggles (state only; no download assert) ──
  const rec = await page.evaluate(async () => {
    const b = document.getElementById('record');
    if (!b) return 'no button';
    b.click(); await new Promise((r) => setTimeout(r, 400));
    const on = b.getAttribute('aria-pressed') === 'true' || b.classList.contains('on') || /stop|rec/i.test(b.textContent);
    b.click();
    return on ? 'toggles' : 'no toggle';
  });
  ok(`${label}: record toggles`, rec === 'toggles', rec);

  // ── v4: MIDI export + arrangement (scene chain) ──
  ok(`${label}: .mid + arrangement controls present`, await page.evaluate(() =>
    !!(document.getElementById('midi') && document.getElementById('arrCapture') &&
       document.getElementById('arrPlay') && document.getElementById('arrShare') &&
       document.getElementById('arrClear') && document.getElementById('arrList'))));
  await page.selectOption('#presetSel', 'fullset');
  const midi = await page.evaluate(() => { const b = window.__gen.midiBytes(8); return { len: b.length, head: b.slice(0, 4).join(',') }; });
  ok(`${label}: __gen.midiBytes() is a Standard MIDI File (MThd header)`, midi.head === '77,84,104,100' && midi.len > 100, `${midi.len} bytes`);
  const trks = await page.evaluate(() => window.__gen.renderTracks(4));
  ok(`${label}: render emits note tracks for armed voices, FIELD excluded`,
    trks.length >= 5 && trks.every((t) => t.notes > 0) && !trks.some((t) => /FIELD/.test(t.name)));
  const arr = await page.evaluate(() => {
    window.__gen.clearArr();
    window.__gen.captureScene();
    window.__gen.setFifth(1200 * Math.log2(3 / 2));   // make scene 2 differ
    window.__gen.captureScene();
    const enc = window.__gen.encodeArr(), dec = window.__gen.decodeArr(enc);
    return { count: window.__gen.arr().scenes, enc: enc.slice(0, 2), decLen: dec ? dec.length : 0, hash: location.hash.slice(0, 3) };
  });
  ok(`${label}: capture builds a 2-scene set; encodes "A|…"; round-trips; owns the URL`,
    arr.count === 2 && arr.enc === 'A|' && arr.decLen === 2 && arr.hash === '#A|');
  await page.evaluate(() => window.__gen.play(false));
  await page.click('#arrPlay');
  await page.waitForTimeout(900);
  const setLive = await page.evaluate(() => ({ playing: window.__gen.state().playing, arr: window.__gen.arr().playing }));
  ok(`${label}: play set runs the clock through the chain`, setLive.playing && setLive.arr);
  await page.click('#arrPlay');   // stop the set
  const setHash = await page.evaluate(() => { window.__gen.clearArr(); window.__gen.captureScene(); window.__gen.captureScene(); window.__gen.captureScene(); return location.hash; });
  await page.goto(URL.split('#')[0] + setHash, { waitUntil: 'networkidle' });
  const restored = await page.evaluate(() => window.__gen.arr().scenes);
  ok(`${label}: an arrangement link (#A|…) restores the whole set on reload`, restored === 3, String(restored));
  await page.evaluate(() => window.__gen.clearArr());

  // ── v5: reorder (↑/↓) + duplicate (⧉) act on ARR, visible via __gen.arr() ──
  const reorder = await page.evaluate(() => {
    window.__gen.clearArr();
    window.__gen.captureScene();                                  // scene 1 → 1 bar (default 4, then tag with bars)
    document.querySelector('#arrList .arr-scene:nth-child(1) [data-act="bars+"]').click();  // scene 1 → 5 bars (unique tag)
    window.__gen.captureScene();                                  // scene 2 → 4 bars
    const before = window.__gen.arr().bars.slice();               // [5, 4]
    document.querySelector('#arrList .arr-scene:nth-child(2) [data-act="up"]').click();     // move scene 2 earlier
    const after = window.__gen.arr().bars.slice();                // [4, 5]
    return { before, after };
  });
  ok(`${label}: ↑ reorders scenes (bars swap 5,4 → 4,5)`,
    JSON.stringify(reorder.before) === JSON.stringify([5, 4]) && JSON.stringify(reorder.after) === JSON.stringify([4, 5]),
    JSON.stringify(reorder));
  const dup = await page.evaluate(() => {
    const n0 = window.__gen.arr().scenes;                         // 2
    document.querySelector('#arrList .arr-scene:nth-child(1) [data-act="dup"]').click();    // clone scene 1 after it
    return { n0, bars: window.__gen.arr().bars.slice(), n1: window.__gen.arr().scenes };     // [4,4,5], 3
  });
  ok(`${label}: ⧉ duplicates a scene in place (2 → 3, clone right after)`,
    dup.n0 === 2 && dup.n1 === 3 && JSON.stringify(dup.bars) === JSON.stringify([4, 4, 5]),
    JSON.stringify(dup));
  ok(`${label}: loop toggle reflects ARR.loop via aria-pressed`, await page.evaluate(() => {
    const b = document.getElementById('arrLoop'); if (!b) return false;
    const on = b.getAttribute('aria-pressed');
    b.click(); const off = b.getAttribute('aria-pressed');
    b.click(); const back = b.getAttribute('aria-pressed');
    return on === 'true' && off === 'false' && back === 'true';
  }));
  await page.evaluate(() => window.__gen.clearArr());

  // ── tap tempo ──
  const tap = await page.evaluate(async () => {
    const b = document.getElementById('tap'); if (!b) return 'no button';
    b.click(); await new Promise((r) => setTimeout(r, 250)); b.click();
    const bpm = window.__gen.state().bpm;
    return (bpm >= 60 && bpm <= 200) ? 'ok:' + bpm : 'bad:' + bpm;
  });
  ok(`${label}: tap tempo sets a valid bpm`, tap.indexOf('ok') === 0, tap);

  // ── surprise (dice): a random state is always legal, non-silent, playable ──
  const dice = await page.evaluate(() => {
    const b = document.getElementById('dice'); if (!b) return 'no button';
    window.__gen.clearArr();
    b.click();
    const s = window.__gen.state();
    const on = ['bells', 'pulse', 'grains', 'drone', 'field', 'drums', 'bass', 'harmony'].filter((v) => s.on[v]).length;
    return (on >= 2 && on <= 5 && window.__gen.renderTracks(4).length >= 1) ? 'ok' : 'bad:' + on;
  });
  ok(`${label}: surprise rolls a legal, non-silent, playable state`, dice === 'ok', dice);
  await page.selectOption('#presetSel', 'fullset');   // restore a known state (the roll randomised everything)

  // ── WAV render: faithful offline bounce → a zip of master + stems, non-silent ──
  const wav = await page.evaluate(async () => {
    const b = await window.__gen.renderWavBytes(2);                       // 2 bars, fast
    if (!(b[0] === 0x50 && b[1] === 0x4b && b[2] === 0x03 && b[3] === 0x04)) return { pk: false };
    const nameLen = b[26] | (b[27] << 8);                                 // first entry = master.wav
    const pcm = 30 + nameLen + 44;                                        // local hdr + name + WAV hdr
    let sum = 0, nz = 0, count = 0;
    for (let i = pcm; i + 1 < b.length && count < 200000; i += 2) {
      let s = b[i] | (b[i + 1] << 8); if (s >= 32768) s -= 65536;
      sum += s * s; if (s !== 0) nz++; count++;
    }
    return { pk: true, len: b.length, rms: Math.sqrt(sum / Math.max(1, count)), nz };
  });
  ok(`${label}: wav render → a zip whose master PCM has real energy (not silence)`,
    wav.pk && wav.len > 2000 && wav.rms > 1 && wav.nz > 100, JSON.stringify({ len: wav.len, rms: Math.round(wav.rms || 0), nz: wav.nz }));
  ok(`${label}: instrument still plays after a render (globals restored)`, await page.evaluate(() => {
    window.__gen.play(true); const ok = window.__gen.state().playing === true; window.__gen.play(false); return ok;
  }));

  // ── per-voice timbre: the tone knob adds harmonics (brightness is audible, not cosmetic) ──
  ok(`${label}: tone sliders present on the free-timbre voices (pulse/bass/harmony)`, await page.evaluate(() =>
    !!(document.getElementById('tone-pulse') && document.getElementById('tone-bass') && document.getElementById('tone-harmony'))));
  const bright = await page.evaluate(async () => {
    window.__gen.clearArr();
    window.__gen.applyState(window.__gen.decodeState('#v=2&bpm=120&root=110&vol=70&f5=700&sw=0&bells=0,60,1,5&pulse=1,75,1,3.5,0&grains=0,55,1,4&drone=0,35,8&field=0,45,0.5927&drums=0,50,2&bass=0,50,1,3,8,0&harmony=0,50,2,0,0'));
    const slew = async () => {                          // L2 high-frequency-energy proxy of the master PCM
      const b = await window.__gen.renderWavBytes(2);
      const nameLen = b[26] | (b[27] << 8); let i = 30 + nameLen + 44, prev = 0, sl = 0, en = 0, c = 0;
      for (; i + 1 < b.length && c < 120000; i += 2) { let s = b[i] | (b[i + 1] << 8); if (s >= 32768) s -= 65536; const d = s - prev; sl += d * d; en += s * s; prev = s; c++; }
      return en > 0 ? sl / en : 0;
    };
    const t0 = await slew();
    const el = document.getElementById('tone-pulse'); el.value = 100; el.dispatchEvent(new Event('input'));
    const t100 = await slew();
    return { t0, t100 };
  });
  ok(`${label}: raising tone brightens the timbre — more harmonics ⇒ more high-frequency energy`,
    bright.t100 > bright.t0 * 1.2, JSON.stringify({ t0: +bright.t0.toFixed(3), t100: +bright.t100.toFixed(3) }));
  await page.selectOption('#presetSel', 'fullset');

  // ── hood (evidence) opens with real numbers ──
  await page.click('[data-hood="grains"]');
  ok(`${label}: grains hood shows the conservation ledger`, await page.evaluate(() =>
    !document.getElementById('hood').hidden && /conservation|shed/i.test(document.getElementById('hoodNums').textContent)));
  await page.click('[data-hood="drums"]');
  ok(`${label}: drums hood opens`, await page.evaluate(() => /spectrum|isospectral|Driscoll|GWW/i.test(document.getElementById('hoodNums').textContent + document.getElementById('hoodFree').textContent)));

  // ── keyboard shortcut ──
  await page.evaluate(() => document.activeElement && document.activeElement.blur());
  await page.keyboard.press('2');
  const pulseToggled = await page.evaluate(() => window.__gen.state().on.pulse === false);
  ok(`${label}: shortcut '2' toggles PULSE`, pulseToggled);
  await page.keyboard.press('2');
  await page.evaluate(() => { if (document.activeElement) document.activeElement.blur(); const h = document.getElementById('hood'); if (h) h.hidden = true; });
  await page.keyboard.press('e');
  ok(`${label}: shortcut 'e' opens the evidence hood`, await page.evaluate(() => !document.getElementById('hood').hidden));
  await page.keyboard.press('Escape');
  await page.evaluate(() => { if (document.activeElement) document.activeElement.blur(); });
  const leadB = await page.evaluate(() => window.__gen.state().on.lead);
  await page.keyboard.press('9');
  ok(`${label}: shortcut '9' toggles LEAD`, (await page.evaluate(() => window.__gen.state().on.lead)) !== leadB);
  await page.keyboard.press('9');

  // ── hygiene ──
  ok(`${label}: no horizontal overflow`, !(await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth + 1)));
  ok(`${label}: no JS errors`, errors.length === 0, errors.slice(0, 3).join(' | '));
  await page.screenshot({ path: `/tmp/v3-final-${label}.png`, fullPage: true });
  await page.close();
}
await browser.close();
console.log(`\n${n - bad}/${n} page checks passed${bad ? ' — FAILURES ABOVE' : ''}`);
process.exit(bad ? 1 : 0);
