#!/usr/bin/env node
// verify-is-a-tomato-a-fruit-or-vegetable.mjs
//
// Offline gate for /strata/is-a-tomato-a-fruit-or-vegetable/. Recomputes EVERY
// verdict the page shows, from the same item table, and checks self-consistency.
// Where possible it verifies two independent ways. Exits 0 iff all checks pass.
//
//   Three rulers (each a pure function item -> 'F'ruit | 'V'egetable):
//     BOTANICAL : (ripened flower ovary AND contains seeds) ? F : V   [definition]
//     CULINARY  : sweet/dessert => F, else savory/side => V           [convention]
//     LEGAL     : = CULINARY, because Nix v. Hedden (1893) held the tariff word
//                 "vegetable" tracks common usage, not botany.
//
//   The 1893 holding is stored and reprinted verbatim with its cite and duty.
//   The ITEMS table below mirrors the inline <script> in index.html exactly.

// ── item table (single source of truth, mirrors the page) ────────────────
const ITEMS = [
  { name: 'Tomato',      ovary: true,  seeds: true,  culinary: 'V', subtype: 'true berry',              group: 'surprise' },
  { name: 'Cucumber',    ovary: true,  seeds: true,  culinary: 'V', subtype: 'pepo (berry)',            group: 'surprise' },
  { name: 'Bell pepper', ovary: true,  seeds: true,  culinary: 'V', subtype: 'berry',                   group: 'surprise' },
  { name: 'Avocado',     ovary: true,  seeds: true,  culinary: 'V', subtype: 'berry or drupe*',         group: 'surprise' },
  { name: 'Pumpkin',     ovary: true,  seeds: true,  culinary: 'V', subtype: 'pepo (berry)',            group: 'surprise' },
  { name: 'Green bean',  ovary: true,  seeds: true,  culinary: 'V', subtype: 'legume (pod)',            group: 'surprise' },
  { name: 'Eggplant',    ovary: true,  seeds: true,  culinary: 'V', subtype: 'berry',                   group: 'surprise' },
  { name: 'Olive',       ovary: true,  seeds: true,  culinary: 'V', subtype: 'drupe',                   group: 'surprise' },
  { name: 'Corn',        ovary: true,  seeds: true,  culinary: 'V', subtype: 'caryopsis (grain)',       group: 'surprise' },
  { name: 'Rhubarb',     ovary: false, seeds: false, culinary: 'F', subtype: 'leaf stalk (petiole)',    group: 'mirror'  },
  { name: 'Carrot',      ovary: false, seeds: false, culinary: 'V', subtype: 'taproot',                 group: 'control' },
  { name: 'Potato',      ovary: false, seeds: false, culinary: 'V', subtype: 'stem tuber',              group: 'control' },
  { name: 'Lettuce',     ovary: false, seeds: false, culinary: 'V', subtype: 'leaves',                  group: 'control' },
  { name: 'Apple',       ovary: true,  seeds: true,  culinary: 'F', subtype: 'pome (accessory)',        group: 'control' },
  { name: 'Strawberry',  ovary: true,  seeds: true,  culinary: 'F', subtype: 'accessory (not a berry)', group: 'control' }
];

// ── the three rulers ─────────────────────────────────────────────────────
const botanical = it => (it.ovary && it.seeds) ? 'F' : 'V';
const culinary  = it => it.culinary;
const legal     = it => culinary(it);            // Nix v. Hedden: tariff word tracks common usage
const byName    = n => ITEMS.find(it => it.name === n);
const word      = v => (v === 'F' ? 'Fruit' : 'Vegetable');
const flips     = it => !(botanical(it) === culinary(it) && culinary(it) === legal(it));

// ── the stored 1893 facts (verbatim holding + cite + duty) ───────────────
const NIX = {
  cite: '149 U.S. 304',
  parallel: '13 S.Ct. 881',
  decided: 'May 10, 1893',
  year: 1893,
  justice: 'Gray',
  act: 'Tariff Act of March 3, 1883',
  dutyPct: 10,                     // ad valorem, on "vegetables"; "fruits" were free
  holding:
    'Botanically speaking, tomatoes are the fruit of a vine, just as are cucumbers, squashes, ' +
    'beans, and peas. But in the common language of the people, whether sellers or consumers of ' +
    'provisions, all these are vegetables which are grown in kitchen gardens, and which, whether ' +
    'eaten cooked or raw, are, like potatoes, carrots, parsnips, turnips, beets, cauliflower, ' +
    'cabbage, celery, and lettuce, usually served at dinner in, with, or after the soup, fish, or ' +
    'meats which constitute the principal part of the repast, and not, like fruits generally, as ' +
    'dessert.'
};

// ── harness ──────────────────────────────────────────────────────────────
let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  const ok = !!cond;
  if (ok) pass++; else fail++;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? '  ::  ' + detail : ''}`);
}

console.log('=== is-a-tomato-a-fruit-or-vegetable :: offline verification ===\n');

// 1) botanical verdict is EXACTLY (ovary && seeds) for every item (two ways:
//    the ruler function vs. a fresh recomputation from the raw booleans).
{
  const ok = ITEMS.every(it => botanical(it) === ((it.ovary && it.seeds) ? 'F' : 'V'));
  check('botanical(x) == (ovary AND seeds) for all 15 items', ok);
}

// 2) legal column equals culinary column item-by-item (the Nix holding).
{
  const ok = ITEMS.every(it => legal(it) === culinary(it));
  check('legal(x) == culinary(x) for all items (Nix: tariff word = common usage)', ok);
}

// 3) the tomato flips Fruit -> Vegetable -> Vegetable across the three frames.
{
  const t = byName('Tomato');
  check('tomato flips Fruit -> Vegetable -> Vegetable',
    botanical(t) === 'F' && culinary(t) === 'V' && legal(t) === 'V',
    `${word(botanical(t))} -> ${word(culinary(t))} -> ${word(legal(t))}`);
}

// 4) rhubarb flips the OPPOSITE way: Vegetable -> Fruit -> Fruit (the mirror).
{
  const r = byName('Rhubarb');
  check('rhubarb flips Vegetable -> Fruit -> Fruit (the mirror of the tomato)',
    botanical(r) === 'V' && culinary(r) === 'F' && legal(r) === 'F',
    `${word(botanical(r))} -> ${word(culinary(r))} -> ${word(legal(r))}`);
}

// 5) all nine "surprise" items are botanical fruits but culinary vegetables,
//    and there are exactly nine of them.
{
  const nine = ITEMS.filter(it => it.group === 'surprise');
  const ok = nine.length === 9 && nine.every(it => botanical(it) === 'F' && culinary(it) === 'V');
  check('the 9 everyday "vegetables" are all botanical fruits + culinary vegetables', ok,
    nine.map(it => it.name).join(', '));
}

// 6) count of botanical fruits in the whole basket, cross-checked two ways.
{
  const a = ITEMS.filter(it => botanical(it) === 'F').length;
  const b = ITEMS.filter(it => it.ovary && it.seeds).length;   // independent recount
  // tomato,cucumber,pepper,avocado,pumpkin,bean,eggplant,olive,corn,apple,strawberry = 11
  check('botanical fruits in basket = 11 (two independent counts agree)', a === 11 && b === 11, `${a} == ${b}`);
}

// 7) berry sub-twist: the tomato is a TRUE berry; the strawberry is an accessory
//    fruit, NOT a berry (the folk "berries are the small ones" is backwards).
{
  const t = byName('Tomato'), s = byName('Strawberry');
  const ok = t.subtype === 'true berry' &&
             botanical(s) === 'F' && /accessory/.test(s.subtype) && !/^true berry$/.test(s.subtype);
  check('tomato is a true berry; strawberry is an accessory fruit (not a berry)', ok);
}

// 8) ten of fifteen flip; nine flip the tomato's way (Fruit->Vegetable), rhubarb
//    alone flips the opposite way (Vegetable->Fruit); the five controls never flip.
{
  const flippers = ITEMS.filter(flips);
  const dirs = {};
  for (const it of flippers) { const d = botanical(it) + '->' + culinary(it); dirs[d] = (dirs[d] || 0) + 1; }
  const r = byName('Rhubarb');
  const ok = flippers.length === 10 && dirs['F->V'] === 9 && dirs['V->F'] === 1 &&
             botanical(r) === 'V' && culinary(r) === 'F';
  check('10 flip: 9 go Fruit->Vegetable, rhubarb alone goes Vegetable->Fruit (the mirror)', ok,
    `flippers=${flippers.length}, F->V=${dirs['F->V'] || 0}, V->F=${dirs['V->F'] || 0}`);
}

// 9) controls never move: carrot/potato/lettuce all Vegetable in all frames;
//    apple/strawberry all Fruit in all frames.
{
  const veg = ['Carrot', 'Potato', 'Lettuce'].every(n => {
    const it = byName(n); return botanical(it) === 'V' && culinary(it) === 'V' && legal(it) === 'V';
  });
  const fru = ['Apple', 'Strawberry'].every(n => {
    const it = byName(n); return botanical(it) === 'F' && culinary(it) === 'F' && legal(it) === 'F';
  });
  check('unambiguous controls never flip (3 all-vegetable, 2 all-fruit)', veg && fru);
}

// 10) the 1893 legal facts are exactly as the page states.
{
  const ok = NIX.year === 1893 && NIX.cite === '149 U.S. 304' && NIX.dutyPct === 10 &&
             NIX.justice === 'Gray' && /March 3, 1883/.test(NIX.act) && /May 10, 1893/.test(NIX.decided);
  check('Nix v. Hedden facts: 149 U.S. 304, decided May 10 1893, Gray J., 1883 Act, 10% ad valorem', ok);
}

// 11) the holding text actually contains the "usually served at dinner ... not,
//     like fruits generally, as dessert" language, verbatim from the reporter.
{
  const ok = /usually served at dinner in, with, or after the soup, fish, or meats/.test(NIX.holding) &&
             /not, like fruits generally, as dessert\.$/.test(NIX.holding) &&
             /Botanically speaking, tomatoes are the fruit of a vine/.test(NIX.holding);
  check('Gray holding reprints the verbatim "served at dinner / not as dessert" passage', ok);
}

// 12) the tariff logic checks out: tomatoes were dutiable as VEGETABLES (10%),
//     so calling them fruit would have made them free. legal(tomato) must be 'V'.
{
  const t = byName('Tomato');
  const dutyPaid = legal(t) === 'V' ? NIX.dutyPct : 0;
  check('under the 1883 Act the tomato pays the 10% vegetable duty (fruit would be free)',
    legal(t) === 'V' && dutyPaid === 10, `duty = ${dutyPaid}%`);
}

// ── reprint the holding + the 3-frame table for the record ───────────────
console.log('\n--- Nix v. Hedden, ' + NIX.cite + ' (' + NIX.parallel + '), decided ' + NIX.decided +
  ', ' + NIX.justice + ', J. ---');
console.log('Under the ' + NIX.act + ', imported tomatoes are dutiable as "vegetables" at ' +
  NIX.dutyPct + '% ad valorem (not free as "fruits").');
console.log('Holding (verbatim): "' + NIX.holding + '"');

console.log('\n--- classification table (item | structure | botanical | culinary | legal) ---');
for (const it of ITEMS) {
  const mark = flips(it) ? '  <== flips' : '';
  console.log(
    it.name.padEnd(12) + ' | ' + it.subtype.padEnd(22) + ' | ' +
    word(botanical(it)).padEnd(9) + ' | ' + word(culinary(it)).padEnd(9) + ' | ' +
    word(legal(it)).padEnd(9) + mark
  );
}

console.log(`\n=== ${pass} passed, ${fail} failed ===`);
process.exit(fail === 0 ? 0 : 1);
