"""Builds summary.json, the single source of every number quoted in the article."""
import json, collections, statistics as st
from urllib.parse import urlsplit
R=[json.loads(l) for l in open('chains.jsonl')]
C=json.load(open('canonical_check.json'))
V=("http://","http://www.","https://","https://www.")
live=[r for r in R if any(r['variants'][v]['end']=='ok' for v in V)]
def kind(a,b):
    A,B=urlsplit(a),urlsplit(b); t=[]
    if A.scheme!=B.scheme: t.append('scheme')
    ha,hb=A.hostname or '',B.hostname or ''
    if ha!=hb: t.append('www' if ha.removeprefix('www.')==hb.removeprefix('www.') else 'other-host')
    if (A.path or '/')!=(B.path or '/') or A.query!=B.query: t.append('path')
    return '+'.join(t) or 'same'
ok_chains=[(r,v,r['variants'][v]) for r in live for v in V if r['variants'][v]['end']=='ok']
hops_by_variant={v:collections.Counter() for v in V}
codes=collections.Counter(); scheme_codes=collections.Counter(); seq=collections.Counter(); t_by=collections.defaultdict(list)
for r,v,c in ok_chains:
    h=c['hops']; n=len(h)-1
    hops_by_variant[v][min(n,3)]+=1
    for i in range(n):
        codes[h[i]['code']]+=1
        if 'scheme' in kind(h[i]['url'],h[i+1]['url']): scheme_codes[h[i]['code']]+=1
    if n>=2: seq[' -> '.join(kind(h[i]['url'],h[i+1]['url']) for i in range(n))]+=1
    if n: t_by[min(n,3)].append(sum(x['t'] for x in h[:-1]))
worst=collections.Counter(min(max(len(r['variants'][v]['hops'])-1 for v in V if r['variants'][v]['end']=='ok'),3) for r in live)
temp=lambda c: c[302]+c[303]+c[307]
http_no_upgrade=sum(1 for r in live if r['variants']['http://']['end']=='ok' and len(r['variants']['http://']['hops'])==1)
multi=sum(seq.values())
S={
 "sample":{"list":"Tranco 94GG2","ranks":"1-100000","seed":20261004,"domains":len(R),"answered_2xx":len(live),
   "variant_tests":len(R)*4,"measured":"2026-10-04","vantage":"MacBook, Poland, residential connection"},
 "two_plus_hops_any_variant":{"domains":sum(worst[k] for k in (2,3)),"share":round(sum(worst[k] for k in (2,3))/len(live),4)},
 "worst_variant_hops":{str(k):worst[k] for k in sorted(worst)},
 "hops_by_variant":{v:{str(k):n for k,n in sorted(c.items())} for v,c in hops_by_variant.items()},
 "redirect_codes":dict(codes),"temporary_share":round(temp(codes)/sum(codes.values()),4),
 "https_upgrade_codes":dict(scheme_codes),"https_upgrade_temporary_share":round(temp(scheme_codes)/sum(scheme_codes.values()),4),
 "chains_2plus":multi,"top_sequences":seq.most_common(6),
 "median_redirect_seconds":{str(k):round(st.median(v),3) for k,v in sorted(t_by.items())},
 "chains_per_hopcount":{str(k):len(v) for k,v in sorted(t_by.items())},
 "http_served_without_https_redirect":{"domains":http_no_upgrade,"share":round(http_no_upgrade/len(live),4)},
 "both_hosts_serve_200":{"domains":len(C),"share":round(len(C)/len(live),4),
   "canonical":dict(collections.Counter(c['status'] for c in C))},
 "loops":sum(1 for r in R for v in V if r['variants'][v]['end']=='loop'),
}
json.dump(S,open('summary.json','w'),indent=1)
print(json.dumps(S,indent=1))
