// verify.mjs — the geometry behind the stratum
// "The Give Was Never in the Yarn" (/strata/why-knitting-stretches/).
//
// The claim the page makes: a knitted fabric stretches tens of percent and a woven
// fabric on the grain barely does — from the SAME yarn — because the give is
// GEOMETRIC (loops rearranging, a grid shearing) while the yarn's own length is
// conserved. The stretch is not in the thread.
//
// Primary sources for the load-bearing physics:
//   [1] Poincloux, Adda-Bedia & Lechenault, "Geometry and elasticity of a knitted
//       fabric," Phys. Rev. X 8, 021075 (2018)  (arXiv:1801.08355). Knit response
//       from (i) yarn BENDING energy, (ii) conservation of total yarn length,
//       (iii) stitch topology — "loose yet extremely stretchable fabrics with
//       almost vanishing rigidity, exhibited by hardly any bulk material."
//   [2] Faulconnier, Michel, Adda-Bedia, Crassous & Steinberger, "Laddering of a
//       knitted fabric: a topology-induced failure," arXiv:2604.20580 (2026). A
//       force threshold set by the stitch's natural curvature controls BOTH onset
//       and arrest of a run; laddering speed ~ linear in fabric tension, of the
//       order of the bending-wave speed.
//   [3] Munden, "The geometry and dimensional properties of plain-knit fabrics,"
//       J. Text. Inst. 50, T448 (1959). Dry-relaxed constants Kc≈5.0, Kw≈3.8,
//       Ks≈19, with the identity Ks = Kc·Kw.
//   [4] ScienceDirect "Knitted Fabric" overview + textile refs: plain jersey
//       ~30–50% widthwise / ~10–20% lengthwise, 1x1 rib ~100–120% along the course,
//       knits ~2.5x wovens; woven on-grain a few % (crimp interchange, then jam).
//
// Two jobs, no dependencies (node: builtins only):
//   (A) recompute EVERY number the page shows, against exact geometry and the
//       sourced bands, PASS/FAIL, non-zero exit on any failure;
//   (B) READ the shipped public/strata/why-knitting-stretches/index.html and assert
//       it literally contains the same key figures and formulas, so the drawing and
//       the numbers cannot silently disagree.
//
//   run:  node research/why-knitting-stretches/verify.mjs

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── shared geometry (identical to the page's inline script) ──────────────────
const D2R = Math.PI / 180;
const eBias = (phiDeg) => Math.SQRT2 * Math.cos((phiDeg * D2R) / 2) - 1; // trellis extension
const phiJam = (dOverP) => Math.asin(dOverP) / D2R;                       // jam angle (deg)
function ellipsePerim(a, c, N = 4000) {
  let L = 0, px = a, py = 0;
  for (let i = 1; i <= N; i++) {
    const t = (2 * Math.PI * i) / N, x = a * Math.cos(t), y = c * Math.sin(t);
    L += Math.hypot(x - px, y - py); px = x; py = y;
  }
  return L;
}
function solveC(a, target, cHi = 6.0) {
  let lo = 1e-6, hi = cHi;
  for (let i = 0; i < 90; i++) { const m = (lo + hi) / 2; if (ellipsePerim(a, m) < target) lo = m; else hi = m; }
  return (lo + hi) / 2;
}

// ── 1. Woven bias is exact pin-jointed-net (trellis) geometry ────────────────
console.log('\n— woven: on-grain jams, the bias shears open (ε = √2·cos(φ/2) − 1) —');
ok('relaxed grid (φ=90°) has zero bias extension', approx(eBias(90), 0, 1e-9), `ε=${eBias(90).toFixed(6)}`);
ok('bias extension is monotone as the grid shears (φ: 90°→30°)',
   eBias(80) > 0 && eBias(60) > eBias(80) && eBias(30) > eBias(60));
const jam05 = phiJam(0.5);
ok('cover d/p=0.5 jams at φ = arcsin(0.5) = 30°', approx(jam05, 30, 1e-6), `φ_jam=${jam05.toFixed(3)}°`);
ok('bias max at d/p=0.5 ≈ +36.6%', approx(eBias(jam05), 0.3660, 5e-4), `${(eBias(jam05) * 100).toFixed(2)}%`);
ok('bias max at d/p=0.3 ≈ +39.8% (looser weave jams later → more give)',
   approx(eBias(phiJam(0.3)), 0.3978, 5e-4), `${(eBias(phiJam(0.3)) * 100).toFixed(2)}%`);
ok('bias max at d/p=0.7 ≈ +30.9% (tighter weave jams sooner → less give)',
   approx(eBias(phiJam(0.7)), 0.3093, 5e-4), `${(eBias(phiJam(0.7)) * 100).toFixed(2)}%`);
// transverse contraction at the jam (the bias-cut "narrowing" everyone sees)
const contr = Math.SQRT2 * Math.sin((jam05 * D2R) / 2) - 1;
ok('bias pull narrows the cloth strongly (transverse ≈ −63.4%)', approx(contr, -0.634, 2e-3), `${(contr * 100).toFixed(1)}%`);

// ── 2. Munden's relaxed constants carry an internal identity ─────────────────
console.log('\n— Munden dry-relaxed constants and the identity Ks = Kc·Kw —');
const Kc = 5.0, Kw = 3.8, Ks = Kc * Kw;
ok('Ks = Kc·Kw = 5.0·3.8 = 19.0', approx(Ks, 19.0, 1e-9), `Ks=${Ks.toFixed(3)}`);
ok('relaxed loop aspect Kc/Kw ≈ 1.316 (wider than tall)', approx(Kc / Kw, 1.3158, 1e-3), `${(Kc / Kw).toFixed(4)}`);

// ── 3. Knit stretch conserves yarn length: fabric strain ≫ yarn strain (=0) ──
console.log('\n— knit loop (idealised closed curve, fixed yarn length) —');
const A0 = 5.0, C0 = 3.8;                 // semi-axes (mm), ratio A0/C0 = Kc/Kw
const L0 = ellipsePerim(A0, C0);
ok('idealised yarn length per loop ℓ ≈ 27.78 mm', approx(L0, 27.775, 0.02), `ℓ=${L0.toFixed(3)} mm`);
// widen the loop; solve height to hold yarn length; yarn strain must stay ~0
let maxYarnStrain = 0;
for (const fab of [0.10, 0.20, 0.30, 0.389]) {
  const a = A0 * (1 + fab), c = solveC(a, L0, C0), Lnow = ellipsePerim(a, c);
  const yarnStrain = Math.abs((Lnow - L0) / L0);
  maxYarnStrain = Math.max(maxYarnStrain, yarnStrain);
  ok(`fabric width +${(fab * 100).toFixed(1)}% → yarn strain ${(yarnStrain * 100).toFixed(3)}% (≈0)`,
     yarnStrain < 5e-3, `ℓ=${Lnow.toFixed(3)} mm, c=${c.toFixed(3)} mm`);
}
ok('yarn strain stays essentially zero across the whole pull', maxYarnStrain < 5e-3,
   `max=${(maxYarnStrain * 100).toFixed(3)}%`);
// idealised kinematic maximum: c→0 ⇒ ℓ = 4a ⇒ width strain
const A_MAX = L0 / 4, S_MAX = (2 * A_MAX) / (2 * A0) - 1;
ok('idealised max width ≈ +38.9% (reached at ZERO yarn strain)', approx(S_MAX, 0.3887, 2e-3), `${(S_MAX * 100).toFixed(2)}%`);
ok('…and it lands inside the measured plain-jersey band 30–50%', S_MAX > 0.30 && S_MAX < 0.50);

// ── 4. The three regimes rank the way the page claims ────────────────────────
console.log('\n— the ordering the page rests on —');
const GRAIN_MAX = 0.04;                    // representative on-grain crimp give
ok('knit widthwise (~39%) and woven-bias (~37%) are the same league — both geometric',
   Math.abs(S_MAX - eBias(jam05)) < 0.05, `Δ=${((S_MAX - eBias(jam05)) * 100).toFixed(1)} pts`);
ok('woven on-grain (~4%) is the outlier — an order below the geometric givers',
   GRAIN_MAX * 8 < S_MAX && GRAIN_MAX * 8 < eBias(jam05), `on-grain=${(GRAIN_MAX * 100).toFixed(0)}%`);

// ── 5. Representative extensibility bands (sourced) are internally consistent ─
console.log('\n— sourced extensibility bands (scoped to a named structure) —');
const jerseyWidth = [30, 50], jerseyLength = [10, 20], rib = [100, 120], knitVsWoven = 2.5;
ok('plain jersey stretches more along the course (width) than the wale (length)',
   jerseyWidth[0] > jerseyLength[1]);
ok('1×1 rib along the course far exceeds plain jersey (≈100–120%)', rib[0] >= 2 * jerseyWidth[0]);
ok('knits ≈ 2.5× wovens is consistent with jersey-width / woven-on-grain order',
   knitVsWoven > 1.5 && (jerseyWidth[0] / (GRAIN_MAX * 100)) > knitVsWoven);

// ── 6. Laddering: the paper's qualitative laws (illustrative model) ──────────
console.log('\n— laddering: threshold controls onset AND arrest; speed ∝ tension —');
const F_STAR = 0.35, k = 3.2;
const ladderSpeed = (T, relaxed = 0, warp = false) => {
  if (warp) return 0;                      // warp knit resists running (no single thread to unzip)
  const eff = T - relaxed;
  return eff > F_STAR ? (eff - F_STAR) * k : 0;
};
ok('below the curvature threshold a weft-knit run arrests (v=0)', ladderSpeed(0.30) === 0);
ok('at the threshold v=0 (onset = arrest, one number)', approx(ladderSpeed(F_STAR), 0, 1e-9));
ok('above threshold the run propagates (v>0)', ladderSpeed(0.6) > 0);
// linear scaling with tension above threshold (v = k·(T−F*))
const v1 = ladderSpeed(0.5), v2 = ladderSpeed(0.7), v3 = ladderSpeed(0.9);
ok('laddering speed scales LINEARLY with tension above threshold',
   approx(v2 - v1, v3 - v2, 1e-9) && approx((v2 - v1), k * 0.2, 1e-9), `slope=${((v2 - v1) / 0.2).toFixed(2)}`);
ok('self-arrest: freed length relaxes tension back below threshold, stopping the run',
   ladderSpeed(0.6, 0.30) === 0, `same F*=${F_STAR} halts it`);
ok('a warp knit does not run (topology-induced resistance)', ladderSpeed(0.9, 0, true) === 0);

// ── (B) Read the shipped page and assert it prints the same figures ──────────
console.log('\n— the shipped page contains the same figures & formulas —');
const here = dirname(fileURLToPath(import.meta.url));
const htmlPath = join(here, '..', '..', 'public', 'strata', 'why-knitting-stretches', 'index.html');
const html = readFileSync(htmlPath, 'utf8');
const has = (s) => html.includes(s);
const need = [
  // the load-bearing formulas, present verbatim in the page
  ['bias formula ε = √2·cos(φ/2) − 1', 'ε_bias = √2·cos(φ/2) − 1'],
  ['jamming rule φ = arcsin(d/p)', 'φ = arcsin(d/p)'],
  ['idealised yarn length 27.78 mm', '27.78 mm'],
  ['knit ~39% figure', '~39%'],
  ['woven-bias ~37% figure', '~37%'],
  ['woven on-grain ~4% figure', '~4%'],
  ['Munden identity Ks = Kc·Kw', 'Ks = Kc·Kw'],
  ['Munden proportions 5.0:3.8', '5.0:3.8'],
  ['plain jersey 30–50%', '30–50%'],
  ['plain jersey 10–20%', '10–20%'],
  ['rib 100–120%', '100–120%'],
  ['knits ≈ 2.5×', '2.5×'],
  ['yarn strain 0.0%', '0.0%'],
  // the shipped inline computation uses the SAME geometry the verifier checks
  ['inline eBias uses √2·cos', 'Math.SQRT2 * Math.cos'],
  ['inline jam uses arcsin', 'Math.asin(dOverP)'],
  ['inline ellipsePerim present', 'function ellipsePerim'],
  // provenance
  ['Poincloux primary cited', 'Poincloux'],
  ['Faulconnier primary cited', 'Faulconnier'],
  ['arXiv 1801.08355 linked', 'arxiv.org/abs/1801.08355'],
  ['arXiv 2604.20580 linked', 'arxiv.org/abs/2604.20580'],
  ['canonical URL', 'https://artwaste.land/strata/why-knitting-stretches/'],
  ['landing date 2026-07-09', '2026-07-09'],
  ['no-elastane caveat stated', 'no elastane'],
  ['bias trap corrected (on the grain)', 'on the grain'],
];
for (const [name, s] of need) ok(name, has(s), `"${s.length > 26 ? s.slice(0, 26) + '…' : s}"`);

// ── tally ────────────────────────────────────────────────────────────────────
const total = 33; // informational; the real gate is fails === 0
console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}  (${'geometry recomputed + page parity'})\n`);
process.exit(fails === 0 ? 0 : 1);
