// return-rate.mjs: EXPLORATORY, not pre-registered (2026-09-27, written while making the film).
//
// The layer's open edge (1): the horizon falls with the nudge about a quarter faster per bit
// than the forward growth rate predicts (refit ratios 0.63 to 0.85). One guess was that the
// separation grows faster on the RETURN leg than on the forward one. This measures it the same
// way measure.mjs measures the forward rate (nudge disk 0 by one grid step, fit log2 of the
// largest separation in grid steps against steps over 8..24 bits), but on the return leg:
// run T steps out, copy, nudge one copy, reverse both, and watch them part on the way back.
//
//   node return-rate.mjs   -> return-rate.json
import { initial, IntGas, maxSeparation, L } from './engine.mjs';
import { readFileSync, writeFileSync } from 'node:fs';

const res = JSON.parse(readFileSync(new URL('./results.json', import.meta.url), 'utf8'));
function slope(xs, ys) { const n = xs.length, mx = xs.reduce((a, b) => a + b) / n, my = ys.reduce((a, b) => a + b) / n; let a = 0, b = 0; for (let i = 0; i < n; i++) { a += (xs[i] - mx) * (ys[i] - my); b += (xs[i] - mx) ** 2; } return a / b; }
const rows = [];
for (const seed of [1, 2, 3, 4, 5]) {
  const row = { seed, forward: res.rows.find((r) => r.seed === seed).rateBitsPerStep, back: {} };
  for (const T of [2500, 5000]) {
    const g = new IntGas(initial({ seed })); g.step(T);
    const a = g.clone(), b = g.clone(); b.nudge(0, 1); a.reverse(); b.reverse();
    const ts = [], bs = [];
    for (let s = 25; s < T; s += 25) {
      a.step(25); b.step(25);
      const sep = maxSeparation(a.xs(), a.ys(), b.xs(), b.ys()) * L, bits = sep > 0 ? Math.log2(sep) : -Infinity;
      if (bits >= 8 && bits <= 24) { ts.push(s); bs.push(bits); }
    }
    row.back[T] = ts.length >= 3 ? slope(ts, bs) : null;
  }
  rows.push(row);
  console.log(seed, row.forward.toFixed(4), JSON.stringify(Object.fromEntries(Object.entries(row.back).map(([k, v]) => [k, v && +v.toFixed(4)]))));
}
writeFileSync(new URL('./return-rate.json', import.meta.url), JSON.stringify({ exploratory: true, rows }, null, 1) + '\n');
