"""Summarize a complete request window; not token-interval ITL statistics."""
import argparse,json,math

def percentile(values,p):
    if not values:return None
    values=sorted(values);return values[max(0,math.ceil(len(values)*p)-1)]

def summarize(rows):
    if not rows:raise ValueError('no rows')
    for r in rows:
        if r['end_s']<r['start_s']:raise ValueError('negative request duration')
        if r.get('first_s') is not None and not r['start_s']<=r['first_s']<=r['end_s']:
            raise ValueError('invalid first-output timestamp')
        if r.get('output_tokens') is not None and r['output_tokens']<0:
            raise ValueError('negative token count')
    success=[r for r in rows if not r.get('error') and r.get('finish_reason') is not None]
    ttft=[1000*(r['first_s']-r['start_s']) for r in success if r.get('first_s') is not None]
    tpot=[1000*(r['end_s']-r['first_s'])/(r['output_tokens']-1) for r in success
          if r.get('first_s') is not None and (r.get('output_tokens') or 0)>1]
    window=max(r['end_s'] for r in rows)-min(r['start_s'] for r in rows)
    known=all(r.get('output_tokens') is not None for r in success)
    return {'requests':len(rows),'completed':len(success),
        'error_or_incomplete_rate':1-len(success)/len(rows),
        'window_s':window,'ttft_p50_ms':percentile(ttft,.5),'ttft_p95_ms':percentile(ttft,.95),
        'request_tpot_p95_ms':percentile(tpot,.95),'tpot_samples':len(tpot),
        'output_tps':sum(r['output_tokens'] for r in success)/window if window>0 and success and known else None,
        'quality_labeled_requests':sum(r.get('quality_pass') is not None for r in success),
        'quality_pass_rps':sum(r.get('quality_pass') is True for r in success)/window if window>0 else None,
        'note':'Nearest-rank percentiles; single-token outputs excluded from TPOT. Quality-pass RPS is not SLO-qualified goodput.'}

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('jsonl');a=p.parse_args()
    with open(a.jsonl) as f:rows=[json.loads(line) for line in f if line.strip()]
    print(json.dumps(summarize(rows),ensure_ascii=False,indent=2))
