"""Inventory stored response pointers; does not read sources or verify fixes. Python 3, standard library."""
from pathlib import Path
from collections import Counter
from html import escape
import sys, json, csv, io, hashlib
INPUT = Path(__file__).with_name("hallucination-tracker-v2.29.json")
EXPECTED = "bab340da78ce986c472f3739594cdd02ac7f673b49cdb65aab2580287b3c2a09"
def main():
    out=Path(sys.argv[1])
    raw=INPUT.read_bytes()
    if hashlib.sha256(raw).hexdigest()!=EXPECTED:
        raise SystemExit("Input differs from frozen release")
    data=json.loads(raw); records=data['records']
    ids=[r['id'] for r in records]
    if len(ids)!=len(set(ids)): raise SystemExit("Duplicate IDs")
    inventory=[]
    for r in sorted(records,key=lambda r:r['id']):
        response=r['response_url'].strip(); primary=r['primary_source_url'].strip()
        bucket='missing' if not response else ('same as primary' if response==primary else 'different from primary')
        inventory.append({'id':r['id'],'evidence_label':r.get('evidence_status',r.get('ai_involvement')),'record_type':r.get('record_type',''),'response_pointer':bucket,'response_url':r['response_url'],'primary_source_url':r['primary_source_url'],'response_status':r['response_status'],'response':r['response'],'source_scope':r['source_scope'],'reviewed_at':r['reviewed_at']})
    counts={k:sum(r['response_pointer']==k for r in inventory) for k in ['same as primary','different from primary','missing']}
    summary={'dataset':data['title'],'version':data['version'],'released':data['released'],'analysis_date':'2026-10-25','input_sha256':EXPECTED,'records':len(records),'response_url_present':len(records)-counts['missing'],'counts':counts,'rule':'Trim stored URL strings; compare exact strings. No network lookup or URL normalization.','limitations':'Pointers do not establish a provider statement, correction, independent corroboration or source truth. Missing pointers do not establish silence. Curated collection; not a population rate.'}
    assert sum(counts.values())==len(records)
    out.mkdir(parents=True,exist_ok=False)
    (out/'summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2)+'\n')
    b=io.StringIO(newline=''); w=csv.DictWriter(b,fieldnames=list(inventory[0]));w.writeheader();w.writerows(inventory)
    (out/'response-inventory.csv').write_text(b.getvalue(),newline='')
    svg=['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 360">','<title>Response URL fields in frozen Tracker v2.29</title>','<desc>Exact stored URL comparison. Metadata counts, not verified corrections.</desc>','<rect width="400" height="360" fill="#faf5ed"/>','<g font-family="sans-serif" fill="#242424">','<text x="16" y="28" font-size="18">Tracker v2.29: '+str(len(records))+' records</text>']
    for i,(label,n) in enumerate(counts.items()):
        y=65+i*76;svg += [f'<text x="16" y="{y}" font-size="16">{escape(label)}: {n}</text>',f'<rect x="16" y="{y+10}" width="{330*n/len(records):.1f}" height="24" fill="#174f63"/>']
    svg += ['<text x="16" y="300" font-size="14">Metadata counts, not verified fixes.</text>','<text x="16" y="323" font-size="13">hallucination-free.org · CC BY 4.0</text>','<text x="16" y="344" font-size="13">Analysis: October 25, 2026</text></g></svg>']
    (out/'chart.svg').write_text(''.join(svg)+'\n')
if __name__=='__main__':main()
