#!/usr/bin/env node
// verify-extractor.mjs — assertions for the parts of this study that could quietly lie.
//
//   node research/the-laws-own-arithmetic/verify-extractor.mjs
//
// Every case here is either a real string from the CFR or a construction of one of the
// five false-positive classes the prototype produced. The extractor is not allowed to
// run over 824 MB of regulation until it gets all of these right, because a defect in
// any one of them turns into a published sentence saying a regulation is wrong when it
// is not.

import { Rat, roundToSigFigs, roundToPlaces } from './lib/rational.mjs';
import { lookupUnit, convert, UNITS } from './lib/units.mjs';
import { readNumber, scanQuantities, findPairs } from './lib/scan.mjs';
import { walkTitle } from './lib/xml.mjs';
import { classifyPair } from './lib/compare.mjs';

let pass = 0;
const failures = [];
function check(name, got, want) {
  const g = typeof got === 'string' ? got : JSON.stringify(got);
  const w = typeof want === 'string' ? want : JSON.stringify(want);
  if (g === w) pass++;
  else failures.push(`${name}\n     got  ${g}\n     want ${w}`);
}
function ok(name, cond, detail = '') {
  if (cond) pass++;
  else failures.push(`${name}${detail ? `\n     ${detail}` : ''}`);
}

// --- exact arithmetic ------------------------------------------------------
check('Rat parses a leading-dot decimal', Rat.parse('.020').toString(), '1/50');
check('Rat parses thousands separators', Rat.parse('1,250.5').toString(), '2501/2');
check('Rat parses a negative', Rat.parse('-40').toString(), '-40');
check('Rat rounds half away from zero', Rat.parse('2.5').toFixed(0), '3');
check('Rat renders a repeating rational to places', Rat.parse('1').div(Rat.parse('3')).toFixed(6), '0.333333');
check('roundToSigFigs(1234.5, 3)', roundToSigFigs(Rat.parse('1234.5'), 3).toString(), '1230');
check('roundToSigFigs(0.0035271, 2)', roundToSigFigs(Rat.parse('0.0035271'), 2).toString(), '7/2000');
check('roundToPlaces(0.508, 1)', roundToPlaces(Rat.parse('0.508'), 1).toString(), '1/2');

// --- the defined conversions are exact -------------------------------------
check('1 in is exactly 25.4 mm', convert(Rat.parse('1'), UNITS.in, UNITS.mm).toString(), '127/5');
check('1 lb is exactly 0.45359237 kg', convert(Rat.parse('1'), UNITS.lb, UNITS.kg).toString(), '45359237/100000000');
check('1 lbf in newtons', convert(Rat.parse('1'), UNITS.lbf, UNITS.N).toPrecision(14), '4.4482216152605');
check('1 gal is exactly 3.785411784 L', convert(Rat.parse('1'), UNITS.gal, UNITS.L).toPrecision(10), '3.785411784');
check('1 acre in m2', convert(Rat.parse('1'), UNITS.acre, UNITS.m2).toPrecision(11), '4046.8564224');
check('-40 degC is -40 degF', convert(Rat.parse('-40'), UNITS.degC, UNITS.degF).toString(), '-40');
check('212 degF is 100 degC', convert(Rat.parse('212'), UNITS.degF, UNITS.degC).toString(), '100');
check('1 psi in Pa', convert(Rat.parse('1'), UNITS.psi, UNITS.Pa).toPrecision(10), '6894.757293');
check('1 ft2 in in2', convert(Rat.parse('1'), UNITS.ft2, UNITS.in2).toString(), '144');
check('1 m3 in L', convert(Rat.parse('1'), UNITS.m3, UNITS.L).toString(), '1000');
check('1 cm2 in mm2', convert(Rat.parse('1'), UNITS.cm2, UNITS.mm2).toString(), '100');
check('1 ft3 in in3', convert(Rat.parse('1'), UNITS.ft3, UNITS.in3).toString(), '1728');
ok('BTU is flagged inexact', UNITS.btu.exact === false);
ok('calorie is flagged inexact', UNITS.cal.exact === false);
ok('horsepower is flagged inexact', UNITS.hp.exact === false);
ok('inch of mercury is flagged inexact', UNITS.inHg.exact === false);
ok('the pound is exact', UNITS.lb.exact === true);

// --- number reading --------------------------------------------------------
check('reads a simple fraction', readNumber('1/2-inch', 0).value.toString(), '1/2');
check('reads a mixed fraction', readNumber('1 1/2 inches', 0).value.toString(), '3/2');
check('reads a hyphenated mixed fraction', readNumber('1-1/2 inch', 0).value.toString(), '3/2');
check('does not read a date as a fraction', readNumber('1/2/2020', 0).value.toString(), '1');
check('reads e-notation', readNumber('2.5e-3 g', 0).value.toString(), '1/400');
check('reads a superscript exponent', readNumber('2.5 × 10^(-3) g', 0).value.toString(), '1/400');
check('records significant figures', String(readNumber('0.0035', 0).sigfigs), '2');
check('records decimal places', String(readNumber('0.0035', 0).places), '4');

// --- unit lookup -----------------------------------------------------------
check('Kn resolves to kilonewtons', lookupUnit('Kn').id, 'kN');
check('in. resolves to inches', lookupUnit('in.').id, 'in');
check('cu. ft. resolves to cubic feet', lookupUnit('cu. ft.').id, 'ft3');
check('sq. in. resolves to square inches', lookupUnit('sq. in.').id, 'in2');
ok('a bare C does not resolve to Celsius', lookupUnit('C') === null);
ok('a bare F does not resolve to Fahrenheit', lookupUnit('F') === null);
ok('gr does not resolve to grains', lookupUnit('gr') === null);

// --- quantity scanning -----------------------------------------------------
const q1 = scanQuantities('not more than 100 mg (0.0035 ounce) of gallium');
check('scans two quantities from the gallium sentence', String(q1.length), '2');
check('the first is 100 mg', `${q1[0].value} ${q1[0].unit.id}`, '100 mg');
check('the second is 0.0035 oz', `${q1[1].value.toString()} ${q1[1].unit.id}`, '7/2000 oz');
const q2 = scanQuantities('a 12" x 24" panel');
check('reads the inch mark', `${q2.length} ${q2[0].unit.id}`, '2 in');
const q3 = scanQuantities('1,250 pounds of force');
check('reads thousands separators in running text', q3[0].value.toString(), '1250');
ok('does not read "3 in 4 cases" as 3 inches followed by 4', (() => {
  const q = scanQuantities('3 in 4 cases');
  return q.length === 1 && q[0].unit.id === 'in';
})(), 'known limitation: a bare "in" before a number is still read as inches; it is marked weak');

// --- pair finding, and the five false-positive classes ---------------------
function pairsOf(text) {
  const qs = scanQuantities(text);
  return findPairs(text, qs);
}
const gal = pairsOf('not more than 100 mg (0.0035 ounce) of gallium');
check('finds the gallium pair', String(gal.length), '1');
check('the gallium pair is clean', JSON.stringify(gal[0].flags), '[]');

const tol = pairsOf('a length of 254 mm ±3 mm (10 inches)');
check('finds the tolerance pair', String(tol.length), '1');
ok('the tolerance pair is flagged', tol[0].flags.includes('tolerance'), JSON.stringify(tol[0].flags));
check('the tolerance pair converts the 254, not the 3', tol[0].a.value.toString(), '254');

const comp = pairsOf('a height of 6 feet, 6 inches (1.98 m)');
check('finds the compound pair', String(comp.length), '1');
ok('the compound pair is flagged', comp[0].flags.includes('compound-quantity'), JSON.stringify(comp[0].flags));

const den = pairsOf('a fire load of 37.5 kg (7.5 pounds) of combustibles per square meter');
ok('the trailing denominator is flagged', den.length === 1 && den[0].flags.includes('denominator-after'), JSON.stringify(den[0] && den[0].flags));

const sci = pairsOf('a dose of 2.5 × 10^(-3) g (2.5 mg)');
ok('a scientific-notation pair is flagged', sci.length === 1 && sci[0].flags.includes('scientific'), JSON.stringify(sci[0] && sci[0].flags));

const hedge = pairsOf('a mass of 100 g (about 3.5 ounces)');
ok('a hedged parenthetical is still a pair', hedge.length === 1 && hedge[0].flags.includes('hedged'), JSON.stringify(hedge[0] && hedge[0].flags));

ok('a citation in parentheses is not a pair', pairsOf('the limit of 5 mg (see 40 CFR 60.15) applies').length === 0);
ok('a two-quantity parenthetical is not a pair', pairsOf('a plate 5 mm (3 in by 4 in) thick').length === 0);

// --- classification --------------------------------------------------------
const cls = (text) => {
  const p = pairsOf(text)[0];
  return classifyPair(p);
};
check('100 mg (0.0035 ounce) agrees', cls('not more than 100 mg (0.0035 ounce)').verdict, 'agree');
check('1 g (0.35 ounce) disagrees', cls('does not exceed 1 g (0.35 ounce)').verdict, 'discrepant');
check('the gallium discrepancy is a factor of ten', cls('does not exceed 1 g (0.35 ounce)').ratio.toPrecision(4), '9.922');
check('1/2-inch (13 mm) agrees: 12.7 rounds to 13', cls('a 1/2-inch (13 mm) nut').verdict, 'agree');
check('.020 inch (5.1 mm) disagrees', cls('a .020 inch (5.1 mm) washer').verdict, 'discrepant');
check('7.5 mm (3 in.) disagrees', cls('7.5 mm (3 in.) circumference manila').verdict, 'discrepant');
check('-40 degC (-40 degF) agrees', cls('at -40 °C (-40 °F)').verdict, 'agree');
check('a BTU pair that agrees under the IT definition agrees', cls('1,000 Btu (1.055 MJ)').verdict, 'agree');
check('but it is marked definition-dependent', String(cls('1,000 Btu (1.055 MJ)').definitionDependent), 'true');
check('a BTU pair that disagrees is never called an error', cls('1,000 Btu (1.100 MJ)').verdict, 'inexact-unit');
check('2,250 pounds (10.01 kN) re-reads pounds as force', cls('2,250 pounds (10.01 kN)').reading, 'force-reading');
check('2,250 pounds (10.01 kN) then agrees', cls('2,250 pounds (10.01 kN)').verdict, 'agree');

// --- the XML walk ----------------------------------------------------------
const xml = `<DIV5 N="25" TYPE="PART"><HEAD>PART 25</HEAD>
<DIV8 N="§ 25.853" NODE="14:1" TYPE="SECTION"><HEAD>§ 25.853 Compartment interiors.</HEAD>
<P>The specimen shall be 1/2 inch (13 mm) thick.</P></DIV8>
<DIV9 N="Appendix F to Part 25" TYPE="APPENDIX"><HEAD>Appendix F to Part 25</HEAD>
<P>Use a .020 inch (5.1 mm) thick wide area washer and a 1,<E T="03">250</E> gram weight.</P>
<P>A concentration of 2.5×10<SU>-3</SU> g is required.</P></DIV9></DIV5>`;
const blocks = [];
walkTitle(xml, 14, (b) => blocks.push(b));
const sectionBlock = blocks.find((b) => b.text.includes('1/2 inch'));
const appendixBlock = blocks.find((b) => b.text.includes('.020 inch'));
check('a section paragraph is cited to its section', sectionBlock.cite, '14 CFR 25.853');
check('an appendix paragraph is NOT cited to the last section', appendixBlock.cite, '14 CFR part 25, Appendix F to Part 25');
check('the appendix knows it has no section', String(appendixBlock.section), 'null');
ok('markup inside a number is rejoined', appendixBlock.text.includes('1,250 gram'), appendixBlock.text);
const supBlock = blocks.find((b) => b.text.includes('concentration'));
ok('a superscript exponent survives as one token', supBlock.text.includes('10^(-3)'), supBlock.text);
check('the superscript parses to 0.0025', String(scanQuantities(supBlock.text)[0].value.toString()), '1/400');

// --- cases found by running the extractor over a real title -----------------
// Everything below was a false positive in the first full extraction of title 49, or a
// real finding that the first extractor could not see. They are assertions now so that
// no later change quietly reintroduces them.

// A temperature INTERVAL converts with no offset, and the CFR writes intervals in the
// same notation as temperatures. Nine of title 49's thirty-seven first-pass errors.
check('20 degC (36 degF) read as an interval agrees', cls('a rise of 20 \u00b0C (36 \u00b0F)').verdict, 'agree');
check('and the row says which reading saved it', cls('a rise of 20 \u00b0C (36 \u00b0F)').reading, 'temperature-interval');
check('5 degC (9 degF) likewise', cls('within 5 \u00b0C (9 \u00b0F)').verdict, 'agree');
check('a real temperature pair still agrees directly', cls('at 55 \u00b0C (131 \u00b0F)').reading, 'direct');
check('and a wrong one is still caught', cls('at 55 \u00b0C (150 \u00b0F)').verdict, 'discrepant');

// "53 +/-1.0 km/h (33.5 mph)": the base of the tolerance carries no unit of its own,
// so the parenthetical converts a number that was never a quantity by itself.
const bareTol = pairsOf('a 53 \u00b11.0 km/h impact (33.5 mph)');
const bareTol2 = pairsOf('in a 53 \u00b11.0 km/h (33.5 mph) impact');
ok('a bare tolerance base is recovered', bareTol2.length === 1 && bareTol2[0].flags.includes('tolerance-bare-base'), JSON.stringify(bareTol2[0] && bareTol2[0].flags));
check('and the recovered base is the 53', bareTol2[0].a.value.toString(), '53');

// "0.076 mm (0.003 in) +/-0.004 mm (0.002 in)": the tolerance owns its own parenthetical,
// so it is a pair in its own right and must NOT be rewritten to the base.
const ownPair = pairsOf('a thickness of 0.076 mm (0.003 in) \u00b10.004 mm (0.002 in)');
ok('a tolerance with its own parenthetical stays its own pair',
  ownPair.some((p) => p.flags.includes('tolerance-own-pair') && p.a.value.toString() === '1/250'),
  JSON.stringify(ownPair.map((p) => [p.verbatim, p.flags])));

// The slash of a written fraction is not a compound unit.
const fracPair = pairsOf('shall not exceed 5/8 inch (16 mm) in width');
ok('a fraction slash is not read as a rate', fracPair.length === 1 && !fracPair[0].flags.includes('slash-or-per-inside'), JSON.stringify(fracPair[0] && fracPair[0].flags));
check('and 5/8 inch is 16 mm', fracPair[0] && classifyPair(fracPair[0]).verdict, 'agree');
ok('a real rate still gets the flag', pairsOf('a flow of 10 gal/min (38 L) per minute').every((p) => p.flags.includes('slash-or-per-inside')));

// Shapes that look like conversions and are not.
check('"(or 96 hours)" is an alternative, not a conversion', cls('during the 48 hours (or 96 hours) following delivery').verdict, 'alternative');
check('a same-unit parenthetical asserts no conversion', cls('transfer a 100 mL (1 mL) aliquot').verdict, 'same-unit');
check('a percentage-of parenthetical is not a conversion', cls('accurate to within \u00b1 0.5 percent of 3 liters (15 milliliters)').verdict, 'percent-of');
check('the eight-hour day is a convention, not an error', cls('a period of 90 days (720 hours)').verdict, 'agree');
check('and it is named', cls('a period of 90 days (720 hours)').reading, 'eight-hour-day');

// "nm" is nanometres in a spectroscopy method and nautical miles in a fishery closure.
check('nm read as nautical miles where that is what it means', cls('the area within 15 nm (27.78 km) of the point').verdict, 'agree');
check('and the re-reading is named', cls('the area within 15 nm (27.78 km) of the point').reading, 'ambiguous-unit');
check('nm still reads as nanometres where THAT is what it means', cls('a wavelength of 254 nm (0.254 \u00b5m)').verdict, 'agree');
check('and that reading is not re-read', cls('a wavelength of 254 nm (0.254 \u00b5m)').reading, 'direct');

// GPO writes exponents as <E T="51">, not as <SU>.
const eXml = `<DIV5 N="774" TYPE="PART"><DIV8 N="\u00a7 774.1" NODE="15:2" TYPE="SECTION"><P>a particle size of 50 \u00d7 10<E T="51">-6</E> m (50 \u00b5m) or less</P></DIV8></DIV5>`;
const eBlocks = [];
walkTitle(eXml, 15, (bk) => eBlocks.push(bk));
ok('a GPO superscript exponent survives', eBlocks[0].text.includes('10^(-6)'), eBlocks[0].text);
check('and the pair then agrees', cls(eBlocks[0].text).verdict, 'agree');

// A fraction whose whole number is separated from it by a hyphen AND a newline.
check('"1- 1/4 inches" is one and a quarter', readNumber('1- 1/4 inches', 0).value.toString(), '5/4');
check('and the pair then agrees', cls('a circle 1- 1/4 inches (31.8 mm) in diameter').verdict, 'agree');

// Typographic defects in the Code's own text, which are not arithmetic errors.
check('a thousands separator broken by a space is repaired only when it fits',
  cls('a capacity greater than 151, 416 liters (40,000 gallons)').verdict, 'agree');
check('and the repair is named',
  cls('a capacity greater than 151, 416 liters (40,000 gallons)').reading, 'spaced-thousands');
check('a sentence comma before a number is NOT a thousands separator',
  cls('In Method 5, 120 \u00b0C (248 \u00b0F) is the reference temperature').verdict, 'agree');
check('and that one is read directly',
  cls('In Method 5, 120 \u00b0C (248 \u00b0F) is the reference temperature').reading, 'direct');

check('a tolerance base written with a bare degree sign is recovered',
  cls('a peak occurring at 490\u00b0 \u00b115 \u00b0C (914 \u00b0F)').verdict, 'agree');

check('a letter l standing in for the digit 1 is resolved, not reported',
  cls('a clearance of l ft. 6 in. (46 cm)').verdict, 'agree');
ok('and the typo is recorded', pairsOf('a clearance of l ft. 6 in. (46 cm)')[0].flags.includes('letter-one-for-digit-one'));

check('an ambiguous unit that fits under NEITHER reading is reported against the plausible one',
  cls('a radius of 6 nm (9.66 km) in every direction').aUnit, 'nmi');

// A sign written as a word, and the two remaining typographic defects.
check('"minus 20 degF" is negative twenty, and -28.88 is a truncation of -28.889 rather than an error',
  cls('a range from minus 20 \u00b0F (\u221228.88 \u00b0C) to plus 180 \u00b0F (82.2 \u00b0C)').verdict, 'rounded');
ok('and the value really is negative',
  cls('a range from minus 20 \u00b0F (\u221228.88 \u00b0C) to plus 180 \u00b0F (82.2 \u00b0C)').aValue.sign === -1);
check('a letter l inside the number is repaired only when it fits',
  cls('dry at l75 \u00b0C (350 \u00b0F) for 2 hours').reading, 'letter-l-for-digit-one');
check('a hyphen where a decimal point belongs, likewise',
  cls('a viscosity at 37-8 \u00b0C (100 \u00b0F) as determined by ASTM').reading, 'hyphen-for-decimal-point');
check('a temperature RISE is judged as an interval even when the rounding is not exact',
  cls('a temperature rise of 67 \u00b0F (37.3 \u00b0C)').reading, 'temperature-interval');
check('and it then reads as a rounding rather than an error',
  cls('a temperature rise of 67 \u00b0F (37.3 \u00b0C)').verdict, 'rounded');

check('"minus" after a comma is a subtraction, and its quantity is a difference',
  cls('the average of the three test runs, minus 14 \u00b0C (25 \u00b0F)').verdict, 'agree');
check('and it is read as an interval',
  cls('the average of the three test runs, minus 14 \u00b0C (25 \u00b0F)').reading, 'temperature-interval');
check('a header that lost its minus sign is NOT rescued as an interval',
  cls('T \u2265 55 \u00b0C (\u221267 \u00b0F)').reading, 'direct');

check('trailing zeros are ambiguous: 750 degC as "1400 degF" is two significant figures',
  cls('a furnace temperature of 750 \u00b0C (1400 \u00b0F)').verdict, 'agree');
check('but 110 degC as "220 degF" is not reachable at any precision',
  cls('heated to 110 \u00b0C (220 \u00b0F) throughout').verdict, 'discrepant');
check('and 100 yards as "30 meters" is not rescued by the generous reading',
  cls('within 100 yards (30 meters) of any dwelling').verdict, 'discrepant');
check('a difference cue after the parenthetical is seen',
  cls('shall be at least 20 \u00b0F (6.7 \u00b0C) warmer than the water').reading, 'temperature-interval');

// ---------------------------------------------------------------------------
const total = pass + failures.length;
if (failures.length) {
  console.error(`\n${failures.length} of ${total} assertions FAILED:\n`);
  for (const f of failures) console.error(`  ✗ ${f}`);
  process.exit(1);
}
console.log(`ok — ${pass} of ${total} assertions pass`);
