"""Count URL groups by source role. Offline standard-library metadata analysis."""
from pathlib import Path
from collections import defaultdict
import json,csv,hashlib,sys
HASHES={'hallucination-tracker-v2.42.json': '26e0498c447ef2514bbc4d6b4b64455d71c34890ed3ecb4b5cbbf4c21934425d', 'ai-reliability-incidents-v1.37.json': '9d9e024a66c6a58f259e4c47012925dcf27ddc4c1aca4dff3035f20f7ab5847e'}

def calculate(inputs,fields):
    records={};groups=defaultdict(lambda:defaultdict(set))
    for label,data in zip(['Tracker','Register'],inputs):
        for row in data['records']:
            key=(label,row['id'])
            if key in records:raise ValueError('Duplicate dataset/record ID')
            records[key]=row
            for field in fields:
                url=row.get(field,'')
                if url:groups[url.partition('#')[0]][key].add(field)
    shared={u:members for u,members in groups.items() if len(members)>1}
    distinct=set().union(*(set(m) for m in shared.values())) if shared else set()
    memberships=sum(len(m) for m in shared.values())
    summary=dict(fields=list(fields),records=len(records),document_url_strings=len(groups),shared_url_groups=len(shared),group_memberships=memberships,distinct_records_in_shared_groups=len(distinct),repeated_memberships=memberships-len(distinct))
    members=[dict(document_url=u,members=[dict(dataset=k[0],source_roles=sorted(roles),record=records[k]) for k,roles in sorted(m.items())]) for u,m in sorted(shared.items())]
    return summary,members

def main():
    if len(sys.argv)!=2:raise SystemExit('Usage: python3 source_roles.py NEW_OUTPUT_DIRECTORY')
    base=Path(__file__).resolve().parent;loaded=[]
    for name,expected in HASHES.items():
        raw=(base/name).read_bytes()
        if hashlib.sha256(raw).hexdigest()!=expected:raise ValueError('Input hash mismatch: '+name)
        loaded.append(json.loads(raw))
    summaries=[];members={}
    for key,fields in [('principal_only',('primary_source_url',)),('principal_and_response',('primary_source_url','response_url'))]:
        s,m=calculate(loaded,fields);summaries.append(dict(selection=key,**s));members[key]=m
    dest=Path(sys.argv[1]);dest.mkdir(parents=True,exist_ok=False)
    report=dict(calculated='2026-11-12',inputs=[dict(file=n,version=d['version'],released=d['released'],records=len(d['records'])) for n,d in zip(HASHES,loaded)],normalization='Remove URL fragment only; ignore empty fields; deduplicate record within each URL group',scope='Curated metadata only. URL groups do not establish independent events, investigations, corroboration or source truth.',selections=summaries)
    (dest/'summary.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
    (dest/'members.json').write_text(json.dumps(members,ensure_ascii=False,indent=2)+'\n')
    with (dest/'counts.csv').open('w',newline='') as f:
        rows=[{k:(', '.join(v) if k=='fields' else v) for k,v in s.items()} for s in summaries];w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
    a,b=summaries
    svg=f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 345"><title>Source roles change group counts, not distinct records in this snapshot</title><desc>Principal only: {a['shared_url_groups']} shared groups and {a['distinct_records_in_shared_groups']} distinct records. Including responses: {b['shared_url_groups']} groups and {b['distinct_records_in_shared_groups']} distinct records. {b['group_memberships']} memberships include {b['repeated_memberships']} repeats.</desc><rect width="400" height="345" fill="#faf5ed"/><g font-family="sans-serif" fill="#242424"><text x="16" y="30" font-size="18">Count each record once</text><text x="16" y="54" font-size="13">263 selected records · November 11 releases</text><text x="16" y="88" font-size="16">Principal URLs: {a['shared_url_groups']} shared groups</text><rect x="16" y="101" width="{a['distinct_records_in_shared_groups']*17}" height="24" fill="#174f63"/><text x="16" y="148" font-size="16">{a['distinct_records_in_shared_groups']} distinct records</text><text x="16" y="184" font-size="16">Principal + response: {b['shared_url_groups']} shared groups</text><rect x="16" y="197" width="{b['distinct_records_in_shared_groups']*17}" height="24" fill="#ab3f2b"/><text x="16" y="244" font-size="16">{b['distinct_records_in_shared_groups']} distinct records; {b['group_memberships']} memberships</text><text x="16" y="280" font-size="13">A shared URL does not establish a shared event.</text><text x="16" y="304" font-size="12">Calculated November 12, 2026 · CC BY 4.0</text><text x="16" y="327" font-size="11">hallucination-free.org · deterministicai.org</text></g></svg>'
    (dest/'counts.svg').write_text(svg+'\n')
if __name__=='__main__':main()
