// verify.mjs: the check for the-clock-inside-your-archive.
//
// Runs offline from committed data, no network:
//   node research/the-clock-inside-your-archive/verify.mjs
// Fire the planted corruptions:
//   node research/the-clock-inside-your-archive/verify.mjs --mutate

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import * as E from './engine.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const SLUG = 'the-clock-inside-your-archive';
const PAGE_PATH = join(ROOT, 'public', 'strata', SLUG, 'index.html');
const ENGINE_COPY = join(ROOT, 'public', 'strata', SLUG, 'engine.mjs');
const MD_PATH = join(ROOT, 'src', 'content', 'strata', SLUG + '.md');

let pass = 0;
let fail = 0;
function ok(label, cond){
  if(cond){ pass += 1; console.log('  pass  ' + label); }
  else { fail += 1; console.log('  FAIL  ' + label); }
}
function heading(t){ console.log('\n' + t); }
const deepEq = (a, b) => JSON.stringify(a) === JSON.stringify(b);
const throws = (fn) => { try { fn(); return false; } catch { return true; } };

// ---------- a tiny zip writer, stored entries only ----------

const bytesOf = (s) => Array.from(new TextEncoder().encode(s));
function pushU16(a, v){ a.push(v & 255, (v >>> 8) & 255); }
function pushU32(a, v){ a.push(v & 255, (v >>> 8) & 255, (v >>> 16) & 255, (v >>> 24) & 255); }

const CRC_TABLE = (() => {
  const t = new Uint32Array(256);
  for(let n = 0; n < 256; n++){
    let c = n;
    for(let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1);
    t[n] = c >>> 0;
  }
  return t;
})();
function crc32(list){
  let c = 0xFFFFFFFF;
  for(const b of list) c = CRC_TABLE[(c ^ b) & 255] ^ (c >>> 8);
  return (c ^ 0xFFFFFFFF) >>> 0;
}

// A real writer floors the wall second to even before packing the time word.
function dosWords(wall){
  const [y, mo, d, h, mi, s] = wall;
  const secs = Math.floor(s / 2);
  return {
    time: (secs & 31) | ((mi & 63) << 5) | ((h & 31) << 11),
    date: (d & 31) | ((mo & 15) << 5) | (((y - 1980) & 127) << 9),
  };
}

// specs: { name, content, wall:[y,mo,d,h,mi,s], ut (epoch or null/undefined),
// timeWord/dateWord optional overrides for corruption experiments }
function buildZip(specs, comment = ''){
  const out = [];
  const central = [];
  for(const sp of specs){
    const name = bytesOf(sp.name);
    const data = bytesOf(sp.content);
    const crc = crc32(data);
    const lho = out.length;
    pushU32(out, 0x04034b50); pushU16(out, 20); pushU16(out, 0); pushU16(out, 0);
    pushU32(out, crc); pushU32(out, data.length); pushU32(out, data.length);
    pushU16(out, name.length); pushU16(out, 0);
    out.push(...name, ...data);

    const w = dosWords(sp.wall);
    const timeWord = sp.timeWord ?? w.time;
    const dateWord = sp.dateWord ?? w.date;
    const extra = [];
    if(sp.ut !== null && sp.ut !== undefined){
      pushU16(extra, 0x5455); pushU16(extra, 5);
      extra.push(1); // flags: modification time present
      pushU32(extra, sp.ut >>> 0);
    }

    pushU32(central, 0x02014b50); pushU16(central, 0x031e); pushU16(central, 20);
    pushU16(central, 0); pushU16(central, 0);
    pushU16(central, timeWord); pushU16(central, dateWord);
    pushU32(central, crc); pushU32(central, data.length); pushU32(central, data.length);
    pushU16(central, name.length); pushU16(central, extra.length); pushU16(central, 0);
    pushU16(central, 0); pushU16(central, 0); pushU32(central, 0); pushU32(central, lho);
    central.push(...name, ...extra);
  }
  const cdOffset = out.length;
  out.push(...central);
  const cdSize = out.length - cdOffset;
  const cb = bytesOf(comment);
  pushU32(out, 0x06054b50); pushU16(out, 0); pushU16(out, 0);
  pushU16(out, specs.length); pushU16(out, specs.length);
  pushU32(out, cdSize); pushU32(out, cdOffset);
  pushU16(out, cb.length);
  out.push(...cb);
  return Uint8Array.from(out);
}

// ---------- fixtures, each with a planted offset ----------

// Wall-clock epoch minus the planted offset: what a sincere writer stored.
const U = (w, off) => Date.UTC(w[0], w[1] - 1, w[2], w[3], w[4], w[5]) / 1000 - off;

const OFF_A = 7200; // UTC+02:00
const A_SPECS = [
  { name: 'readme.txt',      content: 'a greeting\n', wall: [2026, 8, 24, 14, 3, 46] },
  { name: 'src/main.mjs',    content: 'export {};\n', wall: [1999, 12, 31, 23, 59, 58] },
  { name: 'img/logo.png',    content: 'pngbytes\n',   wall: [2020, 2, 29, 0, 0, 0] },
  { name: 'data.csv',        content: 'a,b\n1,2\n',   wall: [1980, 1, 1, 0, 0, 2] },
  { name: 'notes/ideas.txt', content: 'more later\n', wall: [2038, 1, 19, 3, 14, 6] },
  { name: 'hello.txt',       content: 'hi\n',         wall: [2001, 9, 9, 3, 46, 40] },
].map((s) => ({ ...s, ut: U(s.wall, OFF_A) }));
const bufA = buildZip(A_SPECS);

const B_SPECS = [
  { name: 'a.txt', content: 'x\n', wall: [2021, 6, 15, 12, 34, 37] },
  { name: 'b.txt', content: 'y\n', wall: [2021, 6, 15, 12, 35, 39] },
  { name: 'c.txt', content: 'z\n', wall: [2021, 6, 16, 8, 0, 1] },
].map((s) => ({ ...s, ut: U(s.wall, OFF_A) }));
const bufB = buildZip(B_SPECS);

const C_SPECS = [
  { name: 'one.txt',   content: '1\n', wall: [2010, 5, 5, 5, 5, 6] },
  { name: 'two.txt',   content: '2\n', wall: [2011, 7, 7, 7, 7, 8] },
  { name: 'three.txt', content: '3\n', wall: [2012, 2, 2, 2, 2, 4] },
];
const bufC = buildZip(C_SPECS); // no extended timestamps at all

const D_SPECS = [
  { name: 'd1.txt', content: '1\n', wall: [2015, 3, 3, 3, 3, 2], ut: U([2015, 3, 3, 3, 3, 2], 7200) },
  { name: 'd2.txt', content: '2\n', wall: [2015, 3, 4, 4, 4, 4], ut: U([2015, 3, 4, 4, 4, 4], 7200) },
  { name: 'd3.txt', content: '3\n', wall: [2015, 3, 5, 5, 5, 6], ut: U([2015, 3, 5, 5, 5, 6], -12600) },
  { name: 'd4.txt', content: '4\n', wall: [2015, 3, 6, 6, 6, 8], ut: U([2015, 3, 6, 6, 6, 8], -12600) },
];
const bufD = buildZip(D_SPECS);

const E_SPECS = [
  { name: 'e1.txt', content: '1\n', wall: [2018, 4, 4, 4, 4, 2], ut: U([2018, 4, 4, 4, 4, 2], 3600) },
  { name: 'e2.txt', content: '2\n', wall: [2018, 4, 5, 5, 5, 4], ut: U([2018, 4, 5, 5, 5, 4], 3600) },
  { name: 'e3.txt', content: '3\n', wall: [2018, 4, 6, 6, 6, 6], ut: U([2018, 4, 6, 6, 6, 6], 3600) },
];
// 300-byte trailing comment whose body contains a forged EOCD signature.
const TRAP_COMMENT = 'PK\x05\x06' + 'z'.repeat(294);
const bufE = buildZip(E_SPECS, TRAP_COMMENT);

// Corrupted input variants for the negative controls.
const bufA_min = buildZip(A_SPECS.map((s, i) =>
  i === 0 ? { ...s, timeWord: dosWords(s.wall).time ^ 0x0020 } : s)); // minute 3 becomes 2
const bufA_ut = buildZip(A_SPECS.map((s, i) =>
  i === 0 ? { ...s, ut: s.ut + 450 } : s)); // pushed off the quarter-hour grid

function patchEocdTotal(buf, val){
  const b = Uint8Array.from(buf);
  for(let i = b.length - 22; i >= 0; i--){
    if(b[i] === 0x50 && b[i + 1] === 0x4b && b[i + 2] === 0x05 && b[i + 3] === 0x06){
      new DataView(b.buffer).setUint16(i + 10, val, true);
      return b;
    }
  }
  throw new Error('no EOCD to patch');
}
const bufA_cnt = patchEocdTotal(bufA, 99); // the EOCD now lies about the count

// ---------- sections ----------

heading('engine copies are byte-identical');
const engResearch = readFileSync(join(HERE, 'engine.mjs'));
const engPublic = readFileSync(ENGINE_COPY);
ok('public/strata/' + SLUG + '/engine.mjs is byte-identical to research/' + SLUG + '/engine.mjs', engResearch.equals(engPublic));

heading('unit: DOS words and the calendar');
ok('date word 0x5D18 and time word 0x90F6 decode to 2026-08-24T18:07:44', deepEq(E.decodeDos(0x5D18, 0x90F6), { y: 2026, mo: 8, d: 24, h: 18, mi: 7, s: 44 }));
let allEven = true;
for(let w = 0; w < 65536; w++){ if(E.decodeDos(0x5D18, w).s % 2 !== 0){ allEven = false; break; } }
ok('all 65536 possible time words decode to an even second, so odd_second_count can only be 0', allEven);
ok('the calendar renders Unix time 1000000000 as 2001-09-09 01:46:40 UTC, the published 1e9 milestone', deepEq(E.civilFromEpoch(1000000000), { y: 2001, mo: 9, d: 9, h: 1, mi: 46, s: 40 }));
ok('epochFromCivil inverts civilFromEpoch across negative, zero and post-2038 instants', [-1, 0, 86399, -86400, 951782400, 1000000000, 2147483646, 4102444800].every((t) => E.epochFromCivil(E.civilFromEpoch(t)) === t));
ok('analyzing bytes with no zip structure throws instead of inventing entries', throws(() => E.analyzeZip(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))));

heading('fixture A: an archive planted at UTC+02:00');
const ra = E.analyzeZip(bufA);
ok('n_entries is 6', ra.n_entries === 6);
ok('n_with_ext_timestamp is 6', ra.n_with_ext_timestamp === 6);
ok('every entry recovers exactly the planted offset 7200', deepEq(ra.entries.map((e) => e.consistent_offsets), [[7200], [7200], [7200], [7200], [7200], [7200]]));
ok('the intersection is exactly [7200]', deepEq(ra.intersection, [7200]));
ok('the verdict is unique', ra.verdict === 'unique');
ok('odd_second_count is 0', ra.odd_second_count === 0);
ok('readme.txt carries the DOS string 2026-08-24T14:03:46', ra.entries[0].dos === '2026-08-24T14:03:46');
// Derived from the fixture itself: hello.txt was written at wall 2001-09-09
// 03:46:40 in UTC+02:00, so the stored instant is 2001-09-09 01:46:40 UTC,
// which is exactly Unix time 1000000000. The old expectation of 999992800
// subtracted 7200 twice; the fixture expectation was wrong, not the engine.
ok('hello.txt carries utc 1000000000, the 1e9 milestone seen through the +02:00 wall clock', ra.entries[5].utc === 1000000000);
ok('every utc equals its wall epoch minus the planted 7200', deepEq(ra.entries.map((e) => e.utc), A_SPECS.map((s) => U(s.wall, 7200))));
ok('the leap-day entry survived intact as 2020-02-29T00:00:00', ra.entries[2].dos === '2020-02-29T00:00:00');

heading('fixture B: a writer who saw odd seconds');
// Re-derived from the specification: an offset o is consistent when the UTC
// instant shifted by o, rendered as wall clock with its seconds field
// truncated to the next lower even number, equals the DOS stamp. A writer who
// saw 12:34:37 and stored 12:34:36 is CONSISTENT under that rule, because the
// truncation is exactly what the format does. The old expectations of empty
// survivors, an empty intersection and an inconsistent verdict were wrong;
// the engine was right. Each entry here recovers the planted 7200 alone.
const rb = E.analyzeZip(bufB);
ok('the DOS stamps are the floored readings, 12:34:37 stored as 12:34:36', rb.entries[0].dos === '2021-06-15T12:34:36');
ok('every entry survives with exactly the planted offset 7200 despite odd wall seconds', deepEq(rb.entries.map((e) => e.consistent_offsets), [[7200], [7200], [7200]]));
ok('the intersection is exactly [7200]', deepEq(rb.intersection, [7200]));
ok('the verdict is unique', rb.verdict === 'unique');
ok('n_with_ext_timestamp is 3', rb.n_with_ext_timestamp === 3);

heading('fixture C: no extended timestamps at all');
const rc = E.analyzeZip(bufC);
ok('n_with_ext_timestamp is 0', rc.n_with_ext_timestamp === 0);
ok('every utc is null', deepEq(rc.entries.map((e) => e.utc), [null, null, null]));
ok('the intersection is empty', deepEq(rc.intersection, []));
ok('the verdict is insufficient', rc.verdict === 'insufficient');

heading('fixture D: entries added from two different offsets');
const rd = E.analyzeZip(bufD);
ok('entries vote for their own rooms: 7200, 7200, -12600, -12600', deepEq(rd.entries.map((e) => e.consistent_offsets), [[7200], [7200], [-12600], [-12600]]));
ok('the intersection is empty', deepEq(rd.intersection, []));
ok('the verdict is inconsistent', rd.verdict === 'inconsistent');

heading('fixture E: a forged EOCD signature inside a 300-byte comment');
const re_ = E.analyzeZip(bufE);
ok('the scanner rejects the forgery and finds the real EOCD, n_entries is 3', re_.n_entries === 3);
ok('the planted offset 3600 is recovered alone', deepEq(re_.intersection, [3600]));
ok('the verdict is unique', re_.verdict === 'unique');

heading('independent reference: a slow Date-based checker beside the fast integer one');
const REF_CANDS = [];
for(let o = -43200; o <= 50400; o += 900) REF_CANDS.push(o);
function refConsistent(Ut, dos, o){
  const d = new Date((Ut + o) * 1000);
  const s = d.getUTCSeconds();
  return d.getUTCFullYear() === dos.y && d.getUTCMonth() + 1 === dos.mo && d.getUTCDate() === dos.d &&
    d.getUTCHours() === dos.h && d.getUTCMinutes() === dos.mi && s - (s % 2) === dos.s;
}
const FIXTURES = [
  ['A (aligned at +02:00)', bufA, A_SPECS],
  ['B (odd seconds on the writer clock)', bufB, B_SPECS],
  ['C (no extended timestamps)', bufC, C_SPECS],
  ['D (two offsets mixed)', bufD, D_SPECS],
  ['E (forged EOCD in the comment)', bufE, E_SPECS],
];
for(const [label, buf, specs] of FIXTURES){
  const r = E.analyzeZip(buf);
  const refs = specs.map((sp) => {
    if(sp.ut === null || sp.ut === undefined) return [];
    const dos = { y: sp.wall[0], mo: sp.wall[1], d: sp.wall[2], h: sp.wall[3], mi: sp.wall[4], s: 2 * Math.floor(sp.wall[5] / 2) };
    return REF_CANDS.filter((o) => refConsistent(sp.ut, dos, o));
  });
  ok('fixture ' + label + ': per-entry survivors match the Date-based reference', deepEq(r.entries.map((e) => e.consistent_offsets), refs));
  const dualRefs = refs.filter((a) => a.length > 0);
  const refInter = dualRefs.length > 0 ? dualRefs.reduce((acc, cur) => acc.filter((o) => cur.includes(o))).sort((a, b) => a - b) : [];
  ok('fixture ' + label + ': intersection matches the reference', deepEq(r.intersection, refInter));
}

heading('the shipped page agrees with the engine');
const page = readFileSync(PAGE_PATH, 'utf8');
ok('the page quotes 105 candidates and the engine computes 105', page.includes('105') && E.candidateOffsets().length === 105);
ok('the page quotes -43200 and CONFIG.offsetMin is -43200', page.includes('-43200') && E.CONFIG.offsetMin === -43200);
ok('the page quotes 50400 and CONFIG.offsetMax is 50400', page.includes('50400') && E.CONFIG.offsetMax === 50400);
ok('the page quotes 1980 and CONFIG.dosYearBase is 1980', page.includes('1980') && E.CONFIG.dosYearBase === 1980);
ok('the page quotes 0x5455 and CONFIG.extId is 0x5455', page.includes('0x5455') && E.CONFIG.extId === 0x5455);
ok('the page quotes 65535 and CONFIG.maxComment is 65535', page.includes('65535') && E.CONFIG.maxComment === 65535);
ok('the page says seconds are divided by 2 and CONFIG.dosSecondsMultiplier is 2', page.includes('divided by 2') && E.CONFIG.dosSecondsMultiplier === 2);
ok('the page quotes 999992800 and 1000000000 and the engine agrees on the 1e9 render', page.includes('999992800') && page.includes('1000000000') && deepEq(E.civilFromEpoch(1000000000), { y: 2001, mo: 9, d: 9, h: 1, mi: 46, s: 40 }));
ok('the page names the verifier file verify.mjs', page.includes('verify.mjs'));
ok('the page carries the home banner script tag verbatim', page.includes('<script src="/media/home-banner.js" defer></script>'));
// Assert the structural fact, not trailing whitespace: after trimming any
// trailing whitespace the page must end with </body> then </html>.
ok('the page ends with </body> then </html>', page.replace(/\s+$/, '').endsWith('</body>\n</html>'));
const md = readFileSync(MD_PATH, 'utf8');
const dekMatch = md.match(/^dek: "(.*)"$/m);
ok('the frontmatter dek was found', dekMatch !== null);
if(dekMatch){
  const nums = [...new Set(dekMatch[1].match(/\d+/g))];
  ok('every number in the dek (' + nums.join(', ') + ') also appears on the page', nums.every((n) => page.includes(n)));
}

heading('negative controls');
console.log('  8 corruptions are planted. Run node research/' + SLUG + '/verify.mjs --mutate to fire them; each must go red.');

if(process.argv.includes('--mutate')){
  const snap = { ...E.CONFIG };
  const restoreCfg = () => Object.assign(E.CONFIG, snap);
  const alignedGreen = (buf) => {
    const r = E.analyzeZip(buf);
    return r.verdict === 'unique' && deepEq(r.intersection, [7200]);
  };
  const defs = [
    {
      name: 'a flipped minute bit in one DOS word (input corruption)',
      base: () => alignedGreen(bufA),
      mut: () => {},
      green: () => alignedGreen(bufA_min),
    },
    {
      name: 'one extended timestamp shifted 450 seconds off the grid (input corruption)',
      base: () => alignedGreen(bufA),
      mut: () => {},
      green: () => alignedGreen(bufA_ut),
    },
    {
      name: 'an EOCD entry count that lies about the directory (input corruption)',
      base: () => !throws(() => E.analyzeZip(bufA)),
      mut: () => {},
      green: () => !throws(() => E.analyzeZip(bufA_cnt)),
    },
    {
      name: 'the DOS base year rule moved from 1980 to 1970 (rule corruption)',
      base: () => E.analyzeZip(bufA).entries.some((e) => e.dos === '2026-08-24T14:03:46'),
      mut: () => { E.CONFIG.dosYearBase = 1970; },
      green: () => E.analyzeZip(bufA).entries.some((e) => e.dos === '2026-08-24T14:03:46'),
    },
    {
      // The step must be one the planted offset does NOT survive. 700 leaves 7200 on the
      // grid (50400 is 72 steps of 700 from the lower bound), so the first version of this
      // control could not fail and was certifying nothing. 1000 does exclude it.
      name: 'the candidate grid step moved from 900 to 1000 (rule corruption)',
      base: () => alignedGreen(bufA),
      mut: () => { E.CONFIG.offsetStep = 1000; },
      green: () => alignedGreen(bufA),
    },
    {
      name: 'the extra field id rule moved from 0x5455 to 0x5456 (rule corruption)',
      base: () => E.analyzeZip(bufA).verdict === 'unique',
      mut: () => { E.CONFIG.extId = 0x5456; },
      green: () => E.analyzeZip(bufA).verdict === 'unique',
    },
    {
      name: 'the seconds multiplier rule moved from 2 to 1 (rule corruption)',
      base: () => E.analyzeZip(bufA).odd_second_count === 0,
      mut: () => { E.CONFIG.dosSecondsMultiplier = 1; },
      green: () => E.analyzeZip(bufA).odd_second_count === 0,
    },
    {
      name: 'the candidate step moved so the page quote of 105 goes stale (rule vs page)',
      base: () => page.includes(String(E.candidateOffsets().length)),
      mut: () => { E.CONFIG.offsetStep = 700; },
      green: () => page.includes(String(E.candidateOffsets().length)),
    },
  ];
  let red = 0;
  for(const d of defs){
    const baseGreen = d.base();
    d.mut();
    const mutGreen = d.green();
    restoreCfg();
    const wentRed = baseGreen === true && mutGreen === false;
    if(wentRed){ red += 1; console.log('  red as required: ' + d.name); }
    else { fail += 1; console.log('  DID NOT GO RED: ' + d.name); }
  }
  console.log('  ' + red + ' of ' + defs.length + ' controls went red as required.');
  if(red !== defs.length) fail += 1;
}

console.log(`
${pass} / ${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
