"""Reproduce the October 17 subset comparison. Python 3.9+; no network.
CC BY 4.0. Credit Hallucination-Free / Deterministic AI; identify changes.
Usage: python3 cross_tab.py tracker|register SNAPSHOT NEW_OUTPUT_DIRECTORY
"""
import csv,hashlib,io,json,sys
from pathlib import Path
from collections import Counter
kind,source,out=sys.argv[1:];source=Path(source);out=Path(out)
expected={'tracker':'9e6881b9d74f44c7a1c9ee0b976200e4555c9e65e9999159212e80b1003acdb8','register':'1cd10bf6caf2e253bdaccd41818dfdec2f8ab27b15cb76a7aac3a88ea31d8d61'}[kind]
raw=source.read_bytes()
if hashlib.sha256(raw).hexdigest()!=expected: raise ValueError('Snapshot differs from pinned release')
d=json.loads(raw);r=d['records'];rows=[]
if kind=='tracker':
 types=['documented incident','controlled study','evaluation with external action','first-person report','reported allegation']
 counts=Counter((x['record_type'],x['ai_involvement']) for x in r)
 for t in types:
  row={'record_type':t,**{s:counts[t,s] for s in ['confirmed','admitted','suspected']}};row['total']=sum(row[s] for s in ['confirmed','admitted','suspected']);rows.append(row)
else:
 for c in ['bias','deception','harmful conduct']:
  subset=[x for x in r if x['category']==c]
  rows.append({'category':c,'all_records':len(subset),'non_study':sum(x['evidence_status']!='study' for x in subset),'finding':sum(x['evidence_status']=='finding' for x in subset)})
rows.append({list(rows[0])[0]:'total',**{k:sum(x[k] for x in rows) for k in list(rows[0])[1:]}})
buf=io.StringIO(newline='');w=csv.DictWriter(buf,fieldnames=list(rows[0]),lineterminator='\n');w.writeheader();w.writerows(rows)
out.mkdir(parents=True,exist_ok=False);(out/'record-types.csv').write_bytes(buf.getvalue().encode())
(out/'table.json').write_text(json.dumps({'source_version':d['version'],'source_released':d['released'],'source_sha256':expected,'denominator':len(r),'unit':'selected record, not a model trial','rows':rows},ensure_ascii=False,indent=2)+'\n')
print(json.dumps(rows))
