#!/usr/bin/env python3
"""Sequential GET observations for an endpoint you own; no WordPress-specific claims."""
from __future__ import annotations
import argparse,datetime,json,math,statistics,time
from pathlib import Path
from urllib.error import HTTPError,URLError
from urllib.parse import urlsplit
from urllib.request import Request,urlopen

def observe(url:str,timeout:float,marker:str|None=None,max_body_bytes:int=2097152)->dict:
    start=time.perf_counter();status=None;headers_ms=None;body=b'';error=None;truncated=False
    try:
        with urlopen(Request(url,headers={'User-Agent':'VPSBench-Sequential-HTTP-Probe/1.0'}),timeout=timeout) as r:
            status=r.status;headers_ms=(time.perf_counter()-start)*1000
            body=r.read(max_body_bytes+1);truncated=len(body)>max_body_bytes
        if truncated:error='body-limit-exceeded; full transfer not measured'
        elif marker is not None and marker not in body.decode('utf-8',errors='replace'):error='expected-marker-missing'
    except HTTPError as e:status=e.code;error='http-error'
    except (URLError,TimeoutError,OSError) as e:error=type(e).__name__
    elapsed=(time.perf_counter()-start)*1000
    success=status is not None and 200<=status<300 and error is None
    return {'http_status':status,'success':success,'error':error,'headers_ms':round(headers_ms,3) if headers_ms is not None else None,'total_ms':round(elapsed,3),'bytes_read':len(body),'body_truncated':truncated}

def summarize(rows:list[dict])->dict:
    times=sorted(r['total_ms'] for r in rows if r['success'])
    return {'attempts':len(rows),'successes':len(times),'failures':len(rows)-len(times),'success_median_ms':round(statistics.median(times),3) if times else None,'success_p95_ms':times[math.ceil(.95*len(times))-1] if times else None,'p95_method':'nearest rank ceil(0.95*n), successful requests only; failures reported separately'}

def probe(url:str,attempts:int,warmup:int,timeout:float,marker:str|None=None)->dict:
    parsed=urlsplit(url)
    if parsed.scheme not in ('http','https') or not parsed.hostname or parsed.username or parsed.password:raise ValueError('Use an HTTP(S) URL without embedded credentials')
    pre=[observe(url,timeout,marker) for _ in range(warmup)]
    rows=[{'attempt':i+1,**observe(url,timeout,marker)} for i in range(attempts)]
    return {'schema_version':1,'observed_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'url':url,'method':'sequential urllib GET; one new urlopen per attempt; default TLS verification; no browser or authenticated editor','warmup':pre,'samples':rows,'summary':summarize(rows),'timeout_seconds':timeout,'expected_marker_set':marker is not None,'body_limit_bytes':2097152,'limits':['Not a concurrent load test','headers_ms includes DNS/connect/TLS/header retrieval; not PHP execution time or browser paint','total_ms includes reading the body; redirects follow urllib defaults','No claim of representative VPS or WordPress performance']}

def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--url',required=True);p.add_argument('--attempts',type=int,default=10);p.add_argument('--warmup',type=int,default=1)
    p.add_argument('--timeout',type=float,default=5);p.add_argument('--marker');p.add_argument('--out',type=Path,required=True)
    a=p.parse_args()
    if not 1<=a.attempts<=100 or not 0<=a.warmup<=10 or not 1<=a.timeout<=30:p.error('attempts: 1..100; warmup: 0..10; timeout: 1..30 seconds')
    if a.out.exists():p.error('Output exists; choose a new filename to retain the previous trial')
    result=probe(a.url,a.attempts,a.warmup,a.timeout,a.marker)
    a.out.parent.mkdir(parents=True,exist_ok=True);a.out.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
    print(json.dumps(result['summary'],ensure_ascii=False))

if __name__=='__main__':main()
