#!/usr/bin/env python3
"""Reproduce a frozen sector/evidence inventory. Standard library; no network."""
from pathlib import Path
from collections import Counter
import csv, hashlib, html, json, sys
CONFIG = {'input': 'hallucination-tracker-v2.31.json', 'sha256': '049f2dd5c00da66f66611edd079da6baeaee7483686500e27726f6e812157c3f', 'version': '2.31', 'records': 123, 'field': 'ai_involvement', 'labels': ['confirmed', 'admitted', 'suspected'], 'title': 'The Hallucination Tracker', 'credit': 'hallucination-free.org', 'record_base': 'https://www.hallucination-free.org/tracker/'}
base = Path(__file__).resolve().parent
raw = (base / CONFIG['input']).read_bytes()
if hashlib.sha256(raw).hexdigest() != CONFIG['sha256']:
    raise SystemExit('Input hash mismatch; no output written')
data = json.loads(raw)
records = data['records']
ids = [r['id'] for r in records]
if len(ids) != len(set(ids)) or len(records) != CONFIG['records']:
    raise SystemExit('Invalid record membership')
sectors = ['consumer','finance','government','health','legal','other']
labels = CONFIG['labels']
field = CONFIG['field']
if any(r['sector'] not in sectors or r[field] not in labels for r in records):
    raise SystemExit('Unexpected sector or evidence label')
counts = Counter((r['sector'], r[field]) for r in records)
rows = [dict(sector=s, **{label:counts[s,label] for label in labels}, total=sum(counts[s,label] for label in labels)) for s in sectors]
out = Path(sys.argv[1]) if len(sys.argv)==2 else None
if out is None: raise SystemExit('Usage: python3 reproduce.py NEW_OUTPUT_DIRECTORY')
out.mkdir(parents=True, exist_ok=False)
with (out/'counts.csv').open('w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=['sector']+labels+['total']);w.writeheader();w.writerows(rows)
with (out/'members.csv').open('w',newline='') as f:
    w=csv.DictWriter(f,fieldnames=list(records[0])+['record_url']);w.writeheader()
    for r in sorted(records,key=lambda r:(r['sector'],r[field],r['id'])):
        w.writerow(dict(r,record_url=CONFIG['record_base']+'#'+r['id'].lower()))
summary = dict(CONFIG, analysis_date='2026-10-27', sectors=rows, unit='One published record; one stored sector per record', limitations='Curated collection, not representative. Evidence labels differ across datasets. Zero means no included record, not no failures. Shared sources and incidents can cross collections. No source reopening or model testing performed.')
(out/'summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2)+'\n')
colors=['#234a62','#aa593d','#7c7547','#716581']
parts=['<svg xmlns="http://www.w3.org/2000/svg" width="820" height="480" viewBox="0 0 820 480" role="img" aria-labelledby="title desc">', '<title id="title">Records by sector and evidence label</title>', '<desc id="desc">'+html.escape('; '.join(s['sector']+': '+', '.join(k+' '+str(s[k]) for k in labels) for s in rows))+'</desc>', '<rect width="820" height="480" fill="#faf8f2"/>', '<g font-family="sans-serif" fill="#1c2d38">', '<text x="24" y="35" font-size="22">Records by sector and evidence label</text>', '<text x="24" y="60" font-size="15">'+html.escape(CONFIG['title']+' v'+CONFIG['version']+'; '+str(len(records))+' curated records')+'</text>']
scale=560/max(r['total'] for r in rows)
for i,r in enumerate(rows):
    y=95+i*43;parts.append(f'<text x="24" y="{y+20}" font-size="16">{r["sector"]}</text>');x=155
    for j,label in enumerate(labels):
        n=r[label];width=n*scale
        if n:parts.append(f'<rect x="{x:.3f}" y="{y}" width="{width:.3f}" height="28" fill="{colors[j]}"/>')
        x+=width
    parts.append(f'<text x="{x+8:.3f}" y="{y+20}" font-size="16">{r["total"]}</text>')
for j,label in enumerate(labels):
    x=24+j*185;parts.append(f'<rect x="{x}" y="370" width="14" height="14" fill="{colors[j]}"/><text x="{x+20}" y="382" font-size="15">{label}</text>')
parts+=['<text x="24" y="420" font-size="14">Collection composition only; no sector risk or failure-rate comparison.</text>', '<text x="24" y="447" font-size="14">'+html.escape(CONFIG['credit']+' · October 27, 2026 · CC BY 4.0')+'</text>','</g></svg>']
(out/'chart.svg').write_text('\n'.join(parts)+'\n')
print(json.dumps({'records':len(records),'cells':len(sectors)*len(labels),'output':str(out)}))
