#!/usr/bin/env python3
"""Count principal evidence URLs and technical hosts in one frozen dataset.
Usage: python3 source_inventory.py SNAPSHOT.json OUTPUT_DIRECTORY
No network access. Hosts are not publishers or independent investigations.
"""
import csv, hashlib, json, sys
from collections import defaultdict
from pathlib import Path
from urllib.parse import urlsplit, urldefrag
from xml.sax.saxutils import escape

def generate(source, destination):
    raw=Path(source).read_bytes()
    data=json.loads(raw)
    records=data['records']
    ids=[r['id'] for r in records]
    if len(ids)!=len(set(ids)):
        raise ValueError('Duplicate record ID')
    hosts=defaultdict(list)
    urls=defaultdict(list)
    documents=defaultdict(list)
    rows=[]
    for r in sorted(records,key=lambda r:r['id']):
        url=r['primary_source_url']
        parsed=urlsplit(url)
        if parsed.scheme not in ('http','https') or not parsed.hostname or parsed.username or parsed.password:
            raise ValueError('Expected public HTTP(S) principal evidence URL')
        host=parsed.hostname.lower()
        hosts[host].append(r['id'])
        urls[url].append(r['id'])
        documents[urldefrag(url)[0]].append(r['id'])
        rows.append({'id':r['id'],'host':host,'primary_source_url':url,
                     'evidence_label':r.get('evidence_status',r.get('ai_involvement','')),
                     'record_type':r.get('record_type',''),
                     'source_scope':r['source_scope'],'response_url':r.get('response_url','')})
    ranked=sorted(hosts,key=lambda h:(-len(hosts[h]),h))
    repeated=[{'url':url,'record_count':len(ids),'ids':ids} for url,ids in sorted(documents.items()) if len(ids)>1]
    summary={'dataset':data['title'],'version':data['version'],'released':data['released'],
             'input_sha256':hashlib.sha256(raw).hexdigest(),'record_count':len(records),
             'unique_principal_urls':len(urls),'unique_hosts':len(hosts),'unique_document_urls':len(documents),
             'repeated_url_groups':len(repeated),'records_in_repeated_url_groups':sum(x['record_count'] for x in repeated),
             'method':'One primary_source_url per record. Exact strings counted separately; repeated-document groups remove only fragments and retain queries. Hostname lowercased; www and subdomains retained. Response URLs and URLs embedded in prose excluded.',
             'limits':'Technical URL inventory only. Not a count of publishers, independent investigations, verified facts, unique incidents or population failures. Different URLs may share evidence; one URL can support distinct failures. No network or source re-review performed.'}
    out=Path(destination);out.mkdir(parents=True,exist_ok=True)
    for name,obj in [('summary.json',summary),('repeated-source-urls.json',repeated)]:
        (out/name).write_text(json.dumps(obj,ensure_ascii=False,indent=2)+'\n')
    for name,content,fields in [('records.csv',rows,['id','host','primary_source_url','evidence_label','record_type','source_scope','response_url']),
                                ('hosts.csv',[{'host':h,'record_count':len(hosts[h]),'ids':' | '.join(hosts[h])} for h in ranked],['host','record_count','ids'])]:
        with (out/name).open('w',newline='') as f:
            w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(content)
    top=ranked[:5]; maximum=max([len(hosts[h]) for h in top],default=1)
    svg=['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 900 350" role="img" aria-labelledby="title desc">',
         '<title id="title">Most common principal evidence hosts</title>',
         '<desc id="desc">Technical host counts in '+escape(data['title'])+' v'+escape(data['version'])+'. Hosts do not measure independent corroboration.</desc>',
         '<rect width="900" height="350" fill="#faf8f2"/>',
         '<g font-family="sans-serif" fill="#172a31"><text x="24" y="35" font-size="22">Principal evidence hosts: top five</text>',
         '<text x="24" y="62" font-size="16">'+str(len(records))+' selected records · version '+escape(data['version'])+'</text>']
    for i,h in enumerate(top):
        y=97+i*39
        svg += ['<text x="24" y="'+str(y+17)+'" font-size="15">'+escape(h)+'</text>',
                '<rect x="350" y="'+str(y)+'" width="'+str(round(410*len(hosts[h])/maximum))+'" height="24" fill="#216478"/>',
                '<text x="780" y="'+str(y+17)+'" font-size="16">'+str(len(hosts[h]))+'</text>']
    svg+=['<text x="24" y="313" font-size="15">Hosts are not independent sources; selected collection, not prevalence.</text>',
          '<text x="24" y="338" font-size="14">Source: '+escape(data['creator'])+' · '+escape(data['url'])+' · CC BY 4.0</text></g></svg>']
    (out/'hosts.svg').write_text('\n'.join(svg)+'\n')
    return summary

if __name__=='__main__':
    print(json.dumps(generate(sys.argv[1],sys.argv[2]),indent=2))
