"""Synthetic paced file producer; measures follower lag, not Android throughput."""
import json, os, subprocess, sys, tempfile, threading, time
from pathlib import Path
A=Path(__file__).resolve().parent
REPO=A.parents[2]
source=[json.loads(l) for l in (A/'events/odkcollect-Rep2.jsonl').read_text().splitlines()][:1200]
results=[]
for interval in [100,250,500]:
    with tempfile.TemporaryDirectory(prefix='region-follow-',dir=REPO/'artifacts') as d:
        root=Path(d);input_file=root/'events.jsonl';input_file.touch();out=root/'out'
        proc=subprocess.Popen([sys.executable,'-m','tools.region_flow_shadow','--input',str(input_file),
          '--output',str(out),'--run-id',source[0]['run_id'],'--follow','--idle-timeout','.5',
          '--interval',str(interval)],cwd=REPO,stdout=subprocess.PIPE,stderr=subprocess.PIPE,
          env={**os.environ,'OPENBLAS_NUM_THREADS':'1','OMP_NUM_THREADS':'1','PYTHONDONTWRITEBYTECODE':'1'})
        arrivals={};lags=[];latencies=[];seen=set();produced=[0]
        def produce():
            with input_file.open('a') as f:
                start=time.monotonic()
                for i,e in enumerate(source,1):
                    delay=start+(i-1)/500-time.monotonic()
                    if delay>0:time.sleep(delay)
                    arrivals[i]=time.monotonic();f.write(json.dumps(e,separators=(',',':'))+'\n');f.flush();produced[0]=i
        writer=threading.Thread(target=produce);writer.start()
        while proc.poll() is None:
            index=out/'index.json'
            if index.exists():
                snaps=json.loads(index.read_text())['snapshots']
                for s in snaps:
                    n=s['confirmed_count']
                    if s['id'] not in seen:
                        seen.add(s['id']);latencies.append((time.monotonic()-arrivals[n])*1000)
                lags.append(produced[0]-snaps[-1]['confirmed_count'])
            time.sleep(.005)
        writer.join();stdout,stderr=proc.communicate()
        assert proc.returncode==0,stderr.decode()
        perf=json.loads((out/'performance.json').read_text());assert perf['accepted']==1200
        results.append(dict(interval=interval,events=1200,synthetic_producer_rate_per_second=500,
          observed_snapshot_publication_lag_max_events=max(lags,default=0),
          event_to_snapshot_publication_ms_max=max(latencies),
          snapshot_publication_poll_resolution_ms=5,terminal_pending=perf['pending_execution_count'],
          snapshots=perf['snapshot_count'],errors=perf['errors'],scope='Synthetic local file tail, no Android/native throughput claim'))
(A/'follow-benchmark.json').write_text(json.dumps(results,indent=2)+'\n')
print('FOLLOW_BENCHMARK_PASS',len(results))
