// node analyze.mjs runs/<dir> <process-regex> [--csv out.csv]
// Bytes sent/received per PHASE (between marks) for the processes matching the regex, plus
// per-remote totals. Counters in net.log are cumulative per connection: a connection already
// open at the first sample is a baseline (its earlier bytes predate the run); one first seen
// later counts from zero. Each sample-to-sample delta is assigned to the phase it lands in.
import fs from 'fs';
const [dir, re, flag, csvOut] = process.argv.slice(2);
const filt = new RegExp(re, 'i');
const marks = fs.readFileSync(`${dir}/marks.csv`, 'utf8').trim().split('\n').slice(1).map(l => { const [t, m] = l.split(','); return { t: +t, m }; });

// Phases: named by the mark that opens them.
const PH = { 'app open': 'open', 'rec start': 'recording', 'audio end': 'stopping', 'rec stopped': 'processing',
  'summary ready': 'after summary (3 min)', 'wifi off': 'offline', 'offline rec start': 'offline', 'offline rec stopped': 'offline',
  'offline done': 'offline', 'wifi on': 'reconnect (3 min)', 'end': 'quit' };
const phaseAt = t => { let p = 'before'; for (const k of marks) if (t >= k.t) p = PH[k.m] || k.m; return p; };

const lines = fs.readFileSync(`${dir}/net.log`, 'utf8').split('\n');
const last = new Map(); // conn key -> {in,out}
const firstT = (() => { for (const l of lines) if (l.startsWith('#t=')) return +l.slice(3); })();
const agg = new Map(); // proc -> phase -> {out,in}
const remotes = new Map(); // proc -> remote -> out
const recv = new Map(); // proc -> remote -> in
let t = null, proc = null;
for (const l of lines) {
  if (l.startsWith('#t=')) { t = +l.slice(3); continue; }
  if (!l || l.startsWith(',')) continue;
  const [name, bin, bout] = l.split(',');
  if (!/^(tcp|udp|quic)[46] /.test(name)) { proc = name.replace(/\.\d+$/, ''); continue; }
  if (!proc || bin === '' || !filt.test(proc)) continue;
  const k = proc + '|' + name, cur = { in: +bin, out: +bout };
  const prev = last.get(k) ?? (t === firstT ? cur : { in: 0, out: 0 });
  const dout = Math.max(0, cur.out - prev.out), din = Math.max(0, cur.in - prev.in);
  last.set(k, cur);
  if (!dout && !din) continue;
  const ph = phaseAt(t);
  const pa = agg.get(proc) || new Map(); const s = pa.get(ph) || { out: 0, in: 0 };
  s.out += dout; s.in += din; pa.set(ph, s); agg.set(proc, pa);
  const remote = name.split('<->')[1]?.replace(/[.:]\d+$/, '') || '?';
  const rm = remotes.get(proc) || new Map(); rm.set(remote, (rm.get(remote) || 0) + dout); remotes.set(proc, rm);
  const rr = recv.get(proc) || new Map(); rr.set(remote, (rr.get(remote) || 0) + din); recv.set(proc, rr);
}
const mb = b => (b / 1e6).toFixed(2);
const rows = [];
for (const [p, pa] of agg) {
  let to = 0, ti = 0;
  console.log(`\n${p}`);
  for (const [ph, s] of pa) { to += s.out; ti += s.in; console.log(`  ${ph.padEnd(24)} sent ${mb(s.out).padStart(9)} MB   received ${mb(s.in).padStart(8)} MB`); rows.push([p, ph, s.out, s.in]); }
  console.log(`  ${'TOTAL'.padEnd(24)} sent ${mb(to).padStart(9)} MB   received ${mb(ti).padStart(8)} MB`);
  for (const [r, o] of [...remotes.get(p)].sort((a, b) => b[1] - a[1]).slice(0, 5)) console.log(`    -> ${r.padEnd(40)} sent ${mb(o)} MB   received ${mb(recv.get(p).get(r))} MB`);
}
if (flag === '--csv') fs.writeFileSync(csvOut, 'process,phase,bytes_sent,bytes_received\n' + rows.map(r => r.join(',')).join('\n') + '\n');
