// engine.mjs: a gas of soft disks that can be run backwards, two ways.
//
// Shared, byte for byte, by the page (public/strata/arrow-of-time/engine.mjs is a copy that the
// verifier compares) and by the verifier. Everything here uses only + - * / and Math.round on
// IEEE doubles, which JavaScript requires to be correctly rounded and forbids fusing, so every
// browser and every Node computes the same bits. (No Math.exp, Math.log, Math.sin, Math.cbrt in
// the dynamics: those are not required to be correctly rounded, and would let two machines differ.)
//
// THE INTEGER GAS (after Levesque & Verlet, J. Stat. Phys. 72, 519, 1993). Positions are integers
// on a grid of 2^32 steps per box side. The update is the position Verlet rule
//     X[n+1] = X[n] + D,   D = X[n] - X[n-1] + round(a(X[n]) * dt^2 * 2^32)
// in which the force is computed in floating point and then ROUNDED TO AN INTEGER before it touches
// the state. The rounding is part of the law of motion, the same law in both directions, so the map
// is exactly invertible: given (X[n+1], D) you recover (X[n], D - A). Reverse every velocity and it
// retraces its path to the bit. That is the object Loschmidt imagined in 1876 and could not build.
//
// THE FLOATING GAS. The same disks, the same force, the same time step, integrated the way molecular
// dynamics normally is (velocity Verlet in doubles). Reversible on paper; not in the machine,
// because every x + v*dt is rounded and the rounding does not know which way time runs.

export const L = 4294967296;          // 2^32 grid steps per box side (exact in a double)
export const H = 1 / L;               // one grid step in box units (a power of two: exact)
const HALF = L / 2;

// 2^(1/3) as a literal, so no machine's cube root is consulted.
const CBRT2 = 1.2599210498948732;

export const DEFAULTS = Object.freeze({ N: 128, sigma: 0.05, dt: 2.5e-4, seed: 1, speed: 1.0 });

// mulberry32: a 32-bit PRNG built from integer ops only.
export function rng(seed) {
  let a = seed >>> 0;
  return function () {
    a = (a + 0x6D2B79F5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

// Approximately normal deviate from 12 uniforms (Irwin-Hall): additions only, so deterministic.
function gauss(r) { let s = 0; for (let k = 0; k < 12; k++) s += r(); return s - 6; }

function wrapInt(x) { x %= L; return x < 0 ? x + L : x; }
function minImgInt(d) { if (d >= HALF) return d - L; if (d < -HALF) return d + L; return d; }
function wrapF(x) { x -= Math.floor(x); return x; }
function minImgF(d) { if (d >= 0.5) return d - 1; if (d < -0.5) return d + 1; return d; }

// Pair accelerations (unit mass, epsilon = 1): the WCA potential, Lennard-Jones cut at its minimum
// and shifted, so disks only push. Summation order is fixed (i < j, ascending) and so the floating
// result is identical everywhere.
function accel(px, py, N, sigma, toBox, minImg, ax, ay) {
  const s2 = sigma * sigma, rc2 = CBRT2 * s2;
  ax.fill(0); ay.fill(0);
  let pe = 0;
  for (let i = 0; i < N; i++) {
    const xi = px[i], yi = py[i];
    for (let j = i + 1; j < N; j++) {
      const dx = minImg(xi - px[j]) * toBox, dy = minImg(yi - py[j]) * toBox;
      const r2 = dx * dx + dy * dy;
      if (r2 < rc2) {
        const q = s2 / r2, q3 = q * q * q;
        const f = 24 * q3 * (2 * q3 - 1) / r2;
        ax[i] += f * dx; ay[i] += f * dy; ax[j] -= f * dx; ay[j] -= f * dy;
        pe += 4 * q3 * (q3 - 1) + 1;
      }
    }
  }
  return pe;
}

// The starting state: every disk in the left half of the box, on a lattice, moving at random.
// Returns plain arrays so both gases can start from the SAME positions and velocities.
export function initial(opts = {}) {
  const { N, sigma, dt, seed, speed } = { ...DEFAULTS, ...opts };
  const r = rng(seed);
  const cols = Math.ceil(Math.sqrt(N / 2)), rows = Math.ceil(N / cols);
  const x = [], y = [], vx = [], vy = [];
  for (let k = 0; k < N; k++) {
    const c = k % cols, w = (k - c) / cols;
    x.push((c + 0.5) / cols * 0.5);
    y.push((w + 0.5) / rows);
    vx.push(gauss(r) * speed); vy.push(gauss(r) * speed);
  }
  // zero total momentum, so the gas does not drift as a whole
  let mx = 0, my = 0; for (let k = 0; k < N; k++) { mx += vx[k]; my += vy[k]; }
  mx /= N; my /= N; for (let k = 0; k < N; k++) { vx[k] -= mx; vy[k] -= my; }
  return { N, sigma, dt, seed, speed, x, y, vx, vy };
}

// ---------------------------------------------------------------- the integer gas
export class IntGas {
  constructor(init) {
    const { N, sigma, dt } = init;
    this.N = N; this.sigma = sigma; this.dt = dt; this.t = 0;
    this.X = new Float64Array(N); this.Y = new Float64Array(N);   // integers held in doubles (< 2^53)
    this.DX = new Float64Array(N); this.DY = new Float64Array(N); // X[n] - X[n-1], also integers
    this.ax = new Float64Array(N); this.ay = new Float64Array(N);
    for (let k = 0; k < N; k++) {
      this.X[k] = wrapInt(Math.round(init.x[k] * L)); this.Y[k] = wrapInt(Math.round(init.y[k] * L));
      this.DX[k] = Math.round(init.vx[k] * dt * L); this.DY[k] = Math.round(init.vy[k] * dt * L);
    }
    this.k = dt * dt * L;
  }
  step(n = 1) {
    const { N, X, Y, DX, DY, ax, ay, k } = this;
    for (let s = 0; s < n; s++) {
      accel(X, Y, N, this.sigma, H, minImgInt, ax, ay);
      for (let i = 0; i < N; i++) {
        DX[i] += Math.round(ax[i] * k); DY[i] += Math.round(ay[i] * k);
        X[i] = wrapInt(X[i] + DX[i]); Y[i] = wrapInt(Y[i] + DY[i]);
      }
      this.t += this.dirSign();
    }
  }
  dirSign() { return this._dir || 1; }
  // Time reversal: the state (X[n+1], D) becomes (X[n], -D). Exactly invertible; applying it twice
  // is the identity. Afterwards step() runs the history backwards, one exact grid step at a time.
  reverse() {
    const { N, X, Y, DX, DY } = this;
    for (let i = 0; i < N; i++) {
      X[i] = wrapInt(X[i] - DX[i]); Y[i] = wrapInt(Y[i] - DY[i]);
      DX[i] = -DX[i]; DY[i] = -DY[i];
    }
    this._dir = -(this._dir || 1);
    this.t += this._dir;   // the pair (X[n+1],X[n]) -> (X[n],X[n+1]) shifts the "current" frame by one
  }
  nudge(i, units) { this.X[i] = wrapInt(this.X[i] + units); }
  clone() {
    const g = Object.create(IntGas.prototype);
    Object.assign(g, this);
    for (const f of ["X", "Y", "DX", "DY", "ax", "ay"]) g[f] = this[f].slice();
    return g;
  }
  pos(i) { return [this.X[i] * H, this.Y[i] * H]; }
  xs() { return Array.from(this.X, v => v * H); }
  ys() { return Array.from(this.Y, v => v * H); }
  key() { return Array.from(this.X).join(",") + "|" + Array.from(this.Y).join(",") + "|" + Array.from(this.DX).join(",") + "|" + Array.from(this.DY).join(","); }
  energy() {
    const pe = accel(this.X, this.Y, this.N, this.sigma, H, minImgInt, this.ax, this.ay);
    let ke = 0; const c = 1 / (this.dt * L);
    for (let i = 0; i < this.N; i++) { const vx = this.DX[i] * c, vy = this.DY[i] * c; ke += 0.5 * (vx * vx + vy * vy); }
    return { ke, pe, e: ke + pe };
  }
}

// ---------------------------------------------------------------- the floating gas
export class FloatGas {
  constructor(init) {
    const { N, sigma, dt } = init;
    this.N = N; this.sigma = sigma; this.dt = dt; this.t = 0; this._dir = 1;
    this.x = Float64Array.from(init.x); this.y = Float64Array.from(init.y);
    this.vx = Float64Array.from(init.vx); this.vy = Float64Array.from(init.vy);
    this.ax = new Float64Array(N); this.ay = new Float64Array(N);
    accel(this.x, this.y, N, sigma, 1, minImgF, this.ax, this.ay);
  }
  step(n = 1) {
    const { N, x, y, vx, vy, ax, ay, dt } = this, h = dt / 2;
    for (let s = 0; s < n; s++) {
      for (let i = 0; i < N; i++) {
        vx[i] += ax[i] * h; vy[i] += ay[i] * h;
        x[i] = wrapF(x[i] + vx[i] * dt); y[i] = wrapF(y[i] + vy[i] * dt);
      }
      accel(x, y, N, this.sigma, 1, minImgF, ax, ay);
      for (let i = 0; i < N; i++) { vx[i] += ax[i] * h; vy[i] += ay[i] * h; }
      this.t += this._dir;
    }
  }
  reverse() {
    for (let i = 0; i < this.N; i++) { this.vx[i] = -this.vx[i]; this.vy[i] = -this.vy[i]; }
    this._dir = -this._dir;
  }
  nudge(i, dx) { this.x[i] = wrapF(this.x[i] + dx); accel(this.x, this.y, this.N, this.sigma, 1, minImgF, this.ax, this.ay); }
  clone() {
    const g = Object.create(FloatGas.prototype);
    Object.assign(g, this);
    for (const f of ["x", "y", "vx", "vy", "ax", "ay"]) g[f] = this[f].slice();
    return g;
  }
  xs() { return Array.from(this.x); }
  ys() { return Array.from(this.y); }
  energy() {
    const pe = accel(this.x, this.y, this.N, this.sigma, 1, minImgF, new Float64Array(this.N), new Float64Array(this.N));
    let ke = 0; for (let i = 0; i < this.N; i++) ke += 0.5 * (this.vx[i] * this.vx[i] + this.vy[i] * this.vy[i]);
    return { ke, pe, e: ke + pe };
  }
}

// ---------------------------------------------------------------- what we look at
// The fraction of disks in the left half of the box (x < 1/2). It starts at 1.
export function leftFraction(xs) { let c = 0; for (const x of xs) if (x < 0.5) c++; return c / xs.length; }

// The largest distance (box units, minimum image) between the same disk in two gases.
export function maxSeparation(ax, ay, bx, by) {
  let m = 0;
  for (let i = 0; i < ax.length; i++) {
    const dx = minImgF(ax[i] - bx[i]), dy = minImgF(ay[i] - by[i]);
    const d = Math.sqrt(dx * dx + dy * dy); if (d > m) m = d;
  }
  return m;
}

// Coarse-grained (Boltzmann) entropy on a G x G grid: ln( N! / prod n_c! ), counted exactly as a sum
// of logs of integers. Reported relative to its value for the evenest possible spread, so 1 = mixed.
// (Uses Math.log, so it is a DISPLAY quantity: compare it with a tolerance, never bit for bit.)
export function coarseEntropy(xs, ys, G = 4) {
  const N = xs.length, n = new Array(G * G).fill(0);
  for (let i = 0; i < N; i++) n[Math.min(G - 1, Math.floor(ys[i] * G)) * G + Math.min(G - 1, Math.floor(xs[i] * G))]++;
  const lf = m => { let s = 0; for (let k = 2; k <= m; k++) s += Math.log(k); return s; };
  const S = lf(N) - n.reduce((a, m) => a + lf(m), 0);
  const cells = G * G, q = Math.floor(N / cells), r = N - q * cells;
  const Smax = lf(N) - (r * lf(q + 1) + (cells - r) * lf(q));
  return S / Smax;
}
