import assert from 'node:assert/strict';

const EPS = 1e-9;
const DEFAULTS = Object.freeze({
  theta: 3,
  dOut: 18,
  dBack: 6,
  residence: 1.5,
  samples: 4000,
  jitter: 8
});
const SERVER_EXTRAS = Object.freeze([1.25, 2.75, 4.5]);

function close(actual, expected, message, epsilon = EPS) {
  assert.ok(
    Math.abs(actual - expected) <= epsilon,
    `${message}: expected ${expected}, received ${actual}`
  );
}

function exchange(theta, dOut, dBack, residence, t1 = 0) {
  const t2 = t1 + dOut + theta;
  const t3 = t2 + residence;
  const t4 = t1 + dOut + residence + dBack;
  const offset = ((t2 - t1) + (t3 - t4)) / 2;
  const delay = (t4 - t1) - (t3 - t2);
  return { t1, t2, t3, t4, offset, delay };
}

function addVectors(left, right) {
  return left.map((value, index) => value + right[index]);
}

function scaleVector(vector, scale) {
  return vector.map((value) => value * scale);
}

function symbolicCheck() {
  // Coefficient order: theta, dOut, dBack, residence, constant.
  const t1 = [0, 0, 0, 0, 0];
  const t2 = [1, 1, 0, 0, 0];
  const t3 = [1, 1, 0, 1, 0];
  const t4 = [0, 1, 1, 1, 0];
  const offset = scaleVector(
    addVectors(addVectors(scaleVector(t1, -1), t2), addVectors(t3, scaleVector(t4, -1))),
    0.5
  );
  const delay = addVectors(
    addVectors(t4, scaleVector(t1, -1)),
    addVectors(t2, scaleVector(t3, -1))
  );
  assert.deepEqual(offset, [1, 0.5, -0.5, 0, 0]);
  assert.deepEqual(delay, [0, 1, 1, 0, 0]);
  return { offset, delay };
}

function queueJitter(index, amplitude) {
  if (index === 0 || amplitude === 0) return 0;
  const state = (Math.imul(index, 1664525) + 1013904223) >>> 0;
  const unit = state / 4294967296;
  return unit * unit * amplitude;
}

function fnv1a(text) {
  let hash = 0x811c9dc5;
  for (let index = 0; index < text.length; index += 1) {
    hash ^= text.charCodeAt(index);
    hash = Math.imul(hash, 0x01000193);
  }
  return (hash >>> 0).toString(16).padStart(8, '0');
}

function sampleRun(base, count, jitterAmplitude) {
  const a = base.t2 - base.t1;
  const roundTrip = base.delay;
  const rows = [];
  let fingerprintInput = '';
  let queuePeak = 0;

  for (let index = 0; index < count; index += 1) {
    const queue = queueJitter(index, jitterAmplitude);
    const t1 = index * 50;
    const t2 = t1 + a + queue / 2;
    const t3 = t2 + DEFAULTS.residence;
    const t4 = t1 + roundTrip + queue + DEFAULTS.residence;
    const offset = ((t2 - t1) + (t3 - t4)) / 2;
    const delay = (t4 - t1) - (t3 - t2);
    rows.push({ t1, t2, t3, t4, offset, delay, queue });
    queuePeak = Math.max(queuePeak, queue);
    fingerprintInput += [t1, t2, t3, t4].map((value) => value.toFixed(6)).join(',') + '|';
  }

  const mean = rows.reduce((sum, row) => sum + row.offset, 0) / rows.length;
  const minimum = rows.reduce((best, row) => row.delay < best.delay ? row : best, rows[0]);
  const rms = Math.sqrt(
    rows.reduce((sum, row) => sum + (row.offset - mean) ** 2, 0) / rows.length
  );
  return {
    rows,
    mean,
    minimumOffset: minimum.offset,
    minimumDelay: minimum.delay,
    rms,
    queuePeak,
    fingerprint: fnv1a(fingerprintInput)
  };
}

function marzullo(intervals) {
  const events = intervals.flatMap((interval) => [
    { x: interval.low, delta: 1 },
    { x: interval.high, delta: -1 }
  ]).sort((left, right) => left.x - right.x || right.delta - left.delta);

  let count = 0;
  let best = 0;
  let low = null;
  let high = null;
  for (const event of events) {
    if (event.delta === 1) {
      count += 1;
      if (count > best) {
        best = count;
        low = event.x;
        high = event.x;
      }
    } else {
      if (count === best) high = event.x;
      count -= 1;
    }
  }
  return { low, high, count: best, midpoint: (low + high) / 2 };
}

const symbolic = symbolicCheck();
const base = exchange(
  DEFAULTS.theta,
  DEFAULTS.dOut,
  DEFAULTS.dBack,
  DEFAULTS.residence
);

close(base.t1, 0, 'T1');
close(base.t2, 21, 'T2');
close(base.t3, 22.5, 'T3');
close(base.t4, 25.5, 'T4');
close(base.offset, 9, 'NTP offset estimate');
close(base.delay, 24, 'round-trip delay');
close(base.offset - DEFAULTS.theta, 6, 'offset bias');
close(
  base.offset,
  DEFAULTS.theta + (DEFAULTS.dOut - DEFAULTS.dBack) / 2,
  'half-asymmetry identity'
);

for (const values of [
  [-19.75, 0, 41.5, 0],
  [8.125, 33.75, 2.25, 7.5],
  [0, 0.125, 0.125, 100],
  [91, 1000, 3, 0.001]
]) {
  const [theta, dOut, dBack, residence] = values;
  const result = exchange(theta, dOut, dBack, residence);
  close(result.offset, theta + (dOut - dBack) / 2, 'arbitrary asymmetry');
  close(result.delay, dOut + dBack, 'arbitrary round trip');
}

const a = base.t2 - base.t1;
const b = base.t4 - base.t3;
const thetaLow = -b;
const thetaHigh = a;
close(thetaLow, -3, 'ambiguity-band low endpoint');
close(thetaHigh, 21, 'ambiguity-band high endpoint');
close(thetaHigh - thetaLow, base.delay, 'ambiguity-band width');
assert.equal(3 - 2, 1, 'two independent equations in three unknowns leave one degree of freedom');

for (let step = 0; step <= 100; step += 1) {
  const latentOut = base.delay * step / 100;
  const latentBack = base.delay - latentOut;
  const latentTheta = a - latentOut;
  const same = exchange(latentTheta, latentOut, latentBack, DEFAULTS.residence);
  close(same.t1, base.t1, 'invariant T1');
  close(same.t2, base.t2, 'invariant T2');
  close(same.t3, base.t3, 'invariant T3');
  close(same.t4, base.t4, 'invariant T4');
  close(same.offset - latentTheta, (latentOut - latentBack) / 2, 'sweep bias');
}

for (const count of [1, 8, 257, DEFAULTS.samples]) {
  for (const jitter of [0, DEFAULTS.jitter, 19.5]) {
    const run = sampleRun(base, count, jitter);
    close(run.mean, base.offset, `mean estimator for ${count} samples`, 1e-8);
    close(run.minimumOffset, base.offset, `minimum estimator for ${count} samples`, 1e-8);
    close(run.rms, 0, `residual for ${count} samples`, 1e-8);
    for (const row of run.rows) {
      close(row.offset, base.offset, 'per-sample structural bias', 1e-8);
    }
  }
}

const run = sampleRun(base, DEFAULTS.samples, DEFAULTS.jitter);
const intervals = SERVER_EXTRAS.map((extra) => {
  const delay = base.delay + 2 * extra;
  return { low: base.offset - delay / 2, high: base.offset + delay / 2 };
});
assert.equal(run.fingerprint, 'd459c6e8', 'default packet-log fingerprint');
close(run.queuePeak, 7.998940942471137, 'default observed queue peak');
for (const [index, expected] of [
  [0, { delay: 26.5, low: -4.25, high: 22.25 }],
  [1, { delay: 29.5, low: -5.75, high: 23.75 }],
  [2, { delay: 33, low: -7.5, high: 25.5 }]
]) {
  close(intervals[index].high - intervals[index].low, expected.delay, `server ${index + 1} delay`);
  close(intervals[index].low, expected.low, `server ${index + 1} interval low`);
  close(intervals[index].high, expected.high, `server ${index + 1} interval high`);
}
const overlap = marzullo(intervals);
assert.equal(overlap.count, SERVER_EXTRAS.length);
close(overlap.midpoint, base.offset, 'Marzullo midpoint');
close(overlap.low, -4.25, 'Marzullo low endpoint');
close(overlap.high, 22.25, 'Marzullo high endpoint');
close(overlap.high - overlap.low, 26.5, 'Marzullo width');

console.log('symbolic offset coefficients [theta, d_out, d_back, residence, constant]:', symbolic.offset);
console.log('symbolic delay coefficients  [theta, d_out, d_back, residence, constant]:', symbolic.delay);
console.log('default timestamps (ms):', {
  T1: base.t1,
  T2: base.t2,
  T3: base.t3,
  T4: base.t4
});
console.log('default exchange (ms):', {
  trueOffset: DEFAULTS.theta,
  dOut: DEFAULTS.dOut,
  dBack: DEFAULTS.dBack,
  asymmetry: DEFAULTS.dOut - DEFAULTS.dBack,
  ntpEstimate: base.offset,
  bias: base.offset - DEFAULTS.theta,
  roundTrip: base.delay
});
console.log('ambiguity band (ms):', {
  low: thetaLow,
  high: thetaHigh,
  width: thetaHigh - thetaLow,
  equations: 2,
  unknowns: 3,
  freeDimensions: 1
});
console.log('deterministic jitter run:', {
  samples: DEFAULTS.samples,
  jitterAmplitudeMs: DEFAULTS.jitter,
  queuePeakMs: run.queuePeak,
  meanOffsetMs: run.mean,
  minimumDelayOffsetMs: run.minimumOffset,
  minimumRoundTripMs: run.minimumDelay,
  rmsResidualMs: run.rms,
  fingerprint: run.fingerprint
});
console.log('first three observed timestamp rows (ms):', run.rows.slice(0, 3).map((row) => ({
  T1: row.t1,
  T2: row.t2,
  T3: row.t3,
  T4: row.t4,
  roundTrip: row.delay
})));
console.log('three best-sample server intervals (ms):', intervals);
console.log('three-server Marzullo overlap (ms): overlap', {
  low: overlap.low,
  high: overlap.high,
  width: overlap.high - overlap.low,
  midpoint: overlap.midpoint
});
console.log('PASS: every displayed default and structural invariant recomputed from scratch.');
