#!/usr/bin/env python3
"""Recompute KACI companion metrics from public Wave One records; no API calls.
Requires Python3 and numpy. Run from this file's folder or elsewhere.
PNG rendering: render-png.cjs with bundled sharp. Original release remains immutable.
"""
from pathlib import Path
from collections import Counter,defaultdict
import json,csv,hashlib,itertools,html
import numpy as np
B=Path(__file__).resolve().parent; OUT=B/'assets';OUT.mkdir(exist_ok=True)
d=json.loads((B/'source/dataset.json').read_text()); s=json.loads((B/'source/stats.json').read_text())
E=['openai','anthropic','google'];LABEL={'openai':'OpenAI','anthropic':'Claude','google':'Gemini'};COL={'openai':'#176b91','anthropic':'#b15439','google':'#7163ae'}
runs=d['runs'];cs=d['citations'];byid={r['run_id']:r for r in runs};slot={(r['engine'],r['query_id'],r['run_index']):r['run_id'] for r in runs}
assert len(runs)==len(byid)==len(slot)==7200
assert all(r['status']=='complete' and not r['synthetic'] and r['wave']=='collection' and r['parser_ok'] for r in runs)
assert len({c['citation_id'] for c in cs})==len(cs)==45799
assert all(c['run_id'] in byid for c in cs)
sets=defaultdict(set);occ=Counter();dom=defaultdict(Counter);presence=defaultdict(set)
for c in cs:
 r=byid[c['run_id']];assert all(c[k]==r[k] for k in ['engine','query_id','run_index','stratum'])
 sets[c['run_id']].add(c['domain']);occ[c['engine']]+=1;dom[c['engine']][c['domain']]+=1;presence[(c['engine'],c['domain'])].add(c['run_id'])
qids=sorted({r['query_id'] for r in runs});assert len(qids)==1200
strata={x:[i for i,q in enumerate(qids) if q.startswith(x+'-')] for x in ['S1','S2','S3','S4']};assert [len(x) for x in strata.values()]==[500,300,200,200]
# Common resamples retain matched engines and both observations of each question.
rng=np.random.default_rng(20261003); idx=np.concatenate([np.array(v)[rng.integers(0,len(v),size=(10000,len(v)),dtype=np.int32)] for v in strata.values()],axis=1)
def interval(num,den):
 a=np.asarray(num,float);b=np.asarray(den,float);numboot=a[idx].sum(axis=1);denboot=b[idx].sum(axis=1);boot=numboot[denboot>0]/denboot[denboot>0]
 return {'estimate':float(a.sum()/b.sum()),'lower_95':float(np.quantile(boot,.025)),'upper_95':float(np.quantile(boot,.975)),'eligible':int(b.sum())}
coverage=[];groups=[];overlap=[];stability=[]
for e in E:
 nums=[sum(bool(sets[slot[e,q,j]]) for j in [1,2]) for q in qids];a=interval(nums,[2]*1200);a.update(engine=e,completed=2400,citing=sum(nums),citation_occurrences=occ[e]);coverage.append(a)
 assert abs(a['estimate']-s['headline_metrics'][e]['citation_present_response_fraction']['estimate'])<1e-12
 for g,inds in strata.items():groups.append({'engine':e,'stratum':g,'citing':sum(nums[i] for i in inds),'completed':2*len(inds),'fraction':sum(nums[i] for i in inds)/(2*len(inds))})
 ns=[];ds=[]
 for q in qids:
  a,b=[sets[slot[e,q,j]] for j in [1,2]];ns.append(len(a&b)/len(a|b) if a|b else 0);ds.append(int(bool(a|b)))
 a=interval(ns,ds);a.update(engine=e,matched=1200);stability.append(a)
 ref=next(x for x in s['stability'] if x['engine']==e);assert abs(a['estimate']-ref['mean_domain_jaccard'])<1e-12;assert a['eligible']==ref['nonempty_domain_union_pairs']
for ea,eb in itertools.combinations(E,2):
 ns=[];ds=[]
 for q in qids:
  n=0;de=0
  for j in [1,2]:
   a,b=sets[slot[ea,q,j]],sets[slot[eb,q,j]]
   if a|b:n+=len(a&b)/len(a|b);de+=1
  ns.append(n);ds.append(de)
 a=interval(ns,ds);a.update(engine_a=ea,engine_b=eb,matched=2400);overlap.append(a)
 ref=next(x for x in s['overlap'] if x['engine_a']==ea and x['engine_b']==eb);assert abs(a['estimate']-ref['mean_domain_jaccard'])<1e-12;assert a['eligible']==ref['nonempty_domain_union_pairs']
classify={x['domain']:x for x in d['domain_classifications']};assert sum(bool(v['reviewed']) for v in classify.values())==100
cats=defaultdict(Counter)
for c in cs:
 cl=classify[c['domain']];cats[c['engine']][cl['category'] if cl['reviewed'] else 'unreviewed']+=1
catrows=[]
for e in E:
 rev=occ[e]-cats[e]['unreviewed'];assert rev==d['category_review']['provider_coverage'][e]['reviewed_citation_occurrences']
 for cat,n in cats[e].items():catrows.append({'engine':e,'source_type':cat,'occurrences':n,'all_occurrences':occ[e],'all_occurrence_share':n/occ[e],'reviewed_occurrences':rev,'within_reviewed_share':n/rev if cat!='unreviewed' else ''})
top=[]
for e in E:
 for rank,(domain,n) in enumerate(sorted(dom[e].items(),key=lambda x:(-x[1],x[0]))[:10],1):top.append({'engine':e,'rank':rank,'domain':domain,'citation_occurrences':n,'occurrence_share':n/occ[e],'answers_citing_domain':len(presence[e,domain]),'completed_answers':2400,'answer_presence_share':len(presence[e,domain])/2400})
# Match every published league row, not just headline ranks.
with (B/'source/league-tables.csv').open() as f:
 for r in csv.DictReader(f):
  if r['stratum']=='ALL':assert int(r['citation_occurrences'])==dom[r['engine']][r['domain']] and int(r['responses_citing_domain'])==len(presence[r['engine'],r['domain']])
def writecsv(name,rows):
 with (OUT/(name+'.csv')).open('w') as f:
  w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
for name,rows in [('citation-coverage',coverage),('question-group-coverage',groups),('provider-overlap',overlap),('two-run-stability',stability),('top-domains',[x for x in top if x['rank']<=5]),('reviewed-source-types',catrows)]:writecsv(name,rows)
metrics={'release':'v2026.10.05','companion':'2026.10.29.1','collection_date':'2026-10-04','models':{e:sorted({r['model_string'] for r in runs if r['engine']==e}) for e in E},'runs':7200,'citation_occurrences':45799,'unique_domains':len(classify),'reviewed_domains':100,'coverage':coverage,'groups':groups,'overlap':overlap,'stability':stability,'top_domains':top,'reviewed_source_types':catrows,'bootstrap':{'samples':10000,'seed':20261003,'unit':'question ID resampled within all four strata; preserve both runs and engines','interval':'percentile 95%; nonempty unions only for overlap','comparison_to_original':'Point estimates, eligible counts and 95% interval endpoints reproduced to floating-point precision (absolute difference below 1e-12).'}}
comparisons=[]
for name,computed in [('coverage',coverage),('overlap',overlap),('stability',stability)]:
 for a in computed:
  if name=='coverage':ref=s['headline_metrics'][a['engine']]['citation_present_response_fraction']
  elif name=='stability':ref=next(x['jaccard_interval'] for x in s['stability'] if x['engine']==a['engine'])
  else:ref=next(x['jaccard_interval'] for x in s['overlap'] if x['engine_a']==a['engine_a'] and x['engine_b']==a['engine_b'])
  errors={key:abs(a[key]-ref[key]) for key in ['estimate','lower_95','upper_95']};assert max(errors.values())<1e-12;comparisons.append({'metric':name,'engine':a.get('engine',a.get('engine_a')+'/'+a.get('engine_b') if 'engine_a' in a else ''),'absolute_errors':errors})
for a in groups:
 ref=next(x for x in s['strata'] if x['engine']==a['engine'] and x['stratum']==a['stratum']);assert a['citing']==ref['responses_with_citations'] and a['completed']==ref['completed_responses']
(B/'independent-comparison.json').write_text(json.dumps(comparisons,indent=2))
(B/'verified-metrics.json').write_text(json.dumps(metrics,indent=2))
(B/'source-checksums.json').write_text(json.dumps({p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in (B/'source').iterdir() if p.is_file()},indent=2))
# Simple deterministic vector bar charts; sharp rasterizes these unchanged SVGs.
def svg(name,title,subtitle,rows,xmax,xlabel,notes):
 W=1400;left=440;right=90;topmargin=175;rowheight=62;H=topmargin+len(rows)*rowheight+180;pw=W-left-right
 def text(x,y,t,size=22,fill='#162f40',anchor='start'):return f'<text x="{x}" y="{y}" font-size="{size}" fill="{fill}" text-anchor="{anchor}">{html.escape(str(t))}</text>'
 parts=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}" role="img" aria-label="{html.escape(title)}"><rect width="100%" height="100%" fill="#fff"/><g font-family="Arial,sans-serif">',text(45,55,title,33),text(45,98,subtitle,21)]
 for i in range(5):
  v=xmax*i/4;x=left+pw*i/4;parts.append(f'<line x1="{x}" y1="140" x2="{x}" y2="{topmargin+len(rows)*rowheight-18}" stroke="#d7e1e6"/>');parts.append(text(x,topmargin+len(rows)*rowheight+25,f'{v:g}',18,anchor='middle'))
 for i,(label,value,color,lo,hi,detail) in enumerate(rows):
  y=topmargin+i*rowheight;parts +=[text(left-20,y+11,label,22,anchor='end'),f'<rect x="{left}" y="{y-15}" width="{max(value/xmax*pw,.7)}" height="28" fill="{color}"/>']
  if lo is not None:
   a=left+lo/xmax*pw;b=left+hi/xmax*pw;parts.append(f'<path d="M {a},{y-20} v 38 M {b},{y-20} v 38 M {a},{y-1} H {b}" stroke="#172f40" stroke-width="2"/>')
  parts.append(text(left+pw+12,y+10,f'{value:.1f}' if xmax>1 else f'{value:.3f}',20));parts.append(text(left,y+35,detail,15,'#435765'))
 parts.append(text(left,topmargin+len(rows)*rowheight+63,xlabel,20))
 for j,n in enumerate(notes):parts.append(text(45,H-75+j*24,n,17,'#435765'))
 parts.append('</g></svg>');(OUT/(name+'.svg')).write_text(''.join(parts))
common=['KACI Wave One • collection 4 Oct 2026 • official APIs; designed English question panel.','Source: Kingy.ai • v2026.10.05 • DOI 10.5281/zenodo.23170591 • companion 2026.10.29.1']
svg('citation-coverage','How often did these API answers include citations?','Completed answers with native citations; 95% question-clustered bootstrap intervals.',[(LABEL[x['engine']],100*x['estimate'],COL[x['engine']],100*x['lower_95'],100*x['upper_95'],f"{x['citing']:,} / 2,400 completed answers") for x in coverage],100,'Percent of completed answers',common)
svg('provider-overlap','How much did different providers’ cited domains overlap?','Mean matched-answer Jaccard; 95% intervals; pairs with empty unions excluded.',[(LABEL[x['engine_a']]+' / '+LABEL[x['engine_b']],x['estimate'],'#176b91',x['lower_95'],x['upper_95'],f"{x['eligible']:,} eligible / 2,400 matched pairs") for x in overlap],.10,'Jaccard: intersection / union of cited-domain sets',common)
svg('two-run-stability','How consistent were sources across two identical questions?','Mean same-provider domain-set Jaccard across two runs; 95% intervals.',[(LABEL[x['engine']],x['estimate'],COL[x['engine']],x['lower_95'],x['upper_95'],f"{x['eligible']:,} eligible / 1,200 questions; empty unions excluded") for x in stability],1,'Jaccard overlap; this is not a source-retention rate',common)
svg('top-domains','Which domains led each provider’s occurrence ranking?','Exploratory top five per provider; duplicate native citation annotations retained.',[(LABEL[x['engine']]+': '+x['domain'],100*x['occurrence_share'],COL[x['engine']],None,None,f"{x['citation_occurrences']:,} occurrences; cited in {x['answers_citing_domain']} / 2,400 answers") for x in top if x['rank']<=5],10,'Percent of that provider’s citation occurrences',common)
svg('reviewed-source-types','How much of the citation evidence has reviewed source labels?','Selected top 100 domains by pooled frequency; review coverage differs by provider.',[(LABEL[e],100*(1-cats[e]['unreviewed']/occ[e]),COL[e],None,None,f"{occ[e]-cats[e]['unreviewed']:,} / {occ[e]:,} occurrences reviewed; remainder unreviewed") for e in E],100,'Percent of citation occurrences covered by reviewed domains',['Selected subset; source-type labels do not establish industry, quality or web-wide preference.',common[1]])
print(json.dumps({'passed':True,'runs':len(runs),'citations':len(cs),'groups':groups,'assets':[p.name for p in OUT.iterdir()]},indent=2))

# Source-type composition across all occurrences, keeping unreviewed mass explicit.
catnames=sorted(set(x['source_type'] for x in catrows if x['source_type']!='unreviewed'))+['unreviewed']
palette=['#216b91','#468c6c','#b87936','#7363a4','#bc526b','#6c8291','#9b7b5b','#6e7398','#a6bac4','#90555c','#305b3f','#d8dfe4']
parts=['<svg xmlns="http://www.w3.org/2000/svg" width="1400" height="790" viewBox="0 0 1400 790" role="img" aria-label="Source types within reviewed KACI evidence, with unreviewed share"><rect width="100%" height="100%" fill="white"/><g font-family="Arial,sans-serif" fill="#162f40">','<text x="45" y="55" font-size="33">Which source types appear in the reviewed evidence?</text>','<text x="45" y="100" font-size="21">All citation occurrences shown; reviewed categories retain their selected-subset scope.</text>']
for i,e in enumerate(E):
 y=160+i*120;parts.append(f'<text x="45" y="{y+32}" font-size="25">{LABEL[e]}</text>');left=250
 for j,cat in enumerate(catnames):
  share=cats[e][cat]/occ[e];w=share*1060;color='#d8dfe4' if cat=='unreviewed' else palette[j%len(palette)];parts.append(f'<rect x="{left}" y="{y}" width="{w}" height="48" fill="{color}"><title>{html.escape(cat)}: {share:.1%}</title></rect>');left+=w
 parts.append(f'<text x="250" y="{y+80}" font-size="20">{occ[e]:,} occurrences; {cats[e]["unreviewed"]/occ[e]:.1%} unreviewed</text>')
for j,cat in enumerate(catnames):
 x=45+(j%3)*450;y=560+(j//3)*40;color='#d8dfe4' if cat=='unreviewed' else palette[j%len(palette)];parts.append(f'<rect x="{x}" y="{y-17}" width="20" height="20" fill="{color}"/><text x="{x+30}" y="{y}" font-size="19">{html.escape(cat)}</text>')
parts += ['<text x="45" y="730" font-size="18">100 domains selected by pooled frequency; 4,531 remain unreviewed. Source type does not establish quality.</text>','<text x="45" y="760" font-size="17">KACI • 4 Oct 2026 collection • v2026.10.05 • DOI 10.5281/zenodo.23170591 • companion 2026.10.29.1</text>','</g></svg>']
(OUT/'reviewed-source-types.svg').write_text(''.join(parts))
