import {readFileSync} from 'node:fs';
import {createHash} from 'node:crypto';
import {spawnSync} from 'node:child_process';
import {resolve} from 'node:path';
import {
  ParseFault, asciiValue, bytesHex, comparePixels, entryIn, exifEpoch, forbiddenThumbnailMarkers,
  gpsValues, inspectJpeg, orientPixels, parseExifCandidate, parseExifDateTime, parseExifOffset,
  resampleTo, runComparison
} from '../../public/strata/the-thumbnail-that-was-not-edited/exif-core.mjs';
import {
  FALLBACK_BASE64, FALLBACK_LAST_MODIFIED, FALLBACK_SHA256, FALLBACK_SIZE, FALLBACK_THUMBNAIL_SHA256
} from '../../public/strata/the-thumbnail-that-was-not-edited/fallback-data.mjs';
import {ascii, buildExifPayload, entry, longBytes, rationalBytes, shortBytes, tinyJpeg, wrapJpeg} from './specimens.mjs';
import {harnessAvailable, runPageOn} from './page-harness.mjs';

const root = resolve(import.meta.dirname, '../..');
const publicDir = resolve(root, 'public/strata/the-thumbnail-that-was-not-edited');
const html = readFileSync(resolve(publicDir, 'index.html'), 'utf8');
const pageJs = readFileSync(resolve(publicDir, 'page.js'), 'utf8');
const coreJs = readFileSync(resolve(publicDir, 'exif-core.mjs'), 'utf8');
const generator = readFileSync(resolve(publicDir, 'make-fallback.mjs'), 'utf8');
const fallback = new Uint8Array(readFileSync(resolve(publicDir, 'fallback-stale-thumbnail.jpg')));
const markdown = readFileSync(resolve(root, 'src/content/strata/the-thumbnail-that-was-not-edited.md'), 'utf8');

let passed = 0;
let failed = 0;
const results = [];
function check(condition, label, detail = '') {
  if (condition) { passed++; results.push(`PASS ${label}${detail ? `: ${detail}` : ''}`); }
  else { failed++; results.push(`FAIL ${label}${detail ? `: ${detail}` : ''}`); }
}
function equal(actual, expected, label) { check(Object.is(actual, expected), label, `got ${JSON.stringify(actual)}, expected ${JSON.stringify(expected)}`); }
function sha(bytes) { return createHash('sha256').update(bytes).digest('hex'); }
function copy(bytes) { return new Uint8Array(bytes); }
function writeU32LE(bytes, offset, value) { new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).setUint32(offset, value, true); }

// Records every refusal code that an executed specimen actually reached, so that coverage is
// asserted from behaviour rather than from a code literal appearing somewhere in this file.
const reachedCodes = new Set();

function refusal(bytes, expectedCode, expectedOffset, label) {
  try {
    const result = inspectJpeg(bytes);
    const error = result.exifErrors[0] || (result.exif && result.exif.thumbnailError);
    check(error instanceof ParseFault, `${label} produces a structured refusal`, error ? error.message : 'no refusal');
    if (error) {
      reachedCodes.add(error.code);
      equal(error.code, expectedCode, `${label} code`);
      equal(error.offset, expectedOffset, `${label} byte`);
    }
  } catch (error) {
    check(error instanceof ParseFault, `${label} throws a structured refusal`, error.message);
    if (error instanceof ParseFault) {
      reachedCodes.add(error.code);
      equal(error.code, expectedCode, `${label} code`);
      equal(error.offset, expectedOffset, `${label} byte`);
    }
  }
}

// A second, deliberately separate reader. It shares no code with exif-core.mjs: it finds the
// APP1 segment, the TIFF base, the 1st IFD, and tags 513 and 514 by walking raw bytes again.
// If the page parser's byte order handling, TIFF base, or pointer arithmetic were wrong, this
// would disagree with it.
function independentThumbnailRange(bytes) {
  if (bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;
  let at = 2;
  let app1 = null;
  while (at + 4 <= bytes.length) {
    if (bytes[at] !== 0xff) return null;
    const marker = bytes[at + 1];
    if (marker === 0xd9 || marker === 0xda) break;
    const length = (bytes[at + 2] << 8) | bytes[at + 3];
    if (marker === 0xe1 && Buffer.from(bytes.subarray(at + 4, at + 10)).toString('latin1') === 'Exif\0\0') { app1 = {start:at + 4,end:at + 2 + length}; break; }
    at += 2 + length;
  }
  if (!app1) return null;
  const base = app1.start + 6;
  const little = bytes[base] === 0x49;
  const u16 = o => little ? bytes[o] | (bytes[o + 1] << 8) : (bytes[o] << 8) | bytes[o + 1];
  const u32 = o => (little
    ? bytes[o] + bytes[o + 1] * 256 + bytes[o + 2] * 65536 + bytes[o + 3] * 16777216
    : bytes[o] * 16777216 + bytes[o + 1] * 65536 + bytes[o + 2] * 256 + bytes[o + 3]);
  if (u16(base + 2) !== 42) return null;
  const ifd0 = base + u32(base + 4);
  const count0 = u16(ifd0);
  const next = u32(ifd0 + 2 + count0 * 12);
  if (!next) return null;
  const ifd1 = base + next;
  const count1 = u16(ifd1);
  let offsetValue = null, lengthValue = null, compression = null;
  for (let i = 0; i < count1; i++) {
    const e = ifd1 + 2 + i * 12;
    const tag = u16(e);
    if (tag === 513) offsetValue = u32(e + 8);
    if (tag === 514) lengthValue = u32(e + 8);
    if (tag === 259) compression = u16(e + 8);
  }
  if (offsetValue === null || lengthValue === null) return null;
  return {tiffBase:base,order:little ? 'II' : 'MM',compression,start:base + offsetValue,end:base + offsetValue + lengthValue};
}

function minimalExif(order = 'II') {
  const little = order === 'II';
  const tiff = new Uint8Array(14);
  tiff[0] = order.charCodeAt(0); tiff[1] = order.charCodeAt(1);
  const dv = new DataView(tiff.buffer);
  dv.setUint16(2, 42, little); dv.setUint32(4, 8, little); dv.setUint16(8, 0, little); dv.setUint32(10, 0, little);
  const payload = new Uint8Array(6 + tiff.length);
  payload.set([0x45,0x78,0x69,0x66,0,0]); payload.set(tiff,6);
  const declared = payload.length + 2;
  return new Uint8Array([0xff,0xd8,0xff,0xe1,declared >> 8,declared & 255,...payload,0xff,0xd9]);
}

function segmentJpeg(marker, payload, declared = payload.length + 2) {
  return new Uint8Array([0xff,0xd8,0xff,marker,declared >> 8,declared & 255,...payload,0xff,0xd9]);
}

const inspected = inspectJpeg(fallback);
const exif = inspected.exif;
const thumb = exif && exif.thumbnail;

check(Boolean(exif), 'fallback has one structurally valid Exif APP1');
equal(inspected.jpeg.exifCandidates.length, 1, 'fallback Exif candidate count');
equal(inspected.jpeg.dimensions.width, 640, 'fallback main width');
equal(inspected.jpeg.dimensions.height, 400, 'fallback main height');
equal(exif.byteOrder, 'II', 'fallback byte order');
equal(exif.magic, 42, 'fallback TIFF magic');
equal(exif.ifd0Offset, 8, 'fallback declared IFD0 offset');
equal(exif.tiffBase, exif.segment.dataStart + 6, 'TIFF base follows six identifier bytes');
equal(bytesHex(exif.identifier), '45 78 69 66 00 00', 'Exif identifier bytes');
equal(exif.ifd0.nextOffset, exif.ifd1.relativeOffset, 'IFD0 next pointer leads to IFD1');
equal(entryIn(exif.ifd1,259).scalar, 6, 'IFD1 Compression value');
equal(entryIn(exif.ifd1,513).type, 4, 'tag 513 TIFF type LONG');
equal(entryIn(exif.ifd1,513).count, 1, 'tag 513 count');
equal(entryIn(exif.ifd1,514).type, 4, 'tag 514 TIFF type LONG');
equal(entryIn(exif.ifd1,514).count, 1, 'tag 514 count');
equal(thumb.absoluteStart, exif.tiffBase + thumb.relativeOffset, 'absolute thumbnail start arithmetic');
equal(thumb.absoluteEnd, thumb.absoluteStart + thumb.length, 'absolute thumbnail end arithmetic');
check(thumb.absoluteStart >= exif.tiffBase && thumb.absoluteEnd <= exif.tiffEnd, 'thumbnail range remains inside selected APP1');
equal(bytesHex(thumb.bytes.subarray(0,2)), 'FF D8', 'thumbnail SOI');
equal(bytesHex(thumb.bytes.slice(-2)), 'FF D9', 'thumbnail terminal EOI');
equal(inspectJpeg(thumb.bytes).jpeg.dimensions.width, 160, 'thumbnail decoded header width');
equal(inspectJpeg(thumb.bytes).jpeg.dimensions.height, 100, 'thumbnail decoded header height');
equal(fallback.length, FALLBACK_SIZE, 'fallback exported size');
equal(sha(fallback), FALLBACK_SHA256, 'fallback exported SHA-256');
equal(Buffer.from(FALLBACK_BASE64,'base64').compare(Buffer.from(fallback)), 0, 'embedded fallback module bytes equal shipped JPEG');
equal(sha(thumb.bytes), FALLBACK_THUMBNAIL_SHA256, 'extracted thumbnail exported SHA-256');
check(thumb.conformant === true && thumb.recovered === false, 'fallback thumbnail is reached by the conformant Compression 6 path, not the recovery path');

const independent = independentThumbnailRange(fallback);
check(Boolean(independent), 'a second reader, sharing no code with the page parser, locates the fallback thumbnail range');
if (independent) {
  equal(independent.tiffBase, exif.tiffBase, 'independent reader agrees on the TIFF base');
  equal(independent.order, exif.byteOrder, 'independent reader agrees on the byte order');
  equal(independent.compression, 6, 'independent reader reads Compression 6');
  equal(independent.start, thumb.absoluteStart, 'independent reader agrees on the absolute thumbnail start');
  equal(independent.end, thumb.absoluteEnd, 'independent reader agrees on the absolute thumbnail end');
  equal(sha(fallback.subarray(independent.start, independent.end)), FALLBACK_THUMBNAIL_SHA256, 'independently re-sliced range hashes to the shipped thumbnail digest');
}
const bigEndianTwin = (() => {
  const built = buildExifPayload({
    ifd0:[entry(274,3,1,shortBytes(1,false)), entry(306,2,20,ascii('2026:08:09 09:08:07',20))],
    ifd1:[entry(259,3,1,shortBytes(6,false)), entry(513,4,1,longBytes(0,false)), entry(514,4,1,longBytes(0,false))]
  }, {order:'MM', ifd0Offset:26, thumbnail:Buffer.from(thumb.bytes)});
  return wrapJpeg(built.payload, 640, 400);
})();
const bigEndianParsed = inspectJpeg(bigEndianTwin);
const bigEndianIndependent = independentThumbnailRange(bigEndianTwin);
equal(bigEndianParsed.exif.byteOrder, 'MM', 'big-endian twin specimen byte order');
equal(bigEndianParsed.exif.ifd0Offset, 26, 'big-endian twin specimen does not put IFD0 at the usual offset 8');
equal(bigEndianParsed.exif.thumbnail ? sha(bigEndianParsed.exif.thumbnail.bytes) : null, FALLBACK_THUMBNAIL_SHA256, 'the same thumbnail is recovered from a big-endian file at a shifted IFD0 offset');
check(Boolean(bigEndianIndependent && bigEndianParsed.exif.thumbnail && bigEndianIndependent.start === bigEndianParsed.exif.thumbnail.absoluteStart && bigEndianIndependent.end === bigEndianParsed.exif.thumbnail.absoluteEnd), 'independent reader agrees on the big-endian twin range');

const forbidden = forbiddenThumbnailMarkers(inspectJpeg(thumb.bytes).jpeg);
equal(forbidden.length, 1, 'the shipped fallback thumbnail carries exactly one marker Exif 2.32 4.5.8 forbids');
equal(forbidden[0].name, 'APP0', 'that forbidden marker is the JFIF APP0 the encoder wrote');
check(html.includes('non-conformant thumbnail by that clause'), 'the page discloses its own fallback thumbnail as non-conformant');

for (const ifd of exif.allIfds) for (const item of ifd.entries) {
  check(item.valueOffset >= exif.tiffBase && item.valueEnd <= exif.tiffEnd, `${ifd.name} tag ${item.tag} value bounds`);
  equal(item.byteCount, item.valueBytes.length, `${ifd.name} tag ${item.tag} byte count`);
}

const gps = gpsValues(exif);
equal(gps.latitude, 0, 'synthetic latitude');
equal(gps.longitude, 0, 'synthetic longitude');
equal(gps.date, '2026:08:08', 'GPS date');
equal(gps.time.map(x => x.value).join(':'), '22:34:56', 'GPS time');
equal(entryIn(exif.exifIfd,37500).byteCount, 64, 'full synthetic MakerNote byte count');
equal(asciiValue(entryIn(exif.ifd0,306)), '2026:08:09 09:08:07', 'IFD0 DateTime');
equal(asciiValue(entryIn(exif.ifd1,306)), '2026:08:09 07:55:00', 'IFD1 DateTime');
equal(asciiValue(entryIn(exif.exifIfd,36867)), '2026:08:09 08:01:02', 'DateTimeOriginal');
equal(asciiValue(entryIn(exif.exifIfd,36868)), '2026:08:09 08:02:03', 'DateTimeDigitized');
equal(asciiValue(entryIn(exif.exifIfd,36880)), '+10:00', 'OffsetTime');
equal(asciiValue(entryIn(exif.exifIfd,36881)), '+09:30', 'OffsetTimeOriginal');
equal(asciiValue(entryIn(exif.exifIfd,36882)), '+09:30', 'OffsetTimeDigitized');
equal(asciiValue(entryIn(exif.exifIfd,37520)), '654', 'SubSecTime');
equal(asciiValue(entryIn(exif.exifIfd,37521)), '125', 'SubSecTimeOriginal');
equal(asciiValue(entryIn(exif.exifIfd,37522)), '250', 'SubSecTimeDigitized');
equal(new Date(FALLBACK_LAST_MODIFIED).toISOString(), '2026-08-09T09:08:07.654Z', 'synthetic File.lastModified');
const absoluteTimes = [
  Date.UTC(2026,7,8,23,8,7,654), Date.UTC(2026,7,8,22,31,2,125),
  Date.UTC(2026,7,8,22,32,3,250), Date.UTC(2026,7,8,22,34,56), FALLBACK_LAST_MODIFIED
];
equal((Math.max(...absoluteTimes) - Math.min(...absoluteTimes)) / 1000, 38225.529, 'fallback absolute-clock span in seconds');

// Malformed clocks must stay out of the timeline instead of being normalised into invented
// instants. Every one of these matches the printed ASCII shape and is still not an instant.
equal(exifEpoch('2026:08:09 08:01:02','+09:30','125').epoch, Date.UTC(2026,7,8,22,31,2,125), 'a well formed clock and offset still place on the timeline');
for (const [base,offset,label] of [
  ['2026:99:99 99:99:99','+09:30','a month, day, hour, minute and second all out of range'],
  ['2026:13:01 00:00:00','+09:30','month 13'],
  ['2026:02:30 00:00:00','+09:30','30 February'],
  ['2025:02:29 00:00:00','+09:30','29 February in a common year'],
  ['2026:08:09 24:00:00','+09:30','hour 24'],
  ['2026:08:09 08:01:60','+09:30','second 60'],
  ['2026:08:09 08:01:02','+99:99','an offset outside any real UTC band'],
  ['2026:08:09 08:01:02','+09:99','an offset minute field above 59']
]) {
  equal(exifEpoch(base,offset,null).epoch, null, `malformed clock excluded from the timeline: ${label}`);
}
equal(exifEpoch('2024:02:29 12:00:00','+00:00',null).epoch, Date.UTC(2024,1,29,12,0,0,0), '29 February in a leap year is a real instant');
equal(parseExifDateTime('2026:08:09 08:01:02').valid, true, 'valid stored clock parses');
equal(parseExifOffset('-12:00').valid, true, 'a negative offset inside the accepted band parses');
equal(parseExifOffset('+14:00').valid, true, 'the largest real UTC offset parses');
equal(parseExifOffset('+15:00').valid, false, 'an offset beyond the accepted band is refused');
check(html.includes('plus or minus 14:00'), 'the page discloses its own offset band as its own choice');

// GPS references and ranges. An unrecognised reference must not be read as a positive
// coordinate, and an out of range GPS clock must not join the timeline.
function gpsSpecimen(latRefText, latParts, timeParts, dateText) {
  const built = buildExifPayload({
    ifd0:[entry(274,3,1,shortBytes(1)), entry(34853,4,1,longBytes(0))],
    gps:[
      entry(1,2,2,ascii(latRefText,2)), entry(2,5,3,rationalBytes(latParts)),
      entry(3,2,2,ascii('E',2)), entry(4,5,3,rationalBytes([[0,1],[0,1],[0,1]])),
      entry(7,5,3,rationalBytes(timeParts)), entry(29,2,11,ascii(dateText,11))
    ]
  }, {thumbnail:null});
  return gpsValues(inspectJpeg(wrapJpeg(built.payload, 64, 64)).exif);
}
const absentGps = gpsValues(null);
const presentGpsKeys = Object.keys(gpsValues(exif)).sort().join(',');
equal(Object.keys(absentGps).sort().join(','), presentGpsKeys, 'the absent GPS result has the same shape as the present one, so no caller has to guard');
equal(absentGps.time.length, 0, 'the absent GPS result still exposes an empty time list');
const noGpsFile = inspectJpeg(wrapJpeg(buildExifPayload({ifd0:[entry(274,3,1,shortBytes(1))]}, {thumbnail:null}).payload, 64, 64));
equal(Object.keys(gpsValues(noGpsFile.exif)).sort().join(','), presentGpsKeys, 'an Exif file with no GPS IFD gets the same shape, which is the common case in the wild');
const goodGps = gpsSpecimen('N',[[51,1],[30,1],[0,1]],[[22,1],[34,1],[56,1]],'2026:08:08');
check(Math.abs(goodGps.latitude - 51.5) < 1e-12, 'a well formed latitude converts', String(goodGps.latitude));
equal(goodGps.utcEpoch, Date.UTC(2026,7,8,22,34,56,0), 'a well formed GPS date and time place on the timeline');
const oddRef = gpsSpecimen('Q',[[51,1],[30,1],[0,1]],[[22,1],[34,1],[56,1]],'2026:08:08');
equal(oddRef.latitude, null, 'an unrecognised GPSLatitudeRef yields no coordinate rather than a positive one');
check(typeof oddRef.latitudeReason === 'string' && oddRef.latitudeReason.includes('N'), 'the refusal names the references it would accept', oddRef.latitudeReason);
const southRef = gpsSpecimen('S',[[27,1],[28,1],[0,1]],[[22,1],[34,1],[56,1]],'2026:08:08');
check(southRef.latitude < 0, 'a southern reference gives a negative latitude', String(southRef.latitude));
const badRange = gpsSpecimen('N',[[91,1],[0,1],[0,1]],[[22,1],[34,1],[56,1]],'2026:08:08');
equal(badRange.latitude, null, 'a latitude above 90 degrees is refused');
const badGpsClock = gpsSpecimen('N',[[51,1],[30,1],[0,1]],[[99,1],[99,1],[99,1]],'2026:08:08');
equal(badGpsClock.utcEpoch, null, 'an out of range GPSTimeStamp does not join the timeline');
const badGpsDate = gpsSpecimen('N',[[51,1],[30,1],[0,1]],[[22,1],[34,1],[56,1]],'2026:02:31');
equal(badGpsDate.utcEpoch, null, 'an impossible GPSDateStamp does not join the timeline');

refusal(new Uint8Array([0xff]), 'JPEG_TRUNCATED_SOI', 1, 'truncated SOI');
refusal(new Uint8Array([0x00,0xd8]), 'JPEG_WRONG_MAGIC', 0, 'wrong JPEG magic');
refusal(new Uint8Array([0xff,0xd8,0xff,0xe1,0x00,0x20,0x45,0x78]), 'JPEG_SEGMENT_OUT_OF_BOUNDS', 4, 'lying JPEG segment length');
refusal(fallback.subarray(0,fallback.length - 2), 'JPEG_MISSING_EOI', fallback.length - 2, 'missing main EOI');
refusal(new Uint8Array([0xff,0xd8,0x00]), 'JPEG_EXPECTED_MARKER', 2, 'non-marker byte between segments');
refusal(new Uint8Array([0xff,0xd8,0xff]), 'JPEG_TRUNCATED_MARKER', 3, 'truncated marker fill');
refusal(new Uint8Array([0xff,0xd8,0xff,0xe1]), 'JPEG_TRUNCATED_LENGTH', 4, 'truncated segment length');
refusal(new Uint8Array([0xff,0xd8,0xff,0x00]), 'JPEG_STUFFED_BYTE_OUTSIDE_SCAN', 2, 'stuffed byte outside scan');
refusal(new Uint8Array([0xff,0xd8,0xff,0xe1,0x00,0x01,0xff,0xd9]), 'JPEG_BAD_SEGMENT_LENGTH', 4, 'segment below minimum length');
refusal(new Uint8Array([0xff,0xd8,0xff,0xc0,0x00,0x07,0x08,0x00,0x01,0x00,0x01,0x01,0xff,0xd9]), 'JPEG_BAD_SOF_LENGTH', 4, 'short SOF segment');
refusal(new Uint8Array([0xff,0xd8,0xff,0xc0,0x00,0x08,0x08,0x00,0x00,0x00,0x01,0x01,0xff,0xd9]), 'JPEG_ZERO_DIMENSION', 7, 'zero SOF dimension');
refusal(segmentJpeg(0xe1,new Uint8Array([0x45,0x78,0x69,0x66,0,0])), 'EXIF_TRUNCATED_HEADER', 6, 'truncated Exif header');
try {
  parseExifCandidate(new Uint8Array(14), {dataStart:0,dataEnd:14,offset:0}, 0);
  check(false, 'wrong Exif identifier direct candidate refusal');
} catch (error) {
  check(error instanceof ParseFault, 'wrong Exif identifier direct candidate produces a structured refusal', error.message);
  if (error instanceof ParseFault) reachedCodes.add(error.code);
  equal(error.code, 'EXIF_IDENTIFIER', 'wrong Exif identifier direct candidate code');
  equal(error.offset, 0, 'wrong Exif identifier direct candidate byte');
}

const badTiffMagic = copy(fallback); badTiffMagic[exif.tiffBase + 2] = 0;
refusal(badTiffMagic, 'TIFF_BAD_MAGIC', exif.tiffBase + 2, 'bad TIFF magic');
const badOrder = copy(fallback); badOrder[exif.tiffBase] = 0x5a;
refusal(badOrder, 'TIFF_BYTE_ORDER', exif.tiffBase, 'bad TIFF byte order');
const zeroIfd = minimalExif('II');
writeU32LE(zeroIfd, 16, 0);
refusal(zeroIfd, 'TIFF_ZERO_IFD0', 16, 'zero IFD0 pointer');
const readU16Escape = minimalExif('II');
writeU32LE(readU16Escape, 16, 13);
refusal(readU16Escape, 'TIFF_READ_OUT_OF_BOUNDS', 25, 'IFD pointer one byte before TIFF end');
const oversizedIfd = minimalExif('II');
oversizedIfd[20] = 0x01; oversizedIfd[21] = 0x04;
refusal(oversizedIfd, 'TIFF_TOO_MANY_ENTRIES', 20, 'oversized IFD entry count');
const shortIfd = minimalExif('II');
shortIfd[20] = 1; shortIfd[21] = 0;
refusal(shortIfd, 'TIFF_IFD_OUT_OF_BOUNDS', 20, 'IFD table beyond APP1');
const cyclic = copy(fallback);
writeU32LE(cyclic, exif.ifd0.absoluteOffset + 2 + exif.ifd0.count * 12, exif.ifd0.relativeOffset);
refusal(cyclic, 'TIFF_CYCLIC_IFD', exif.ifd0.absoluteOffset, 'cyclic IFD next pointer');
const badPointer = copy(fallback);
const exifPointerEntry = entryIn(exif.ifd0,34665);
badPointer[exifPointerEntry.entryOffset + 2] = 3; badPointer[exifPointerEntry.entryOffset + 3] = 0;
refusal(badPointer, 'TIFF_BAD_IFD_POINTER', exifPointerEntry.entryOffset, 'IFD pointer with wrong type');
const unknownType = copy(fallback);
const widthEntry = entryIn(exif.ifd0,256);
unknownType[widthEntry.entryOffset + 2] = 0xff; unknownType[widthEntry.entryOffset + 3] = 0xff;
refusal(unknownType, 'TIFF_UNKNOWN_TYPE', widthEntry.entryOffset + 2, 'unknown TIFF field type');
const hugeValue = copy(fallback);
writeU32LE(hugeValue, widthEntry.entryOffset + 4, 9 * 1024 * 1024);
refusal(hugeValue, 'TIFF_VALUE_TOO_LARGE', widthEntry.entryOffset + 4, 'oversized TIFF value multiplication');
const escapedValue = copy(fallback);
const dateEntry = entryIn(exif.ifd0,306);
writeU32LE(escapedValue, dateEntry.entryOffset + 8, 0xffffff00);
refusal(escapedValue, 'TIFF_VALUE_OUT_OF_BOUNDS', dateEntry.entryOffset + 8, 'TIFF value pointer outside APP1');
const hugeThumb = copy(fallback);
writeU32LE(hugeThumb, entryIn(exif.ifd1,514).entryOffset + 8, 0xffffffff);
refusal(hugeThumb, 'THUMBNAIL_RANGE_OUT_OF_BOUNDS', entryIn(exif.ifd1,513).entryOffset, 'out-of-bounds thumbnail length');
const badThumbSoi = copy(fallback); badThumbSoi[thumb.absoluteStart] = 0;
refusal(badThumbSoi, 'THUMBNAIL_BAD_SOI', thumb.absoluteStart, 'bad thumbnail SOI');
const badThumbEoi = copy(fallback); badThumbEoi[thumb.absoluteEnd - 1] = 0;
refusal(badThumbEoi, 'THUMBNAIL_BAD_EOI', thumb.absoluteEnd - 2, 'bad thumbnail EOI');
const missing513 = copy(fallback);
const tag513Entry = entryIn(exif.ifd1,513);
missing513[tag513Entry.entryOffset] = 0x03; missing513[tag513Entry.entryOffset + 1] = 0x02;
refusal(missing513, 'THUMBNAIL_MISSING_513', exif.ifd1.absoluteOffset, 'compressed IFD1 missing tag 513');
const missing514 = copy(fallback);
const tag514Entry = entryIn(exif.ifd1,514);
missing514[tag514Entry.entryOffset] = 0x03; missing514[tag514Entry.entryOffset + 1] = 0x02;
refusal(missing514, 'THUMBNAIL_MISSING_514', exif.ifd1.absoluteOffset, 'compressed IFD1 missing tag 514');
const shortThumb = copy(fallback);
writeU32LE(shortThumb, tag514Entry.entryOffset + 8, 3);
refusal(shortThumb, 'THUMBNAIL_TOO_SHORT', tag514Entry.entryOffset, 'thumbnail shorter than SOI and EOI');

const noExif = inspectJpeg(new Uint8Array([0xff,0xd8,0xff,0xd9]));
equal(noExif.jpeg.exifCandidates.length, 0, 'a bare SOI and EOI pair carries no Exif candidate');
equal(noExif.exif, null, 'a JPEG without Exif yields a negative result rather than a refusal');
equal(noExif.jpeg.dimensions, null, 'and the same specimen declares no image, which the page reports separately from acceptance');
equal(inspectJpeg(minimalExif('II')).exif.byteOrder, 'II', 'minimal little-endian TIFF accepted');
equal(inspectJpeg(minimalExif('MM')).exif.byteOrder, 'MM', 'minimal big-endian TIFF accepted');
const firstBad = minimalExif('II').slice(2,-2);
firstBad[12] = 0;
const secondGood = minimalExif('MM').slice(2,-2);
const multiple = new Uint8Array([0xff,0xd8,...firstBad,...secondGood,0xff,0xd9]);
const selected = inspectJpeg(multiple);
equal(selected.jpeg.exifCandidates.length, 2, 'multiple Exif candidate count');
equal(selected.exifErrors.length, 1, 'invalid first Exif candidate retained as a refusal');
equal(selected.exif.candidateIndex, 1, 'first structurally valid Exif candidate selected');
equal(selected.exif.byteOrder, 'MM', 'selected second candidate content');

// Specimens the page's own generator cannot have produced. Each is built by specimens.mjs,
// which lays out its own TIFF and IFD chain, and each targets a real behaviour of the corpus
// rather than the shipped fallback.
const compressionEntry = entryIn(exif.ifd1,259);
const thumbnailCopy = () => Buffer.from(thumb.bytes);
function unseenSpecimen(ifd1Entries, options = {}) {
  const built = buildExifPayload({
    ifd0:[entry(274,3,1,shortBytes(1)), entry(306,2,20,ascii('2026:08:09 09:08:07',20)), entry(34665,4,1,longBytes(0))],
    exif:options.exif || [entry(36867,2,20,ascii('2026:08:09 08:01:02',20))],
    ifd1:ifd1Entries
  }, {order:options.order || 'II', ifd0Offset:options.ifd0Offset === undefined ? 8 : options.ifd0Offset, thumbnail:options.thumbnail === undefined ? thumbnailCopy() : options.thumbnail});
  return {bytes:wrapJpeg(built.payload, options.mainWidth || 640, options.mainHeight || 400, options.trailing || null),built};
}

// 1. A file that omits the Compression tag the standard marks mandatory but still points at a
//    complete JPEG stream. Strict Compression 6 gating drops thumbnails like this one.
const noCompressionTag = unseenSpecimen([entry(513,4,1,longBytes(0)), entry(514,4,1,longBytes(0))]);
const noCompressionParsed = inspectJpeg(noCompressionTag.bytes);
check(Boolean(noCompressionParsed.exif.thumbnail && noCompressionParsed.exif.thumbnail.bytes), 'IFD1 with no Compression tag but a valid tag 513 and 514 pair still yields the thumbnail');
equal(noCompressionParsed.exif.thumbnail?.recovered, true, 'that extraction is labelled a recovery, not the published mechanism');
equal(noCompressionParsed.exif.thumbnail?.conformant, false, 'that extraction is not reported as conformant');
equal(noCompressionParsed.exif.thumbnail?.declaredCompression, null, 'no Compression value was readable on that file');
equal(noCompressionParsed.exif.thumbnail ? sha(noCompressionParsed.exif.thumbnail.bytes) : null, FALLBACK_THUMBNAIL_SHA256, 'the recovered stream is byte-identical to the stream that was written');
check(html.includes('files that omit the mandatory') && html.includes('labelled a recovery'), 'the recovery rule is disclosed on the page as a rule changed after seeing data');

// 2. Compression 1 while a complete JPEG stream sits at tag 513. Seen in the wild on at least
//    one camera model. The stream is real, so it is recovered and labelled.
const mislabelled = unseenSpecimen([entry(259,3,1,shortBytes(1)), entry(513,4,1,longBytes(0)), entry(514,4,1,longBytes(0))]);
const mislabelledParsed = inspectJpeg(mislabelled.bytes);
equal(mislabelledParsed.exif.thumbnail?.declaredCompression, 1, 'mislabelled specimen declares Compression 1');
equal(mislabelledParsed.exif.thumbnail?.recovered, true, 'Compression 1 with a real JPEG stream at tag 513 is recovered');
equal(mislabelledParsed.exif.thumbnail ? sha(mislabelledParsed.exif.thumbnail.bytes) : null, FALLBACK_THUMBNAIL_SHA256, 'the mislabelled stream is recovered byte for byte');

// 3. A genuinely uncompressed 1st IFD: Compression 1, no tag 513 or 514 pair at all. This must
//    stay a structural report and must never be rendered.
const trulyUncompressed = unseenSpecimen([entry(259,3,1,shortBytes(1)), entry(273,4,1,longBytes(0)), entry(279,4,1,longBytes(64))], {thumbnail:null});
const trulyUncompressedParsed = inspectJpeg(trulyUncompressed.bytes);
check(trulyUncompressedParsed.exif.thumbnail?.uncompressed, 'uncompressed IFD1 with no JPEG pointer pair follows the structural report path');
check(!trulyUncompressedParsed.exif.thumbnail?.bytes, 'the uncompressed structural report carries no pixel bytes to render');

// 4. An unsupported compression value with no usable pointer pair must refuse with a stable
//    code and byte instead of leaving a half-built thumbnail for the renderer to trip over.
const unsupported = unseenSpecimen([entry(259,3,1,shortBytes(5)), entry(273,4,1,longBytes(0))], {thumbnail:null});
const unsupportedParsed = inspectJpeg(unsupported.bytes);
check(unsupportedParsed.exif.thumbnailError instanceof ParseFault, 'unsupported IFD1 Compression refuses instead of producing a thumbnail object');
if (unsupportedParsed.exif.thumbnailError) {
  reachedCodes.add(unsupportedParsed.exif.thumbnailError.code);
  equal(unsupportedParsed.exif.thumbnailError.code, 'THUMBNAIL_UNSUPPORTED_COMPRESSION', 'unsupported compression refusal code');
  equal(unsupportedParsed.exif.thumbnailError.offset, entryIn(unsupportedParsed.exif.ifd1,259).entryOffset, 'unsupported compression refusal names the Compression entry byte');
}
check(unsupportedParsed.exif.thumbnail === null, 'no thumbnail object survives an unsupported compression refusal');

// 5. A Compression tag that is not one readable SHORT. The old code left {compression:null}
//    with no length, which the renderer then dereferenced.
const unreadableCompression = copy(fallback);
writeU32LE(unreadableCompression, compressionEntry.entryOffset + 4, 2);
const unreadableParsed = inspectJpeg(unreadableCompression);
equal(unreadableParsed.exif.thumbnail?.declaredCompression, null, 'a Compression tag with count 2 has no readable scalar');
check(Boolean(unreadableParsed.exif.thumbnail?.bytes && unreadableParsed.exif.thumbnail?.length), 'a recovered thumbnail always carries both its bytes and its declared length');
for (const state of [thumb, noCompressionParsed.exif.thumbnail, mislabelledParsed.exif.thumbnail, unreadableParsed.exif.thumbnail]) {
  check(state && typeof state.length === 'number' && state.bytes instanceof Uint8Array, 'every renderable thumbnail state carries a numeric length and a byte slice', `${state.length}`);
}

// 6. Malformed embedded stream: outer file intact, thumbnail SOI and EOI intact, third byte of
//    the inner stream corrupted. The inner refusal must be reported, not swallowed.
const malformedInner = copy(fallback);
malformedInner[thumb.absoluteStart + 2] = 0x00;
const malformedInnerParsed = inspectJpeg(malformedInner);
check(malformedInnerParsed.exif.thumbnailError === null, 'a corrupt inner stream still passes the declared range checks, which is why the page must parse the slice separately');
let innerFault = null;
try { inspectJpeg(malformedInnerParsed.exif.thumbnail?.bytes); } catch (error) { innerFault = error; }
check(innerFault instanceof ParseFault, 'parsing the extracted slice refuses on the corrupt inner stream');
if (innerFault) {
  equal(innerFault.code, 'JPEG_EXPECTED_MARKER', 'inner stream refusal code');
  equal(innerFault.offset, 2, 'inner stream refusal names the slice-relative byte');
  equal(thumb.absoluteStart + innerFault.offset, thumb.absoluteStart + 2, 'the page can name the same byte in file coordinates');
}
check(/state\.thumbDecode = error instanceof ParseFault/.test(pageJs) && /file byte \$\{thumb\.absoluteStart \+ error\.offset\}/.test(pageJs), 'the page records the inner refusal with both slice-relative and file-absolute bytes');
check(/if \(decodeNotes\.length\) status/.test(pageJs), 'the page never overwrites a decode refusal with a success status');

// 7. Bytes after the terminal EOI must be counted and surfaced, not silently accepted.
const withTrailing = unseenSpecimen([entry(259,3,1,shortBytes(6)), entry(513,4,1,longBytes(0)), entry(514,4,1,longBytes(0))], {trailing:Buffer.from([0x50,0x4b,0x03,0x04,0xde,0xad,0xbe,0xef])});
const trailingParsed = inspectJpeg(withTrailing.bytes);
equal(trailingParsed.jpeg.trailingBytes, 8, 'eight bytes after the terminal EOI are counted');
equal(inspectJpeg(fallback).jpeg.trailingBytes, 0, 'the shipped fallback has no unaccounted trailing bytes');
check(/bytes after terminal EOI/.test(pageJs) && /jpeg\.trailingBytes === 0/.test(pageJs), 'the page displays the trailing byte count and checks it');

// 8. A marker sequence with no frame header at all is accepted by the walk but declares no
//    image, and the page must say so rather than call it an ordinary JPEG.
const markersOnly = inspectJpeg(new Uint8Array([0xff,0xd8,0xff,0xd9]));
equal(markersOnly.jpeg.dimensions, null, 'FF D8 FF D9 is a valid marker sequence that declares no image');
equal(markersOnly.jpeg.markers.length, 2, 'that sequence contains exactly SOI and EOI');
check(/a frame header is present/.test(pageJs), 'the page distinguishes an accepted marker sequence from a decodable image');

const px = values => new Uint8ClampedArray(values);
const a = {width:2,height:1,data:px([0,0,0,255, 255,255,255,255])};
const b = {width:2,height:1,data:px([255,255,255,255, 255,255,255,255])};
equal(comparePixels(a,a).mad, 0, 'identical pixel fixture has zero MAD');
equal(comparePixels(a,b).mad, 0.5, 'one of two pixels differing by 255 has MAD 0.5');
equal(comparePixels(a,b).meanChannelDifference, 127.5, 'unnormalized mean channel difference');
// The reason this page uses mean absolute difference rather than correlation, demonstrated
// rather than asserted. A global gain and offset leaves correlation at 1 and moves MAD a long
// way, so a correlation check cannot see a tone edit at all.
function pearson(a, b) {
  const n = a.data.length / 4 * 3;
  const va = [], vb = [];
  for (let i = 0; i < a.data.length; i += 4) for (let c = 0; c < 3; c++) { va.push(a.data[i + c]); vb.push(b.data[i + c]); }
  const ma = va.reduce((s,v) => s + v, 0) / n, mb = vb.reduce((s,v) => s + v, 0) / n;
  let num = 0, da = 0, db = 0;
  for (let i = 0; i < n; i++) { num += (va[i] - ma) * (vb[i] - mb); da += (va[i] - ma) ** 2; db += (vb[i] - mb) ** 2; }
  return num / Math.sqrt(da * db);
}
const tone = {width:4,height:1,data:px([10,20,30,255, 60,70,80,255, 110,120,130,255, 160,170,180,255])};
const brightened = {width:4,height:1,data:px(Array.from(tone.data, (v,i) => i % 4 === 3 ? 255 : Math.min(255, Math.round(v * 1.2 + 20))))};
check(Math.abs(pearson(tone,brightened) - 1) < 1e-9, 'a global gain and offset leaves Pearson correlation at 1, so a correlation check is blind to it', pearson(tone,brightened).toFixed(12));
check(comparePixels(tone,brightened).mad > 0.1, 'the same change moves this page mean absolute difference well away from zero', comparePixels(tone,brightened).mad.toFixed(9));
check(html.includes('invariant to a global brightness and contrast change'), 'the page states why it does not use correlation');
check(html.includes('4.4.6.4') && html.includes('padding data black'), 'the page cites the DCF clause that makes contain the right default');

const one = {width:1,height:1,data:px([11,22,33,255])};
const scaled = resampleTo(one,3,2,'contain');
check(Array.from(scaled.data).every((v,i) => v === [11,22,33,255][i % 4]), 'bilinear one-pixel fixture is constant on a larger grid');
const fixture = {width:2,height:2,data:px([1,2,3,255, 50,60,70,255, 90,100,110,255, 200,210,220,255])};
const auto = runComparison(fixture,fixture,{fit:'contain',transform:'auto'});
equal(auto.candidate.id, 'identity', 'auto alignment selects identity on asymmetric identical fixtures');
equal(auto.comparison.mad, 0, 'auto alignment exact fixture score');
equal(auto.scores.length, 8, 'automatic comparison scores all eight transforms');
equal(auto.threshold, null, 'comparison has no binary threshold');

// A non-square fixture, so a failure to swap dimensions on a quarter turn cannot pass, and
// every one of the eight mappings is asserted cell by cell rather than by one sampled pixel.
const grid = {width:3,height:2,data:px([
  10,0,0,255,  20,0,0,255,  30,0,0,255,
  40,0,0,255,  50,0,0,255,  60,0,0,255
])};
const redsOf = image => Array.from({length:image.width * image.height}, (_, i) => image.data[i * 4]);
const expectedOrientations = {
  1:{width:3,height:2,reds:[10,20,30,40,50,60]},
  2:{width:3,height:2,reds:[30,20,10,60,50,40]},
  3:{width:3,height:2,reds:[60,50,40,30,20,10]},
  4:{width:3,height:2,reds:[40,50,60,10,20,30]},
  5:{width:2,height:3,reds:[10,40,20,50,30,60]},
  6:{width:2,height:3,reds:[40,10,50,20,60,30]},
  7:{width:2,height:3,reds:[60,30,50,20,40,10]},
  8:{width:2,height:3,reds:[30,60,20,50,10,40]}
};
for (const [orientation, want] of Object.entries(expectedOrientations)) {
  const got = orientPixels(grid, Number(orientation));
  equal(`${got.width}x${got.height}`, `${want.width}x${want.height}`, `orientation ${orientation} output grid on a non-square fixture`);
  equal(redsOf(got).join(','), want.reds.join(','), `orientation ${orientation} pixel mapping on a non-square fixture`);
}
// The eight transforms must form a group under composition, because the page's headline claim
// that the Orientation control cannot move an automatic score depends on exactly that.
for (let outer = 1; outer <= 8; outer++) {
  const composed = new Set();
  for (let inner = 1; inner <= 8; inner++) composed.add(redsOf(orientPixels(orientPixels(grid, inner), outer)).join(','));
  equal(composed.size, 8, `pre-composing orientation ${outer} permutes the eight transforms without collapsing them`);
}
let mismatchRejected = false;
try { comparePixels(a, fixture); } catch (error) { mismatchRejected = error instanceof RangeError; }
check(mismatchRejected, 'comparison refuses unequal grids instead of making a vacuous comparison');

function decodeWithImageMagick(bytes, width, height) {
  const run = spawnSync('convert', ['jpg:-','-depth','8','rgba:-'], {input:Buffer.from(bytes),maxBuffer:width * height * 4 + 1024 * 1024});
  if (run.error || run.status !== 0) throw new Error(`ImageMagick decode failed: ${run.error ? run.error.message : run.stderr.toString()}`);
  equal(run.stdout.length, width * height * 4, `ImageMagick ${width} by ${height} RGBA byte count`);
  return {width,height,data:new Uint8ClampedArray(run.stdout)};
}
let offlineMad = null;
// The documented offline value. It is decoder dependent by construction, so it is asserted to
// a tolerance about one hundredth of its own size rather than to a range that any wrong
// alignment, any wrong resampler, and most wrong images would also satisfy.
const DOCUMENTED_OFFLINE_MAD = 0.113463562;
const OFFLINE_MAD_TOLERANCE = 1e-3;
try {
  const mainPixels = decodeWithImageMagick(fallback,640,400);
  const thumbPixels = decodeWithImageMagick(thumb.bytes,160,100);
  const result = runComparison(mainPixels,thumbPixels,{fit:'contain',transform:'auto'});
  offlineMad = result.comparison.mad;
  check(Math.abs(offlineMad - DOCUMENTED_OFFLINE_MAD) < OFFLINE_MAD_TOLERANCE, `offline fallback MAD reproduces the documented ${DOCUMENTED_OFFLINE_MAD} within ${OFFLINE_MAD_TOLERANCE}`, offlineMad.toFixed(9));
  equal(result.candidate.id, 'rotate-180', 'fallback best offline alignment');
  const identityScore = result.scores.find(s => s.id === 'identity').mad;
  check(identityScore > offlineMad, 'the automatic winner really is below the identity alignment, so the best-of-eight selection is doing something on this specimen', `identity ${identityScore.toFixed(9)} against best ${offlineMad.toFixed(9)}`);
  // The two controls that cannot move the headline on this specimen, asserted rather than
  // asserted about. Both would fail if the eight transforms or the fit rule were wrong.
  for (let orientation = 1; orientation <= 8; orientation++) {
    const rotated = runComparison(orientPixels(mainPixels, orientation), thumbPixels, {fit:'contain',transform:'auto'});
    check(Math.abs(rotated.comparison.mad - offlineMad) < 1e-12, `pre-applying Orientation ${orientation} leaves the automatic score unchanged`, rotated.comparison.mad.toFixed(9));
  }
  const cover = runComparison(mainPixels,thumbPixels,{fit:'cover',transform:'auto'});
  check(Math.abs(cover.comparison.mad - offlineMad) < 1e-12, 'contain and centre crop coincide on the fallback because 640 by 400 and 160 by 100 share one aspect ratio', cover.comparison.mad.toFixed(9));
  // And a specimen where the fit control does matter, so the coincidence above is a property of
  // the fallback rather than of the code.
  const tall = decodeWithImageMagick(fallback,640,400);
  const narrowThumb = resampleTo(thumbPixels, 60, 100, 'cover');
  const containNarrow = runComparison(tall, narrowThumb, {fit:'contain',transform:'identity'}).comparison.mad;
  const coverNarrow = runComparison(tall, narrowThumb, {fit:'cover',transform:'identity'}).comparison.mad;
  check(Math.abs(containNarrow - coverNarrow) > 1e-6, 'on a thumbnail grid with a different aspect ratio the fit control does move the score', `${containNarrow.toFixed(9)} against ${coverNarrow.toFixed(9)}`);
  check(html.includes('the same 1.6 ratio'), 'the page discloses that two of its three controls cannot move the fallback score');
} catch (error) {
  check(false, 'offline fallback pixel decode and comparison', error.message);
}

const title = /<title>([^<]+)<\/title>/.exec(html)?.[1];
const metaDescription = /<meta name="description" content="([^"]+)"/.exec(html)?.[1];
const front = key => new RegExp(`^${key}: "([^"]+)"`, 'm').exec(markdown)?.[1];
equal(title, front('seoTitle'), 'HTML title equals frontmatter seoTitle');
equal(metaDescription, front('dek'), 'meta description equals frontmatter dek');
equal(/<meta name="aw-plain" content="([^"]+)"/.exec(html)?.[1], front('plain'), 'visible plain summary equals frontmatter plain');
check(metaDescription.includes('not proof of editing') && metaDescription.includes('without a thumbnail are normal'), 'shareable dek carries both concessions');
check(/property="og:description"[^>]+content="[^"]*does not prove an edit/.test(html), 'OG description carries the no-proof concession');
check(/name="twitter:description"[^>]+content="[^"]*cannot prove/.test(html), 'Twitter description carries the no-proof concession');
check(title.includes('Extract') && title.includes('Locally'), 'search title promises extraction and locality, not authentication');
check(markdown.includes('"immersive"') && markdown.includes('"interactive"') && markdown.includes('"show-the-check"') && markdown.includes('"the specimen is yours"'), 'required wave tags are present');
check(markdown.includes('draft: false'), 'frontmatter publishes the stratum');

const jsonBlock = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/.exec(html)?.[1];
let jsonLd = null;
try { jsonLd = JSON.parse(jsonBlock); check(true, 'JSON-LD parses as JSON'); } catch (error) { check(false, 'JSON-LD parses as JSON', error.message); }
if (jsonLd) {
  equal(jsonLd['@type'], 'Article', 'JSON-LD type');
  equal(jsonLd.name, title, 'JSON-LD name equals SEO title');
  equal(jsonLd.headline, front('title'), 'JSON-LD headline equals poetic title');
  equal(jsonLd.description, metaDescription, 'JSON-LD description equals verified dek');
  equal(jsonLd.datePublished, '2026-08-09T00:00:00Z', 'JSON-LD publication date');
  equal(jsonLd.author && jsonLd.author['@type'], 'Organization', 'JSON-LD author type');
  equal(jsonLd.author && jsonLd.author.name, 'Artificial Wasteland', 'JSON-LD author name');
  equal(jsonLd.author && jsonLd.author.url, 'https://artwaste.land/', 'JSON-LD author url');
  equal(jsonLd.publisher && jsonLd.publisher['@type'], 'Organization', 'JSON-LD publisher type');
  equal(jsonLd.publisher && jsonLd.publisher.name, 'Artificial Wasteland', 'JSON-LD publisher name');
  equal(jsonLd.publisher && jsonLd.publisher.url, 'https://artwaste.land/', 'JSON-LD publisher url');
  equal(jsonLd.url, 'https://artwaste.land/strata/the-thumbnail-that-was-not-edited/', 'JSON-LD canonical url');
  equal(jsonLd.image, 'https://artwaste.land/og/the-thumbnail-that-was-not-edited.png', 'JSON-LD image url');
  equal(jsonLd.url, /<link rel="canonical" href="([^"]+)"/.exec(html)?.[1], 'JSON-LD url equals the canonical link');
}
check(/property="og:description"[^>]+content="[^"]*if it has one/.test(html), 'OG description says the second picture may not be there');
check(/name="twitter:description"[^>]+content="[^"]*if present/.test(html), 'Twitter description says the thumbnail may not be there');
check(metaDescription.includes('standard Exif and GPS time field'), 'the dek claims recognised standard time fields rather than every stored clock');
check(html.includes('XMP or IPTC blocks in other segments are not read'), 'the body names the clocks it does not read');

for (const visible of ['Compression</strong> value is <span class="value">6</span>','513 (0x0201)','514 (0x0202)','640 by 400','160 by 100','more than 90,000','9,098','1,535','91 percent sensitivity','14 percent false positives','2019-05-29','96 MiB','40 megapixels','1,024 entries','32 MiB']) check(html.includes(visible), `visible checked figure ${visible}`);
check(pageJs.includes('const MAX_FILE_BYTES = 96 * 1024 * 1024'), '96 MiB visible cap matches page code');
check(pageJs.includes('const MAX_DECODE_PIXELS = 40 * 1000 * 1000'), '40 megapixel visible cap matches page code');
check(coreJs.includes('count > 1024'), '1,024-entry visible cap matches parser code');
check(coreJs.includes('byteCount > 32 * 1024 * 1024'), '32 MiB TIFF-value visible cap matches parser code');
check(generator.includes("makeImage(mainPath, 640, 400, 'main')") && generator.includes("makeImage(thumbPath, 160, 100, 'thumb')"), 'fallback visible dimensions match generator');
// The enforced policy is the meta element, not the paragraph that prints it, so both are read
// and the printed copy is required to be the same string.
const activeCsp = /<meta http-equiv="Content-Security-Policy" content="([^"]+)"/.exec(html)?.[1];
const printedCsp = /<pre id="csp-print">([^<]+)<\/pre>/.exec(html)?.[1];
check(Boolean(activeCsp), 'an active Content Security Policy meta element is present');
equal(printedCsp, activeCsp, 'the printed policy is the policy that is enforced');
check(Boolean(activeCsp) && activeCsp.includes("connect-src 'none'"), 'the enforced policy forbids all connect destinations');
check(Boolean(activeCsp) && activeCsp.includes("object-src 'none'") && activeCsp.includes("base-uri 'none'"), 'the enforced policy forbids plugins and base rewriting');
check(Boolean(activeCsp) && activeCsp.includes("form-action 'self'"), 'the enforced policy allows only same-origin form submission, so the banner search control works');
check(html.includes('left that control visible but dead'), 'the page explains why form-action is self rather than none');
check(!/<(?:script|img|link)[^>]+(?:src|href)="https?:\/\/(?!artwaste\.land)/i.test(html), 'no third-party automatic subresource URL');
check(!/\bfetch\s*\(/.test(pageJs), 'page logic never calls fetch');
check(!/new\s+(?:XMLHttpRequest|WebSocket|EventSource)\b/.test(pageJs), 'page logic never constructs a network channel');
check(!/\bsendBeacon\s*\(/.test(pageJs), 'page logic never sends a beacon');
check(pageJs.includes("getEntriesByType('resource')") && pageJs.includes("$('resource-list')"), 'the page reads Resource Timing entries and lists them');

// Two shape assertions rather than behavioural ones, and labelled as such. A redundancy check
// that is quietly rewired to call the very thing it is meant to be independent of cannot be
// caught from outside, so the independence is asserted at the source instead.
check(/const raw = state\.bytes\.slice\(entry\.entryOffset, entry\.entryOffset \+ 12\)/.test(pageJs) && /getUint32\(8, little\)/.test(pageJs), 'SHAPE: the live panel re-reads tags 513 and 514 from raw entry bytes rather than reusing the parser scalar');
check(pageJs.includes('function independentMad') && /for \(let c = 0; c < 3; c\+\+\) total \+=/.test(pageJs), 'SHAPE: the live panel sums the mean absolute difference again outside comparePixels');
check(pageJs.includes("'PARSER POSTCONDITION: '") && pageJs.includes("'INDEPENDENT: '"), 'SHAPE: the live panel labels which lines can fail and which restate a parser postcondition');
check(html.trimEnd().endsWith('</html>'), 'load-bearing HTML close is present');

// Every element identifier the page module reaches for must actually exist in the markup. The
// offline harness creates elements on demand, so it would not notice a missing one.
const referencedIds = [...new Set([...pageJs.matchAll(/\$\('([a-z0-9-]+)'\)/g)].map(match => match[1]))].sort();
const markupIds = new Set([...html.matchAll(/\bid="([a-zA-Z0-9-]+)"/g)].map(match => match[1]));
check(referencedIds.length >= 25, `the page module reaches for ${referencedIds.length} distinct element identifiers`);
for (const id of referencedIds) check(markupIds.has(id), `element identifier ${id} used by page.js exists in the markup`);

// Refusal coverage from behaviour. A code counts as covered only if a constructed specimen
// actually reached it during this run, not because its name appears somewhere in this file.
const verifierSource = readFileSync(import.meta.filename,'utf8');
const parserRefusalCodes = [...new Set([...coreJs.matchAll(/fault\('([A-Z0-9_]+)'/g)].map(match => match[1]))].sort();
check(parserRefusalCodes.length >= 30, `the parser declares ${parserRefusalCodes.length} distinct refusal codes`);
for (const code of parserRefusalCodes) check(reachedCodes.has(code), `parser refusal code ${code} was reached by an executed specimen in this run`);
for (const reached of reachedCodes) check(parserRefusalCodes.includes(reached), `every reached code ${reached} is one the parser declares`);
const authored = [html,pageJs,coreJs,generator,markdown,readFileSync(resolve(publicDir,'CC0-1.0.txt'),'utf8'),verifierSource,readFileSync(resolve(import.meta.dirname,'specimens.mjs'),'utf8')];
check(authored.every(text => !text.includes('\u2014')), 'no authored file contains an em dash');

// ---------------------------------------------------------------------------------------
// The page's own module, run end to end on specimens its generator never produced.
//
// Everything above tests exif-core.mjs. The failures that mattered most on this page were in
// page.js: state left over from a previous specimen, a refusal overwritten by a later success,
// and a render path that dereferenced a half-built object. Those need the page itself.
// ---------------------------------------------------------------------------------------
const host = (() => {
  const app1 = exif.segment;
  return Buffer.concat([Buffer.from(fallback.subarray(0, app1.offset)), Buffer.from(fallback.subarray(app1.dataEnd))]);
})();
function pageSpecimen(name, ifd1Entries, options = {}) {
  const hasGps = Boolean(options.gps);
  const built = buildExifPayload({
    ifd0:[
      entry(274,3,1,shortBytes(1)), entry(306,2,20,ascii('2026:08:09 09:08:07',20)), entry(34665,4,1,longBytes(0)),
      ...(hasGps ? [entry(34853,4,1,longBytes(0))] : [])
    ],
    exif:options.exif || [
      entry(36867,2,20,ascii('2026:08:09 08:01:02',20)), entry(36881,2,7,ascii('+09:30',7)),
      entry(40962,4,1,longBytes(options.px === undefined ? 640 : options.px)),
      entry(40963,4,1,longBytes(options.py === undefined ? 400 : options.py))
    ],
    gps:options.gps || null,
    ifd1:ifd1Entries
  }, {order:'II', ifd0Offset:8, thumbnail:options.thumbnail === undefined ? Buffer.from(thumb.bytes) : options.thumbnail});
  return {name,bytes:wrapJpeg(built.payload, 640, 400, options.trailing || null, host)};
}
const conformantIfd1 = () => [entry(259,3,1,shortBytes(6)), entry(513,4,1,longBytes(0)), entry(514,4,1,longBytes(0))];
const staleClockSpecimen = pageSpecimen('malformed clocks and an unusable GPS reference', conformantIfd1(), {
  exif:[
    entry(36867,2,20,ascii('2026:99:99 99:99:99',20)), entry(36881,2,7,ascii('+99:99',7)),
    entry(40962,4,1,longBytes(640)), entry(40963,4,1,longBytes(400))
  ],
  gps:[
    entry(1,2,2,ascii('Q',2)), entry(2,5,3,rationalBytes([[51,1],[30,1],[0,1]])),
    entry(3,2,2,ascii('E',2)), entry(4,5,3,rationalBytes([[0,1],[0,1],[0,1]])),
    entry(7,5,3,rationalBytes([[99,1],[99,1],[99,1]])), entry(29,2,11,ascii('2026:02:31',11))
  ]
});
const pageSpecimens = [
  {name:'the shipped fallback',bytes:fallback,isFallback:true,lastModified:FALLBACK_LAST_MODIFIED},
  pageSpecimen('big-endian file with IFD0 away from offset 8', [entry(259,3,1,shortBytes(6)), entry(513,4,1,longBytes(0)), entry(514,4,1,longBytes(0))]),
  pageSpecimen('no Compression tag at all', [entry(513,4,1,longBytes(0)), entry(514,4,1,longBytes(0))]),
  pageSpecimen('Compression 1 with a real JPEG stream', [entry(259,3,1,shortBytes(1)), entry(513,4,1,longBytes(0)), entry(514,4,1,longBytes(0))]),
  pageSpecimen('unsupported Compression 5 with no pointer pair', [entry(259,3,1,shortBytes(5)), entry(273,4,1,longBytes(0))], {thumbnail:null}),
  {name:'corrupt inner thumbnail stream',bytes:(() => { const b = copy(fallback); b[thumb.absoluteStart + 2] = 0x00; return b; })()},
  pageSpecimen('eight unaccounted bytes after EOI', conformantIfd1(), {trailing:Buffer.from([0x50,0x4b,0x03,0x04,0xde,0xad,0xbe,0xef])}),
  staleClockSpecimen,
  pageSpecimen('stale PixelXDimension and PixelYDimension', conformantIfd1(), {px:1280, py:800}),
  pageSpecimen('IFD1 with no thumbnail tags', [entry(274,3,1,shortBytes(1))], {thumbnail:null}),
  {name:'a file that is not a JPEG',bytes:new Uint8Array(Buffer.from('not a jpeg\n','ascii'))},
  {name:'a file refused before byte 0',bytes:fallback,declaredSize:100 * 1024 * 1024},
  {name:'a file the picker cannot read',bytes:fallback,readError:'the underlying file was moved or deleted'}
];
let pageRuns = null;
try {
  check(harnessAvailable(), 'the offline page harness has a JPEG decoder available');
  pageRuns = await runPageOn(pageSpecimens);
} catch (error) {
  check(false, 'the page module runs end to end under the offline harness', error.message);
}
if (pageRuns) {
  const byName = new Map(pageRuns.map(run => [run.name, run]));
  for (const run of pageRuns) check(run.threw === null, `page run does not throw on: ${run.name}`, run.threw ? run.threw.stack : '');
  const anchored = run => run.anchorLive.includes('Reproduced on the current file');
  const fallbackRun = byName.get('the shipped fallback');
  check(anchored(fallbackRun), 'the fallback run reproduces the published mechanism');
  check(fallbackRun.madScore === 'MAD / 255 = 0.113464', 'the fallback headline score is displayed', fallbackRun.madScore);
  check(/^\d+\/\d+ instrument checks pass\./.test(fallbackRun.checkScore) && !fallbackRun.checkScore.includes('not entitled'), 'every instrument check passes on the fallback', fallbackRun.checkScore);
  check(fallbackRun.checkLines.some(line => line.startsWith('FAIL CONFORMANCE') && line.includes('APP0')), 'the fallback run names its own forbidden APP0 marker');

  const notJpeg = byName.get('a file that is not a JPEG');
  check(notJpeg.fileStatus.startsWith('REFUSAL JPEG_WRONG_MAGIC at byte 0'), 'a refused file says so', notJpeg.fileStatus);
  check(!anchored(notJpeg), 'a refused file does not inherit the previous specimen anchor line', notJpeg.anchorLive);
  check(notJpeg.madScore === 'MAD / 255 = unavailable', 'a refused file does not inherit the previous headline score', notJpeg.madScore);
  check(!notJpeg.compareStatus.includes('Observation under the named choices'), 'a refused file does not inherit the previous comparison observation', notJpeg.compareStatus);
  check(notJpeg.pixelNote.startsWith('No stored PixelXDimension'), 'a refused file does not inherit the previous second indicator', notJpeg.pixelNote);
  check(notJpeg.clockNote.startsWith('No stored time components'), 'a refused file does not inherit the previous clock span', notJpeg.clockNote);
  check(notJpeg.checkScore.includes('refusal checks pass'), 'a refused file reports refusal checks rather than a stale score', notJpeg.checkScore);

  const bigEndian = byName.get('big-endian file with IFD0 away from offset 8');
  check(anchored(bigEndian), 'a big-endian file at an unusual IFD0 offset still reproduces the mechanism', bigEndian.anchorLive);
  check(bigEndian.madScore === 'MAD / 255 = 0.113464', 'the same thumbnail gives the same score through a different byte order', bigEndian.madScore);

  const noCompression = byName.get('no Compression tag at all');
  check(noCompression.anchorLive.startsWith('Not reproduced as printed'), 'a recovered thumbnail is never reported as reproducing the published mechanism', noCompression.anchorLive);
  check(noCompression.checkLines.some(line => line.startsWith('FAIL ANCHOR')), 'the recovery is flagged on its own line');
  check(noCompression.madScore === 'MAD / 255 = 0.113464', 'the recovered thumbnail still reaches the comparison', noCompression.madScore);

  const mislabelledRun = byName.get('Compression 1 with a real JPEG stream');
  check(mislabelledRun.anchorLive.includes('declares Compression 1'), 'the mislabelled specimen names its declared compression', mislabelledRun.anchorLive);
  check(mislabelledRun.madScore === 'MAD / 255 = 0.113464', 'the mislabelled specimen still reaches the comparison', mislabelledRun.madScore);

  const unsupportedRun = byName.get('unsupported Compression 5 with no pointer pair');
  check(unsupportedRun.structure.includes('THUMBNAIL_UNSUPPORTED_COMPRESSION at byte'), 'an unsupported compression value refuses with a code and a byte', unsupportedRun.structure);
  check(unsupportedRun.madScore === 'MAD / 255 = unavailable', 'an unsupported compression value produces no comparison', unsupportedRun.madScore);

  const corrupt = byName.get('corrupt inner thumbnail stream');
  check(corrupt.fileStatus.includes('did not decode'), 'a corrupt inner stream is reported as a decode refusal, not as a success', corrupt.fileStatus);
  check(corrupt.fileStatus.includes('slice byte 2') && corrupt.fileStatus.includes('file byte 670'), 'the inner refusal names both the slice byte and the file byte', corrupt.fileStatus);
  check(corrupt.madScore === 'MAD / 255 = unavailable', 'a corrupt inner stream produces no comparison', corrupt.madScore);

  const trailingRun = byName.get('eight unaccounted bytes after EOI');
  check(trailingRun.checkLines.some(line => line.startsWith('FAIL FILE: 8 bytes follow the terminal EOI')), 'trailing bytes are surfaced rather than silently accepted');
  check(trailingRun.facts.some(fact => fact.startsWith('bytes after terminal EOI = 8')), 'the trailing byte count is displayed as a file fact', trailingRun.facts.join(' | '));

  const clocks = byName.get('malformed clocks and an unusable GPS reference');
  check(clocks.clockNote.startsWith('Only File.lastModified'), 'a malformed stored clock is kept out of the absolute timeline', clocks.clockNote);
  check(clocks.gpsOutput.includes('is not one of N or S'), 'an unusable GPS reference is refused with a reason instead of read as positive', clocks.gpsOutput);
  check(!clocks.gpsOutput.includes('51.5'), 'no coordinate is printed from an unusable reference', clocks.gpsOutput);

  const staleDims = byName.get('stale PixelXDimension and PixelYDimension');
  check(staleDims.pixelNote.includes('stale with respect to the compressed data'), 'a stale stored dimension pair is named', staleDims.pixelNote);
  check(staleDims.checkLines.some(line => line.startsWith('FAIL SECOND INDICATOR')), 'the stale dimension pair gets its own red line');

  // The two paths that return before any rendering runs. These are the only paths where
  // resetVisuals is the sole thing standing between a new specimen and the previous one's
  // displayed conclusions, so they are asserted field by field.
  for (const label of ['a file refused before byte 0','a file the picker cannot read']) {
    const early = byName.get(label);
    check(early.anchorLive.startsWith('No current file has completed the CIPA thumbnail walk'), `${label}: the anchor line is reset rather than left from the previous specimen`, early.anchorLive);
    check(early.madScore === 'MAD / 255 = unavailable', `${label}: the headline score does not survive`, early.madScore);
    check(!early.compareStatus.includes('Observation under the named choices'), `${label}: the comparison observation does not survive`, early.compareStatus);
    check(early.pixelNote.startsWith('No stored PixelXDimension'), `${label}: the second indicator does not survive`, early.pixelNote);
    check(early.clockNote.startsWith('No stored time components'), `${label}: the clock span does not survive`, early.clockNote);
    check(early.structure.startsWith('No accepted JPEG structure'), `${label}: the structure line does not survive`, early.structure);
    check(early.staleNote.startsWith('No comparison is current'), `${label}: the control-invariance note does not survive`, early.staleNote);
    check(early.checkScore.includes('refusal checks pass'), `${label}: the check score is the refusal score`, early.checkScore);
    check(early.checkLines.length === 2 && early.checkLines.every(line => line.startsWith('PASS REFUSAL')), `${label}: exactly the two refusal checks are listed and both pass`, early.checkLines.join(' | '));
  }
  check(byName.get('a file refused before byte 0').fileStatus.includes('FILE_TOO_LARGE before byte 0'), 'an oversized file is refused before any byte is read');
  check(byName.get('a file the picker cannot read').fileStatus.includes('FILE_READ_ERROR'), 'an unreadable file is refused with its own code');

  const noThumb = byName.get('IFD1 with no thumbnail tags');
  check(noThumb.structure.includes('declares no thumbnail this instrument can follow'), 'an IFD1 without thumbnail tags is a normal negative result', noThumb.structure);
  check(noThumb.madScore === 'MAD / 255 = unavailable', 'no thumbnail means no comparison', noThumb.madScore);
  check(!noThumb.checkScore.includes('not entitled'), 'a file with no thumbnail is not treated as an instrument failure', noThumb.checkScore);
}

for (const line of results) console.log(line);
console.log(`\n${passed}/${passed + failed} checks pass.`);
console.log(`Fallback: ${fallback.length} bytes, SHA-256 ${sha(fallback)}.`);
console.log(`Thumbnail: bytes ${thumb.absoluteStart}..${thumb.absoluteEnd}, ${thumb.length} bytes, SHA-256 ${sha(thumb.bytes)}.`);
console.log(`Offline ImageMagick default MAD / 255: ${offlineMad === null ? 'unavailable' : offlineMad.toFixed(9)}.`);
if (failed) process.exit(1);
