"""Usage: python3 compare.py BASE_CHECKOUT HEAD_CHECKOUT OUTPUT_DIRECTORY
Copy probe.ts to apps/server/probe-47339.ts in each installed checkout first.
No fake CLI, cached responses, concurrency override, or production data is used.
"""
import sys, subprocess, pathlib, datetime, json, statistics, time
base,head,out=sys.argv[1:]
dest=pathlib.Path(out)/datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ')
dest.mkdir(parents=True)
results=[]
for index,side in enumerate(['base','head','head','base','base','head'],1):
    if index > 1:
        print('Waiting 65 seconds between blocks for GitLab burst allowance.',flush=True)
        time.sleep(35)
        time.sleep(30)
    print(f'Starting block {index}: {side}',flush=True)
    proc=subprocess.run(['node','probe-47339.ts'],cwd=pathlib.Path(base if side=='base' else head)/'apps/server',capture_output=True,text=True)
    (dest/f'{index}-{side}.jsonl').write_text(proc.stdout)
    if proc.returncode:
        print(f'Block {index} failed, return code {proc.returncode}; stopping rather than retrying service failures.',flush=True)
        sys.exit(1)
    summary=[json.loads(l) for l in proc.stdout.splitlines() if l.startswith('{')][-1]
    if summary['bgErrors']:
        print('Background service error; excluding block and stopping.',flush=True)
        sys.exit(1)
    results.append(dict(block=index,side=side,**summary))
    print(json.dumps({k:summary[k] for k in ['sha','reads','medianWaitMs','medianTotalMs','bgCompleted','bgErrors']}),flush=True)
(dest/'results.json').write_text(json.dumps(results,indent=2))
report={}
for side in ['base','head']:
    blocks=[r for r in results if r['side']==side]
    rows=[row for b in blocks for row in b['rows']]
    report[side]={'sha':blocks[0]['sha'],'reads':len(rows),'medianWaitMs':statistics.median(r['waitMs'] for r in rows),'medianTotalMs':statistics.median(r['totalMs'] for r in rows),'blockMedianWaitMs':[b['medianWaitMs'] for b in blocks],'blockMedianTotalMs':[b['medianTotalMs'] for b in blocks],'backgroundErrors':sum(b['bgErrors'] for b in blocks)}
fingerprints={}
for b in results:
    for r in b['rows']:
        fingerprints.setdefault(r['issue'],set()).add(tuple(p['digest'] for p in r['parts']))
report['identicalResponseFingerprints']=all(len(v)==1 for v in fingerprints.values())
report['responseVersionsByIssue']={k:len(v) for k,v in fingerprints.items()}
report['waitImprovementMs']=report['base']['medianWaitMs']-report['head']['medianWaitMs']
report['totalImprovementMs']=report['base']['medianTotalMs']-report['head']['medianTotalMs']
report['maxBlockMedianWaitSpreadMs']=max(max(report[s]['blockMedianWaitMs'])-min(report[s]['blockMedianWaitMs']) for s in ['base','head'])
report['maxBlockMedianTotalSpreadMs']=max(max(report[s]['blockMedianTotalMs'])-min(report[s]['blockMedianTotalMs']) for s in ['base','head'])
(dest/'comparison.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2),flush=True)
