const assert = require('assert');
const {
  analyzeMotionLog,
  cadenceSummary,
  motionIntervals,
  parseMotionTraceLine,
} = require('../tools/analyze-motion-trace');

const activeTrace = '[2026-07-24T23:50:59.601Z] [MOTION_TRACE] dhiru-mac-pro.lan peer ended duration=22221ms recv=1472 render=2511 interpolated=2026 coalesced=977 stale=10 seqSkipped=98 sourceAvg/max=15.2/2072.0ms>16=107 arrivalAvg/max=15.1/2075.0ms>16=92 renderAvg/max=8.8/2066.0ms>16=40';

{
  const trace = parseMotionTraceLine(activeTrace);
  assert(trace);
  assert.strictEqual(trace.timestamp, '2026-07-24T23:50:59.601Z');
  assert.strictEqual(trace.arrivals, 1472);
  assert.strictEqual(trace.renders, 2511);
  assert.strictEqual(trace.interpolated, 2026);
  assert.strictEqual(trace.arrival.overFrame, 92);
  assert.strictEqual(trace.render.overFrame, 40);

  const summary = cadenceSummary(trace);
  assert.strictEqual(summary.arrivalOverFramePercent.toFixed(2), '6.25');
  assert.strictEqual(summary.renderOverFramePercent.toFixed(2), '1.59');
  assert.strictEqual(summary.overFrameReductionPercent.toFixed(1), '74.5');
  assert.strictEqual(summary.receiveHz.toFixed(1), '66.2');
  assert.strictEqual(summary.renderHz.toFixed(1), '113.0');
}

{
  const sessions = analyzeMotionLog([
    '[2026-07-24T23:50:23.013Z] [HELLO] dhiru-mac-pro.lan protocol=6 192.168.86.21 via Wi-Fi en0',
    activeTrace,
    '[2026-07-25T00:00:00.000Z] [HELLO] dhiru-mac-pro.lan protocol=7 192.168.86.21 via Wi-Fi en0',
    '[2026-07-25T00:00:02.000Z] [MOTION_TRACE] dhiru-mac-pro.lan active duration=2000ms recv=180 render=360 interpolated=220 coalesced=30 stale=0 seqSkipped=2 sourceAvg/max=11.0/24.0ms>16=8 arrivalAvg/max=11.1/25.0ms>16=9 renderAvg/max=5.5/17.0ms>16=1',
    '[2026-07-25T00:00:04.000Z] [MOTION_TRACE] dhiru-mac-pro.lan active duration=4000ms recv=380 render=760 interpolated=480 coalesced=60 stale=0 seqSkipped=4 sourceAvg/max=10.5/24.0ms>16=14 arrivalAvg/max=10.6/25.0ms>16=15 renderAvg/max=5.3/17.0ms>16=2',
  ].join('\n'));

  assert.strictEqual(sessions.length, 3);
  assert.strictEqual(sessions[0].protocol, 6);
  assert.strictEqual(sessions[1].protocol, 7);
  assert.strictEqual(sessions[1].summary.renderOverFramePercent.toFixed(2), '0.28');

  const intervals = motionIntervals(sessions);
  assert.strictEqual(intervals.length, 1);
  assert.strictEqual(intervals[0].durationMs, 2000);
  assert.strictEqual(intervals[0].arrivals, 200);
  assert.strictEqual(intervals[0].renders, 400);
  assert.strictEqual(intervals[0].summary.receiveHz, 100);
  assert.strictEqual(intervals[0].summary.renderHz, 200);
  assert.strictEqual(intervals[0].summary.arrivalOverFramePercent.toFixed(2), '3.00');
  assert.strictEqual(intervals[0].summary.renderOverFramePercent.toFixed(2), '0.25');
  assert.strictEqual(intervals[0].summary.overFrameReductionPercent.toFixed(1), '91.7');
}

console.log('motion trace analysis tests passed');
