"""Group principal document URLs, not independent incidents. Python standard library."""
import sys,json,csv,hashlib
from pathlib import Path
from collections import defaultdict,Counter
from html import escape
EXPECTED = ['e8b6fc1db6e2a4ead2db81cb8d50dea993b66ea3aaf8df1639aec789c5e1a62a', 'd4b77efcd60cd5c57935333406e4516e00390195c99eeeef9ede886d7f9072d9']
def calculate(paths):
    groups=defaultdict(list)
    totals={}
    for label,path,expected in zip(['Tracker','Register'],paths,EXPECTED):
        raw=path.read_bytes()
        if hashlib.sha256(raw).hexdigest()!=expected:raise ValueError('Input bytes differ from the cited release')
        data=json.loads(raw);totals[label]={'version':data['version'],'records':len(data['records'])}
        for row in data['records']:
            url=row['primary_source_url'].split('#',1)[0]
            if not url:raise ValueError('Missing principal URL')
            groups[url].append({'dataset':label,'record':row})
    members=[{'document_url':url,'members':rows} for url,rows in sorted(groups.items()) if len(rows)>1]
    n=sum(x['records'] for x in totals.values());shared=sum(len(g['members']) for g in members)
    summary={'date':'2026-11-10','datasets':totals,'records':n,'document_urls':len(groups),'shared_document_groups':len(members),'records_in_shared_groups':shared,'records_at_singleton_urls':n-shared,'normalization':'Remove fragment only; preserve query strings, case, www, scheme and all other characters','unit':'Stored principal document URL; not independent studies, unique events or prevalence','omissions':'Response URLs, prose links, redirects, mirrors and syndication are not resolved'}
    return summary,members
def main():
    if len(sys.argv)!=4:raise SystemExit('Usage: python3 group_sources.py TRACKER.json REGISTER.json NEW_OUTPUT_DIRECTORY')
    paths=list(map(Path,sys.argv[1:3]));dest=Path(sys.argv[3]);summary,members=calculate(paths)
    if dest.exists():raise ValueError('Output directory already exists')
    dest.mkdir(parents=True)
    for name,value in [('summary.json',summary),('members.json',members)]:
        (dest/name).write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n')
    with (dest/'groups.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=['document_url','record_count','tracker_records','register_records','ids']);w.writeheader()
        for g in members:
            c=Counter(r['dataset'] for r in g['members'])
            w.writerow(dict(document_url=g['document_url'],record_count=len(g['members']),tracker_records=c['Tracker'],register_records=c['Register'],ids='; '.join(r['record']['id'] for r in g['members'])))
    pairs=[('At a singleton URL',summary['records_at_singleton_urls']),('At a shared URL',summary['records_in_shared_groups'])]
    svg=['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"><title>Records grouped by principal document URL</title><desc>Counts describe stored links, not independent investigations.</desc><rect width="400" height="300" fill="#faf5ed"/><g font-family="sans-serif" fill="#242424"><text x="16" y="28" font-size="19">Principal source URL grouping</text><text x="16" y="52" font-size="14">261 selected records · November 10, 2026</text>']
    for i,(label,n) in enumerate(pairs):
        y=82+i*70;svg.append(f'<text x="16" y="{y}" font-size="16">{escape(label)}</text><rect x="16" y="{y+12}" width="{310*n/summary["records"]:.1f}" height="24" fill="#174f63"/><text x="344" y="{y+31}" font-size="17">{n}</text>')
    svg+=['<text x="16" y="238" font-size="13">Source: hallucination-free.org / deterministicai.org</text><text x="16" y="262" font-size="13">Original analysis · CC BY 4.0</text><text x="16" y="286" font-size="13">URL uniqueness does not prove independence.</text></g></svg>']
    (dest/'source-groups.svg').write_text(''.join(svg)+'\n')
if __name__=='__main__':main()
