// verify.mjs — reproduce, from real coastline data, Mandelbrot 1967's claim
// that geographic curves obey Richardson's empirical law
//
//      L(G) = M · G^(1 - D),
//
// and recover the canonical D values from his Table.
//
//   node research/coastline-paradox/verify.mjs
//
// Data: Natural Earth ne_10m_coastline (public domain). The exact lon/lat
// polylines used here are committed in `coasts.json` and generated by `extract.mjs`.
//
// Two independent estimators of D are run and shown to agree:
//
//   (A) DIVIDER METHOD (Richardson 1961). For each step length G (km), walk
//       a pair of straight dividers along the polyline using great-circle
//       chord distance; L(G) = N(G) · G. A least-squares fit of log L vs
//       log G over the inertial range gives slope = 1 - D, so D = 1 - slope.
//
//   (B) BOX-COUNTING DIMENSION. Project the polyline to a local equirectangular
//       grid in km. Overlay grids of cell size G; count occupied cells N(G).
//       The slope of log N vs log G is -D.
//
// The published values we're reproducing (Mandelbrot 1967, p. 636, quoting
// Richardson 1961 Fig. 17):
//
//     west coast of Great Britain                       D = 1.25
//     land frontier of Germany c. 1899                  D = 1.15
//     land frontier between Spain and Portugal          D = 1.14
//     Australian coast                                  D = 1.13
//     South African coast                               D = 1.02
//     (a straight, "rectifiable" frontier)              D = 1.00
//
// We do not have Richardson's exact polyline. We use modern Natural Earth at
// 1:10,000,000 — a different sampling than the 1950s atlas Richardson worked
// from. So our recovered D values should be close to but not identical to his.

import { readFileSync } from 'fs';

const data = JSON.parse(
  readFileSync(new URL('./coasts.json', import.meta.url), 'utf8'));

let fails = 0;
const ok  = (n, c, e='') => { console.log((c?'  ok   ':'  FAIL ')+n+(e?'  '+e:'')); if(!c)fails++; };
const sec = (s) => console.log('\n=== '+s+' ===');

/* ──────────────────────────── geometry ─────────────────────────────────── */
const R_KM = 6371.0088;                                    // mean Earth radius

// Great-circle chord distance — Haversine.
function haversineKm(a, b) {
  const φ1 = a[1]*Math.PI/180, φ2 = b[1]*Math.PI/180;
  const dφ = (b[1]-a[1])*Math.PI/180;
  const dλ = (b[0]-a[0])*Math.PI/180;
  const s = Math.sin(dφ/2)**2 + Math.cos(φ1)*Math.cos(φ2)*Math.sin(dλ/2)**2;
  return 2*R_KM*Math.asin(Math.sqrt(Math.max(0, Math.min(1, s))));
}

// Total polyline length (sum of chords), in km.
function polylineLengthKm(poly) {
  let L = 0;
  for (let i = 1; i < poly.length; i++) L += haversineKm(poly[i-1], poly[i]);
  return L;
}

// Linear interpolation along a great-circle segment by fraction t ∈ [0,1].
// For short segments at ne_10m scale (a few km), simple lon/lat interpolation
// is accurate to far better than 1 part in 10^3, which is plenty here.
function interp(a, b, t) {
  return [a[0] + t*(b[0]-a[0]), a[1] + t*(b[1]-a[1])];
}

/* ──────────────────────────── divider method ───────────────────────────── */
// Walk a divider of step length G along the polyline. Each "step" is a chord
// of length exactly G from the current divider tip to a point on the polyline
// further along. Returns count N and length N·G.
function divider(poly, G) {
  let tip = poly[0];
  let i = 0;                            // we are on segment poly[i] — poly[i+1]
  let segStart = poly[0];               // the start of the current segment for the tip
  let N = 0;
  while (true) {
    // Find the first vertex coast[j] (j > i) such that haversine(tip, coast[j]) ≥ G.
    // Then the new divider tip lies on segment (coast[j-1], coast[j]).
    let placed = false;
    for (let j = i + 1; j < poly.length; j++) {
      const d = haversineKm(tip, poly[j]);
      if (d >= G) {
        // The tip lies between poly[j-1] and poly[j]. Solve the chord-length
        // equation along that segment in lon/lat space (small-segment approx).
        // We're looking for fraction t ∈ [0,1] along (poly[j-1], poly[j]) such
        // that haversine(tip, interp(poly[j-1], poly[j], t)) = G.
        let lo = 0, hi = 1;
        for (let k = 0; k < 36; k++) {                  // ~1 part in 7×10^10
          const m = 0.5*(lo+hi);
          const p = interp(poly[j-1], poly[j], m);
          if (haversineKm(tip, p) < G) lo = m; else hi = m;
        }
        tip = interp(poly[j-1], poly[j], 0.5*(lo+hi));
        i = j - 1;                                       // remain on this segment
        // BUT the tip is now mid-segment, so advance the "segment start" pointer:
        // next divider step must continue from THIS tip down the polyline. The
        // outer loop accomplishes that by scanning j > i, but the FIRST trial
        // uses poly[i+1] = poly[j], which is fine because the tip itself moves.
        N++;
        placed = true;
        break;
      }
    }
    if (!placed) break;                                  // ran off the polyline
  }
  return { N, length_km: N * G };
}

/* ─────────────────────── box counting (planar) ─────────────────────────── */
// Project (lon, lat) → (x, y) in km on an equirectangular grid local to the
// coast's mean latitude. Lay grids of cell size G km and count occupied cells.
// For each polyline edge, mark every cell the edge crosses (Bresenham-like
// supercover so that "occupied" counts every cell the curve actually visits).
function boxCount(poly, G) {
  const meanLat = poly.reduce((s,[,y]) => s+y, 0) / poly.length;
  const cosLat = Math.cos(meanLat*Math.PI/180);
  const KM_PER_DEG = 111.32;
  const project = ([lon, lat]) => [lon*KM_PER_DEG*cosLat, lat*KM_PER_DEG];

  const occupied = new Set();
  const cellOf = (x, y) => Math.floor(x/G) + ',' + Math.floor(y/G);

  let prev = project(poly[0]);
  occupied.add(cellOf(prev[0], prev[1]));
  for (let i = 1; i < poly.length; i++) {
    const cur = project(poly[i]);
    // walk along the segment with sub-cell steps so every crossed cell is hit
    const dx = cur[0] - prev[0], dy = cur[1] - prev[1];
    const seglen = Math.hypot(dx, dy);
    const nsub = Math.max(2, Math.ceil(seglen / (G * 0.3)));
    for (let k = 1; k <= nsub; k++) {
      const t = k/nsub;
      occupied.add(cellOf(prev[0] + t*dx, prev[1] + t*dy));
    }
    prev = cur;
  }
  return occupied.size;
}

/* ──────────────────────── log-log least-squares ────────────────────────── */
function fitSlope(xs, ys) {
  const n = xs.length;
  const mx = xs.reduce((s,v)=>s+v,0)/n;
  const my = ys.reduce((s,v)=>s+v,0)/n;
  let num=0, den=0;
  for (let i=0;i<n;i++) { num += (xs[i]-mx)*(ys[i]-my); den += (xs[i]-mx)**2; }
  const m = num/den;
  const b = my - m*mx;
  // residual / s.e. on slope (for honesty)
  let ss=0;
  for (let i=0;i<n;i++) ss += (ys[i] - (m*xs[i]+b))**2;
  const sigma = Math.sqrt(ss/(n-2));
  const se = sigma/Math.sqrt(den);
  return { slope: m, intercept: b, sigma, se };
}

/* ──────────────────────── compute D for one coast ──────────────────────── */
function dimensionOf(name, poly, opts={}) {
  const total = polylineLengthKm(poly);
  const spacing = total / poly.length;
  // The honest "inertial range" for a finite, sampled polyline:
  //
  //   floor:   G must be many times the vertex spacing — otherwise the divider
  //            is just walking the polygon's straight chords and the result
  //            reflects sampling, not the coast's roughness.
  //   ceiling: G must be many times smaller than the curve's overall length
  //            — otherwise we're measuring the bounding box, not the curve.
  //
  // Default range: spacing×10  →  total/25. Spans ~1 log decade for the
  // shortest coast here (South Africa) and ~2 for Australia. Avoiding both
  // ends matters: below ~10× spacing the divider is just walking the polyline's
  // sampling-vertex chords, and above ~total/15 the divider is measuring the
  // bounding box rather than the curve (it ran out of polyline to bite into).
  const gMin = opts.gMin ?? Math.max(10, 10*spacing);
  const gMax = opts.gMax ?? total/25;
  const nG = opts.nG ?? 9;
  const Gs = Array.from({length:nG},
    (_,k)=>gMin*Math.pow(gMax/gMin, k/(nG-1)));

  const div = Gs.map(G => {
    const { N, length_km } = divider(poly, G);
    return { G, N, L: length_km };
  });
  const box = Gs.map(G => ({ G, count: boxCount(poly, G) }));

  // Divider fit: log L vs log G, slope = 1 − D. Drop trials where N = 0 (the
  // divider could not even take one full step — happens at the very upper end
  // for short coasts) since log 0 is undefined and would corrupt the fit.
  const usableDiv = div.filter(d => d.N >= 3);
  const xD = usableDiv.map(d => Math.log(d.G));
  const yD = usableDiv.map(d => Math.log(d.L));
  const fitD = fitSlope(xD, yD);
  const Ddiv = 1 - fitD.slope;

  // Box fit: log N vs log G, slope = −D
  const xB = box.map(d => Math.log(d.G));
  const yB = box.map(d => Math.log(d.count));
  const fitB = fitSlope(xB, yB);
  const Dbox = -fitB.slope;

  return {
    name,
    total_km: total,
    spacing_km: spacing,
    Gs, div, box,
    nUsableDiv: usableDiv.length,
    D_divider: Ddiv, se_divider: fitD.se,
    D_box: Dbox,     se_box: fitB.se,
    intercept_divider: fitD.intercept,
  };
}

/* ────────────────────────────── runs ───────────────────────────────────── */
sec('coastline data summary');
const polys = data.coasts;
for (const [k, v] of Object.entries(polys)) {
  const L = polylineLengthKm(v.pts);
  console.log(`  ${k.padEnd(22)}  ${String(v.pts.length).padStart(5)} pts  raw length ≈ ${L.toFixed(0)} km  closed=${v.closed}`);
}

sec('(A) divider method + (B) box counting per coast');
const results = {};
const named = {
  great_britain:      { D_published: null,  label: 'Great Britain (whole)' },
  great_britain_west: { D_published: 1.25,  label: 'Great Britain — west coast (Mandelbrot 1967)' },
  south_africa:       { D_published: 1.02,  label: 'South African coast (Richardson 1961)' },
  australia:          { D_published: 1.13,  label: 'Australia (Richardson 1961)' },
  norway:             { D_published: null,  label: 'Norway fjord coast (popular extreme)' },
  circle_500km:       { D_published: 1.00,  label: 'Circle, R=500 km (control)' },
};

for (const key of Object.keys(named)) {
  const r = dimensionOf(key, polys[key].pts);
  results[key] = r;
  const { label, D_published } = named[key];
  console.log(`\n  ${label}`);
  console.log(`    total polyline ≈ ${r.total_km.toFixed(0)} km, vertex spacing ≈ ${r.spacing_km.toFixed(2)} km`);
  console.log(`    G (km)   N(G)   L(G) km    boxes(G)`);
  for (let i = 0; i < r.Gs.length; i++) {
    const G  = r.Gs[i].toFixed(2);
    const N  = String(r.div[i].N).padStart(6);
    const Lk = r.div[i].L.toFixed(0).padStart(8);
    const B  = String(r.box[i].count).padStart(7);
    console.log(`    ${G.padStart(7)}  ${N}  ${Lk}    ${B}`);
  }
  console.log(`    D_divider = ${r.D_divider.toFixed(3)}  (s.e. ${r.se_divider.toFixed(3)})`);
  console.log(`    D_box     = ${r.D_box.toFixed(3)}  (s.e. ${r.se_box.toFixed(3)})`);
  if (D_published !== null)
    console.log(`    D published (Richardson/Mandelbrot) = ${D_published.toFixed(3)}`);
}

/* ─────────────────────── canonical-value checks ───────────────────────── */
sec('checks: do the recovered D values match the canon?');

// The published values come from Richardson's 1950s atlas tracings. We are
// running on Natural Earth 10m, a different (modern, finer) base. So we
// should NOT expect agreement to two decimals; we expect the right *ordering*
// and the right ballpark. Tolerance set to ±0.15 — wide enough to honestly
// allow base-map differences, tight enough that getting the right number is
// not luck.
const RECOVERY_TOL = 0.15;

ok('control: a circle is rectifiable (D close to 1.00)',
   Math.abs(results.circle_500km.D_divider - 1.0) < 0.05,
   `D_divider = ${results.circle_500km.D_divider.toFixed(3)}, D_box = ${results.circle_500km.D_box.toFixed(3)}`);

ok('South Africa: D close to 1.02 (the smoothest in M67)',
   Math.abs(results.south_africa.D_divider - 1.02) < RECOVERY_TOL,
   `D_divider = ${results.south_africa.D_divider.toFixed(3)} (published 1.02)`);

ok('Australia: D close to 1.13 (Richardson)',
   Math.abs(results.australia.D_divider - 1.13) < RECOVERY_TOL,
   `D_divider = ${results.australia.D_divider.toFixed(3)} (published 1.13)`);

ok('Great Britain west coast: D close to 1.25 (Mandelbrot)',
   Math.abs(results.great_britain_west.D_divider - 1.25) < RECOVERY_TOL,
   `D_divider = ${results.great_britain_west.D_divider.toFixed(3)} (published 1.25)`);

ok('Norway is rougher than the South African coast',
   results.norway.D_divider > results.south_africa.D_divider + 0.05,
   `D(Norway) = ${results.norway.D_divider.toFixed(3)} vs D(SA) = ${results.south_africa.D_divider.toFixed(3)}`);

ok('Britain west coast is rougher than the South African coast',
   results.great_britain_west.D_divider > results.south_africa.D_divider + 0.05,
   `D(GB-W) = ${results.great_britain_west.D_divider.toFixed(3)} vs D(SA) = ${results.south_africa.D_divider.toFixed(3)}`);

// Box counting is noisier than the divider method on these short, finite,
// open coasts: the cell counts are integers, the projection introduces a small
// bias, and where the divider walks step-by-step along the curve, box counting
// records every cell the projection touches (some by chance corner-clipping).
// We require agreement to within 0.25 — looser than the headline tolerance,
// but tight enough that the two independent estimators are clearly seeing the
// same thing. The divider method is what Richardson and Mandelbrot used and
// the headline numbers above are the divider values.
ok('divider and box-counting agree to within 0.25 on every coast',
   Object.values(results).every(r => Math.abs(r.D_divider - r.D_box) < 0.25),
   Object.entries(results).map(([k,r]) =>
     `${k}: div=${r.D_divider.toFixed(2)}, box=${r.D_box.toFixed(2)}`).join('; '));
// Ordering: by divider, the coasts should rank smoothest → roughest as
//   circle < South Africa < Australia < Britain (whole) ≈ Britain (west) < Norway
// (with the two "Britain" entries close, since the west arc dominates the whole
// island's roughness anyway).
{
  const ranks = ['circle_500km','south_africa','australia','great_britain','great_britain_west','norway'];
  const Ds = ranks.map(k => results[k].D_divider);
  let monotonic = true;
  for (let i = 1; i < Ds.length; i++) if (Ds[i] < Ds[i-1] - 0.01) monotonic = false;
  ok('divider D ranks the coasts smooth → rough as expected',
     monotonic,
     ranks.map((k,i)=>`${k}=${Ds[i].toFixed(2)}`).join(' < '));
}

/* ─────────────────── richardson's empirical law itself ────────────────── */
sec('Richardson\'s empirical law (does L grow as a power of G?)');

// And for the circle, L should be nearly constant (no power-law growth)
{
  const r = results.circle_500km;
  const Ls = r.div.filter(d=>d.N>=3).map(d=>d.L);
  const Lmax = Math.max(...Ls), Lmin = Math.min(...Ls);
  ok('circle: L(G) is nearly constant (D ≈ 1) over the inertial range',
     Lmax / Lmin < 1.05,
     `Lmax/Lmin = ${(Lmax/Lmin).toFixed(3)} over G = ${r.Gs[0].toFixed(0)}–${r.Gs.at(-1).toFixed(0)} km`);
}

// And for Britain west, L(small G) > L(large G) — the famous divergence.
{
  const r = results.great_britain_west;
  const Lsmall = r.div[0].L, Llarge = r.div.at(-1).L;
  ok('Britain west: shorter ruler → more length (the famous divergence)',
     Lsmall > Llarge * 1.3,
     `L(G=${r.div[0].G.toFixed(0)} km) = ${Lsmall.toFixed(0)} km · L(G=${r.div.at(-1).G.toFixed(0)} km) = ${Llarge.toFixed(0)} km`);
}

/* ─────────────────────────── final tally ──────────────────────────────── */
sec('summary');
console.log(`\n  ${fails === 0 ? 'ALL CHECKS PASS' : `${fails} CHECK(S) FAILED`}\n`);
process.exit(fails === 0 ? 0 : 1);
