#!/usr/bin/env python3
"""Inventory explicit companion IDs. Python standard library only. CC BY 4.0.
Run: python3 reproduce.py --output /path/to/new-directory
No network access. Relationship labels are editorial inputs, not inferred duplicates.
"""
from pathlib import Path
import argparse, csv, hashlib, json, re
HASHES = {'hallucination-tracker-v2.36.json': 'ed744ef65c6d96c7b1775740c3e60f9bc71f897264e04d3179d724a2e5c9e782', 'ai-reliability-incidents-v1.27.json': '1b6eb9c5609d4c7b8f25a7b3a9cdd02cc4752621d473334a56ff8c65252dd786', 'relations.json': 'fbb226614d690aa641c65a28ed8dc3b8e9821deee1d2e48a7dbd2ec181bb4387'}

def analyze(h, d, relations):
    groups=[h['records'], d['records']]
    records={r['id'].lower():r for group in groups for r in group}
    if len(records)!=sum(map(len,groups)): raise ValueError('duplicate record ID')
    edges=[]
    for group in groups:
        for record in group:
            targets={}
            for field,value in record.items():
                if not isinstance(value,str): continue
                for target in re.findall(r'(?<![a-z0-9-])(?:hf|da)-[0-9][a-z0-9-]*',value.lower()):
                    if target[:2]==record['id'][:2].lower(): continue
                    if target not in records: raise ValueError('missing companion target: '+target)
                    targets.setdefault(target,set()).add(field)
            for target,fields in sorted(targets.items()):
                edges.append({'from_id':record['id'],'to_id':records[target]['id'],'referring_fields':'; '.join(sorted(fields))})
    edges.sort(key=lambda e:(e['from_id'],e['to_id']))
    pairs={tuple(sorted((e['from_id'],e['to_id']))) for e in edges}
    expected={tuple(sorted((r['tracker_id'],r['register_id']))) for r in relations}
    if len(expected)!=len(relations) or expected!=pairs: raise ValueError('relation labels do not match discovered pairs')
    members=sorted({i for pair in pairs for i in pair})
    summary={'analysis_date':'2026-11-03','tracker_version':h['version'],'tracker_records':len(groups[0]),'register_version':d['version'],'register_records':len(groups[1]),'directed_references':len(edges),'distinct_pairs':len(pairs),'referenced_records':len(members),'input_sha256':HASHES,'scope':'Explicit companion IDs in record string fields only; repeated mentions collapsed per direction. Not exhaustive episode matching, a deduplicated event total, independent source count or prevalence estimate.'}
    return edges,[dict(r,tracker_record=records[r['tracker_id'].lower()],register_record=records[r['register_id'].lower()]) for r in relations],summary

def main():
    parser=argparse.ArgumentParser();parser.add_argument('--output',type=Path,required=True);args=parser.parse_args()
    base=Path(__file__).resolve().parent;loaded={}
    for name,digest in HASHES.items():
        raw=(base/name).read_bytes()
        if hashlib.sha256(raw).hexdigest()!=digest: raise SystemExit('Input hash mismatch: '+name)
        loaded[name]=json.loads(raw)
    edges,pairs,summary=analyze(loaded['hallucination-tracker-v2.36.json'],loaded['ai-reliability-incidents-v1.27.json'],loaded['relations.json'])
    args.output.mkdir(parents=True,exist_ok=False)
    for name,data in [('references.json',edges),('pairs-with-records.json',pairs),('summary.json',summary)]:
        (args.output/name).write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
    with (args.output/'references.csv').open('w',newline='') as f:
        writer=csv.DictWriter(f,fieldnames=['from_id','to_id','referring_fields']);writer.writeheader();writer.writerows(edges)
    with (args.output/'pairs.csv').open('w',newline='') as f:
        writer=csv.DictWriter(f,fieldnames=['tracker_id','register_id','relationship','basis']);writer.writeheader();writer.writerows(loaded['relations.json'])
    from collections import Counter
    from html import escape
    counts=Counter(r['relationship'] for r in loaded['relations.json'])
    parts=['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 560 420"><title>Six explicitly linked record pairs</title><desc>Two shared episodes, two distinct study findings, one distinct-task pair and one overlapping training pair. Not an independent incident total.</desc><rect width="560" height="420" fill="#faf5ed"/><g font-family="sans-serif" fill="#242424"><text x="20" y="32" font-size="22">How six record pairs are related</text>']
    labels={'same episode, different failure descriptions':'Same episode, different failures','distinct study findings in one disclosure':'Distinct findings in one study','distinct tasks in one disclosure':'Distinct tasks in one disclosure','overlapping training activity':'Overlapping training activity'}
    for i,(label,n) in enumerate(counts.items()):
        y=72+i*68
        parts += [f'<text x="20" y="{y}" font-size="18">{escape(labels[label])}</text><rect x="20" y="{y+10}" width="{n*200}" height="22" fill="#174f63"/><text x="{30+n*200}" y="{y+28}" font-size="18">{n}</text>']
    parts += ['<text x="20" y="355" font-size="15">Tracker v2.36 / Register v1.27 · November 3, 2026</text><text x="20" y="378" font-size="14">hallucination-free.org · deterministicai.org · CC BY 4.0</text><text x="20" y="402" font-size="15">Curated references; not exhaustive event matching.</text></g></svg>']
    (args.output/'chart.svg').write_text(''.join(parts)+'\n')
    print(json.dumps(summary,indent=2))
if __name__=='__main__': main()
