"""Count labels in a pinned curated collection; Python 3.9+, no network."""
import json,csv,hashlib,sys
from pathlib import Path
from collections import Counter
from html import escape
CONFIG = {'name': 'Tracker v2.36', 'input': 'hallucination-tracker-v2.36.json', 'sha256': 'ed744ef65c6d96c7b1775740c3e60f9bc71f897264e04d3179d724a2e5c9e782', 'dimensions': ['record_type', 'ai_involvement'], 'rows': ['controlled study', 'documented incident', 'evaluation with external action', 'first-person report', 'reported allegation'], 'columns': ['confirmed', 'admitted', 'suspected'], 'credit': 'hallucination-free.org/tracker/', 'color': '#ab3f2b'}
def analyze(data):
 records=data['records']; a,b=CONFIG['dimensions'];ids=[r['id'] for r in records]
 if not records or len(ids)!=len(set(ids)):raise ValueError('empty records or duplicate IDs')
 if any(r[a] not in CONFIG['rows'] or r[b] not in CONFIG['columns'] for r in records):raise ValueError('unknown label')
 counts=Counter((r[a],r[b]) for r in records)
 return [{'row':x,'column':y,'records':counts[x,y]} for x in CONFIG['rows'] for y in CONFIG['columns']]
def main():
 source=Path(__file__).with_name(CONFIG['input']); payload=source.read_bytes()
 if hashlib.sha256(payload).hexdigest()!=CONFIG['sha256']:raise ValueError('changed input')
 data=json.loads(payload);cells=analyze(data);out=Path(sys.argv[1]);out.mkdir(exist_ok=False)
 summary=dict(CONFIG,total_records=len(data['records']),cells=cells,scope='Selected records, not independent events, population prevalence or comparative vendor risk.')
 (out/'summary.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2)+'\n')
 (out/'members.json').write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
 for name,rows in [('cells.csv',cells),('members.csv',sorted(data['records'],key=lambda r:r['id']))]:
  with (out/name).open('w',newline='') as f:
   w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
 columns=CONFIG['columns']; totals={y:sum(c['records'] for c in cells if c['column']==y) for y in columns}
 height=155+65*len(columns)
 parts=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 {height}"><title>Evidence labels in {escape(CONFIG["name"])}</title><desc>Curated record counts; not event frequency or model risk.</desc><rect width="600" height="{height}" fill="#faf5ed"/><g font-family="sans-serif" fill="#242424">',f'<text x="24" y="32" font-size="22">{escape(CONFIG["name"])}: {len(data["records"])} records</text>','<text x="24" y="57" font-size="15">November 4, 2026 profile · selected records only</text>']
 for i,(label,n) in enumerate(totals.items()):
  y=90+i*65;parts +=[f'<text x="24" y="{y}" font-size="17">{escape(label)}: {n}</text>',f'<rect x="24" y="{y+9}" width="{500*n/max(totals.values()):.2f}" height="20" fill="{CONFIG["color"]}"/>']
 parts +=[f'<text x="24" y="{height-35}" font-size="14">{escape(CONFIG["credit"])} · CC BY 4.0</text>','</g></svg>']
 (out/'profile.svg').write_text(''.join(parts)+'\n')
if __name__=='__main__':main()
