#!/usr/bin/env node
// validate.mjs — check every row in this directory against schema.json.
//
//   node validate.mjs            # validate every data file beside this script
//   node validate.mjs FILE…      # validate named files
//
// Dependency-free and self-contained on purpose: this folder is meant to keep working
// if artwaste.land goes away. It also re-checks the sha256 and row count recorded in
// manifest.json, so you can tell whether you have the bytes we described.
//
// Generated by research/data-room/publish.mjs. Do not edit here.

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

const here = path.dirname(fileURLToPath(import.meta.url));

// A dependency-free JSON Schema (draft 2020-12, working subset) validator.
//
// PROVENANCE, because copying without saying so is how a codebase forgets: the
// core of this is lifted from public/data/hansard-reactions/validate.mjs, written
// 2026-09-03 for the Hansard concordance, which was the first dataset this project
// published with a schema that anyone could actually run. It is generalised here so
// every dataset in the room can be checked by the same code path, and so the
// per-dataset validate.mjs that ships inside each download can be GENERATED rather
// than hand-copied eight times.
//
// The subset is deliberate. It covers what our own schemas use — type, const, enum,
// required, properties, additionalProperties, items, min/max on numbers, strings and
// arrays, pattern, format date/uri, $ref within the document, and the combinators —
// and nothing else. An unsupported keyword is IGNORED rather than treated as passing
// silently by accident, so assertUsesOnlySupportedKeywords() below exists to make
// that failure loud: a schema that leans on a keyword this validator does not
// implement is rejected before it can certify anything.

const SUPPORTED = new Set([
  '$schema', '$id', '$defs', '$ref', '$comment',
  'title', 'description', 'examples', 'default', 'deprecated',
  'type', 'const', 'enum',
  'allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else',
  'properties', 'required', 'additionalProperties',
  'items', 'minItems', 'maxItems', 'uniqueItems',
  'minLength', 'maxLength', 'pattern', 'format',
  'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf',
  // Ours, not JSON Schema's: every leaf property in a data-room schema declares
  // where its value came from. The standard's ORIGIN check reads it.
  'x-origin', 'x-source',
]);

const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);

function typeMatches(value, expected) {
  if (expected === 'null') return value === null;
  if (expected === 'array') return Array.isArray(value);
  if (expected === 'object') return value !== null && typeof value === 'object' && !Array.isArray(value);
  if (expected === 'integer') return Number.isInteger(value);
  if (expected === 'number') return typeof value === 'number' && Number.isFinite(value);
  return typeof value === expected; // string, boolean
}

function validDate(value) {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
  if (!m) return false;
  const d = new Date(`${value}T00:00:00Z`);
  return !Number.isNaN(d.valueOf()) &&
    d.getUTCFullYear() === Number(m[1]) &&
    d.getUTCMonth() + 1 === Number(m[2]) &&
    d.getUTCDate() === Number(m[3]);
}

// Walk every subschema, so callers can audit keywords and x-origin coverage.
function* walk(schema, at = '#') {
  if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) return;
  yield [at, schema];
  for (const key of ['properties', '$defs']) {
    for (const [name, child] of Object.entries(schema[key] ?? {})) yield* walk(child, `${at}/${key}/${name}`);
  }
  for (const key of ['items', 'not', 'if', 'then', 'else', 'additionalProperties']) {
    if (schema[key] && typeof schema[key] === 'object') yield* walk(schema[key], `${at}/${key}`);
  }
  for (const key of ['allOf', 'anyOf', 'oneOf']) {
    const branches = schema[key] ?? [];
    for (let i = 0; i < branches.length; i++) yield* walk(branches[i], `${at}/${key}/${i}`);
  }
}

// Loud rather than silent: name every keyword we would have ignored.
function unsupportedKeywords(schema) {
  const found = new Set();
  for (const [, node] of walk(schema)) {
    for (const k of Object.keys(node)) if (!SUPPORTED.has(k)) found.add(k);
  }
  return [...found].sort();
}

// ---------------------------------------------------------------------------
// CSV, for the datasets whose rows are flat scalars. A 720,000-row table of numbers
// belongs in a CSV that loads straight into pandas, R or a spreadsheet, not in JSONL
// where every row repeats its keys — the same table cost 157 MB as JSONL and 36 MB
// here. The schema stays the single contract: these helpers rebuild a typed row object
// from the header line so the SAME validator checks it, rather than a second, weaker
// set of rules growing up around the CSV.

// RFC 4180 fields: quoted fields may contain commas, newlines are not supported inside
// fields (no dataset here needs them, and splitCsvLine would silently corrupt one, so
// writeCsv refuses to emit any value containing a newline).
function splitCsvLine(line) {
  const out = [];
  let field = '', quoted = false;
  for (let i = 0; i < line.length; i++) {
    const c = line[i];
    if (quoted) {
      if (c === '"') { if (line[i + 1] === '"') { field += '"'; i++; } else quoted = false; }
      else field += c;
    } else if (c === '"') quoted = true;
    else if (c === ',') { out.push(field); field = ''; }
    else field += c;
  }
  out.push(field);
  return out;
}

const csvCell = (v) => {
  if (v === null || v === undefined) return '';
  const s = String(v);
  if (/[\r\n]/.test(s)) throw new Error(`a CSV value contains a newline, which this writer refuses to emit: ${JSON.stringify(s.slice(0, 60))}`);
  return /[",]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s;
};

function writeCsv(headers, rows) {
  const lines = [headers.map(csvCell).join(',')];
  for (const r of rows) lines.push(headers.map((h) => csvCell(r[h])).join(','));
  return lines.join('\n') + '\n';
}

// An empty cell is null. Everything else is coerced by the type the schema declares,
// so "3" validates as an integer and "abc" fails as one rather than passing as a string.
function csvRowToObject(headers, cells, schema) {
  const row = {};
  for (let i = 0; i < headers.length; i++) {
    const name = headers[i];
    const raw = cells[i] ?? '';
    const prop = schema.properties?.[name];
    const types = prop ? (Array.isArray(prop.type) ? prop.type : [prop.type]) : ['string'];
    if (raw === '') { row[name] = types.includes('null') ? null : ''; continue; }
    if (types.includes('boolean') && (raw === 'true' || raw === 'false')) { row[name] = raw === 'true'; continue; }
    if (types.includes('number') || types.includes('integer')) {
      const n = Number(raw);
      row[name] = Number.isNaN(n) ? raw : n;
      continue;
    }
    row[name] = raw;
  }
  return row;
}

function makeValidator(schema) {
  const resolveRef = (ref) => {
    if (!ref.startsWith('#/')) throw new Error(`unsupported external $ref: ${ref}`);
    return ref.slice(2).split('/')
      .map((p) => p.replaceAll('~1', '/').replaceAll('~0', '~'))
      .reduce((v, p) => v[p], schema);
  };

  function validate(value, rule = schema, location = '$') {
    if (rule === true) return [];
    if (rule === false) return [`${location}: forbidden by schema`];
    if (rule.$ref) return validate(value, resolveRef(rule.$ref), location);

    const errors = [];
    if (rule.type) {
      const expected = Array.isArray(rule.type) ? rule.type : [rule.type];
      if (!expected.some((t) => typeMatches(value, t))) return [`${location}: expected ${expected.join(' or ')}`];
    }
    if (Object.hasOwn(rule, 'const') && !same(value, rule.const)) {
      errors.push(`${location}: must equal ${JSON.stringify(rule.const)}`);
    }
    if (rule.enum && !rule.enum.some((c) => same(value, c))) {
      errors.push(`${location}: not one of ${rule.enum.map((v) => JSON.stringify(v)).join(', ')}`);
    }

    if (rule.allOf) for (const child of rule.allOf) errors.push(...validate(value, child, location));
    if (rule.anyOf && !rule.anyOf.some((c) => validate(value, c, location).length === 0)) {
      errors.push(`${location}: does not match any anyOf branch`);
    }
    if (rule.oneOf) {
      const n = rule.oneOf.filter((c) => validate(value, c, location).length === 0).length;
      if (n !== 1) errors.push(`${location}: must match exactly one oneOf branch, matched ${n}`);
    }
    if (rule.not && validate(value, rule.not, location).length === 0) {
      errors.push(`${location}: matches a forbidden schema`);
    }
    if (rule.if) {
      const branch = validate(value, rule.if, location).length === 0 ? rule.then : rule.else;
      if (branch) errors.push(...validate(value, branch, location));
    }

    if (typeof value === 'string') {
      const len = [...value].length;
      if (rule.minLength !== undefined && len < rule.minLength) errors.push(`${location}: shorter than minLength ${rule.minLength}`);
      if (rule.maxLength !== undefined && len > rule.maxLength) errors.push(`${location}: longer than maxLength ${rule.maxLength}`);
      if (rule.pattern && !new RegExp(rule.pattern, 'u').test(value)) errors.push(`${location}: does not match ${rule.pattern}`);
      if (rule.format === 'date' && !validDate(value)) errors.push(`${location}: is not a real RFC 3339 full-date`);
      if (rule.format === 'uri') { try { new URL(value); } catch { errors.push(`${location}: is not an absolute URI`); } }
    }

    if (typeof value === 'number') {
      if (rule.minimum !== undefined && value < rule.minimum) errors.push(`${location}: below minimum ${rule.minimum}`);
      if (rule.maximum !== undefined && value > rule.maximum) errors.push(`${location}: above maximum ${rule.maximum}`);
      if (rule.exclusiveMinimum !== undefined && value <= rule.exclusiveMinimum) errors.push(`${location}: not above ${rule.exclusiveMinimum}`);
      if (rule.exclusiveMaximum !== undefined && value >= rule.exclusiveMaximum) errors.push(`${location}: not below ${rule.exclusiveMaximum}`);
      if (rule.multipleOf !== undefined && Math.abs(value / rule.multipleOf - Math.round(value / rule.multipleOf)) > 1e-9) {
        errors.push(`${location}: not a multiple of ${rule.multipleOf}`);
      }
    }

    if (Array.isArray(value)) {
      if (rule.minItems !== undefined && value.length < rule.minItems) errors.push(`${location}: fewer than minItems ${rule.minItems}`);
      if (rule.maxItems !== undefined && value.length > rule.maxItems) errors.push(`${location}: more than maxItems ${rule.maxItems}`);
      if (rule.uniqueItems && new Set(value.map((v) => JSON.stringify(v))).size !== value.length) {
        errors.push(`${location}: items are not unique`);
      }
      if (rule.items) value.forEach((item, i) => errors.push(...validate(item, rule.items, `${location}[${i}]`)));
    }

    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
      for (const key of rule.required ?? []) {
        if (!Object.hasOwn(value, key)) errors.push(`${location}: missing required property ${JSON.stringify(key)}`);
      }
      for (const [key, child] of Object.entries(rule.properties ?? {})) {
        if (Object.hasOwn(value, key)) errors.push(...validate(value[key], child, `${location}.${key}`));
      }
      if (rule.additionalProperties === false) {
        const allowed = new Set(Object.keys(rule.properties ?? {}));
        for (const key of Object.keys(value)) {
          if (!allowed.has(key)) errors.push(`${location}: unexpected property ${JSON.stringify(key)}`);
        }
      }
    }

    return errors;
  }

  return validate;
}


const schema = JSON.parse(fs.readFileSync(path.join(here, 'schema.json'), 'utf8'));
const bad = unsupportedKeywords(schema);
if (bad.length) {
  console.error('FAIL: schema.json uses keywords this validator does not implement: ' + bad.join(', '));
  process.exit(2);
}
const validate = makeValidator(schema);

const DATA_EXT = new Set(['.jsonl', '.csv']);
const RESERVED = new Set(['schema.json', 'sources.json', 'manifest.json', 'README.md', 'validate.mjs']);
const named = process.argv.slice(2).filter((a) => !a.startsWith('-'));
const files = named.length
  ? named.map((f) => path.resolve(f))
  : fs.readdirSync(here).filter((f) => DATA_EXT.has(path.extname(f)) && !RESERVED.has(f)).sort().map((f) => path.join(here, f));

if (!files.length) { console.error('FAIL: no .jsonl or .csv data files found beside validate.mjs'); process.exit(2); }

let rows = 0, violations = 0;
const report = (file, n, errors) => {
  violations++;
  console.error(`FAIL ${path.basename(file)}:${n}`);
  for (const e of errors.slice(0, 8)) console.error('  ' + e);
  if (errors.length > 8) console.error(`  … ${errors.length - 8} more`);
};
for (const file of files) {
  const lines = fs.readFileSync(file, 'utf8').split('\n');
  if (path.extname(file) === '.csv') {
    const headers = splitCsvLine(lines[0] ?? '');
    for (let i = 1; i < lines.length; i++) {
      if (lines[i] === '') continue;
      rows++;
      const errors = validate(csvRowToObject(headers, splitCsvLine(lines[i]), schema));
      if (errors.length) report(file, i + 1, errors);
    }
    continue;
  }
  let n = 0;
  for (const line of lines) {
    n++;
    if (line.trim() === '') continue;
    rows++;
    let record;
    try { record = JSON.parse(line); }
    catch (e) { violations++; console.error(`FAIL ${path.basename(file)}:${n}: invalid JSON: ${e.message}`); continue; }
    const errors = validate(record);
    if (errors.length) report(file, n, errors);
  }
}
console.log(`Checked ${rows.toLocaleString('en-US')} rows in ${files.length} file(s) against schema.json.`);

// The manifest half: are these the bytes we described?
let fixity = 0, fixityBad = 0;
const manPath = path.join(here, 'manifest.json');
if (fs.existsSync(manPath)) {
  const manifest = JSON.parse(fs.readFileSync(manPath, 'utf8'));
  for (const entry of manifest.files ?? []) {
    const p = path.join(here, entry.name);
    if (!fs.existsSync(p)) { fixityBad++; console.error(`FAIL ${entry.name}: listed in manifest.json, missing here`); continue; }
    const buf = fs.readFileSync(p);
    const digest = createHash('sha256').update(buf).digest('hex');
    if (buf.length !== entry.bytes) { fixityBad++; console.error(`FAIL ${entry.name}: ${buf.length} bytes, manifest says ${entry.bytes}`); }
    else if (digest !== entry.sha256) { fixityBad++; console.error(`FAIL ${entry.name}: sha256 ${digest.slice(0, 16)}… differs from manifest`); }
    else fixity++;
  }
  console.log(`Verified ${fixity} file(s) against the sha256 in manifest.json.`);
} else {
  console.log('No manifest.json here, so nothing was checked for fixity.');
}

if (violations || fixityBad) {
  console.error(`FAIL: ${violations} schema violation(s), ${fixityBad} fixity failure(s).`);
  process.exit(1);
}
console.log(fs.existsSync(manPath)
  ? 'PASS: every row satisfies schema.json and every file matches its recorded digest.'
  : 'PASS: every row satisfies schema.json. File digests were NOT checked: download manifest.json beside these files to check them.');
