import csv
import hashlib
import json
from pathlib import Path
import sys

R=Path(__file__).parent
label=sys.argv[1] if len(sys.argv)>1 else 'timeline'
data=json.loads((R/(label+'-window.json')).read_text())
summary=json.loads((R/(label+'-window-summary.json')).read_text())
pub=json.loads((R/(label+'-publisher.json')).read_text())['metrics']
result={};rows=[]
for src,s in summary.items():
    key=hashlib.sha256(src.encode()).hexdigest();profile=pub['profile']['channels'][key]
    events=[]
    for event in profile.get('replacements',[]):
        active=event['inflight'];now=event['at_ns'];phase='no_inflight_record'
        if active and 'sink_finished_ns' in active:
            if active['sink_started_ns']<=now<=active['sink_finished_ns']:phase='sink_call'
            elif now>=active['sink_finished_ns']:phase='after_sink'
            else:phase='before_sink'
        elif active:phase='inflight_incomplete'
        events.append(dict(old_sequence=event['old_sequence'],new_sequence=event['new_sequence'],
            gap_ms=(now-event['old_enqueued_ns'])/1e6,phase=phase,
            other_channel=bool(active and active['key']!=key),
            sink_ms=(active['sink_finished_ns']-active['sink_started_ns'])/1e6 if active and 'sink_finished_ns' in active else None,
            sink_cpu_ms=active.get('sink_cpu_ns',0)/1e6 if active else None))
    lengths=[x['channels'][src]['redis']['length'] for x in data['samples']]
    ttl=[x['channels'][src]['redis']['pttl'] for x in data['samples']]
    row=dict(channel=src[-2:],result_fps=s['fps']['result'],submit_fps=s['fps']['publisher_submit'],redis_fps=s['redis_fps'],
        queue_min=min(s['queue']),queue_max=max(s['queue']),stale=s['counter_delta'].get('stale',0),drop=s['counter_delta'].get('queue_drop',0),
        frame_replaced=profile['counts'].get('replaced_by_frame',0),state_replaced=profile['counts'].get('replaced_by_state',0),
        stored_min=min(lengths),stored_max=max(lengths),ttl_min_ms=min(ttl),ttl_max_ms=max(ttl))
    rows.append(row);result[src[-2:]]=dict(row=row,timings=profile['timings'],replacements=events,counts=profile['counts'])
with (R/(label+'-comparison.csv')).open('w') as f:
    w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
(R/(label+'-analysis.json')).write_text(json.dumps(result,indent=2))
print(json.dumps(result,indent=2))
