"""Frozen date-precision audit 1.1 (November 21, 2026). Python 3.9+, standard library, no network.
Original calculation: Hallucination-Free / Deterministic AI, CC BY 4.0.
This validates date syntax and counts records; it does not verify event dates.
"""
from pathlib import Path
from collections import Counter
from datetime import date
from html import escape
import argparse, csv, hashlib, io, json, re
PINS = {'tracker': {'sha256': 'e4c0f97256c80dcd251a646507cf16ae3ce289b7381b0e97475949efaae2e23c', 'url': 'https://www.hallucination-free.org/data/hallucination-tracker-v2.48.json', 'version': '2.48', 'credit': 'Hallucination-Free', 'domain': 'hallucination-free.org'}, 'register': {'sha256': '33d37b58e871a1279247a5a485f3e29c204005c25b5ead22f286b2195d40212f', 'url': 'https://www.deterministicai.org/data/ai-reliability-incidents-v1.43.json', 'version': '1.43', 'credit': 'Deterministic AI', 'domain': 'deterministicai.org'}}

def validate_records(records):
    if len({r['id'] for r in records})!=len(records):
        raise ValueError('Duplicate stable ID')
    counts=Counter(); rows=[]
    patterns={'day':r'[0-9]{4}-[0-9]{2}-[0-9]{2}','month':r'[0-9]{4}-[0-9]{2}','year':r'[0-9]{4}'}
    for r in records:
        value=r['event_date']; precision=r['date_precision']
        if precision not in patterns or not re.fullmatch(patterns[precision],value):
            raise ValueError('Date label and format differ: '+r['id'])
        # Validate the existing calendar components without changing the value.
        components=list(map(int,value.split('-')))
        date(*(components+[1]*(3-len(components))))
        if not r['date_basis'].strip(): raise ValueError('Missing date basis: '+r['id'])
        counts[precision]+=1
        rows.append({k:r[k] for k in ['id','event_date','date_precision','date_basis','primary_source_url']})
    return counts, rows

def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('collection', choices=sorted(PINS))
    p.add_argument('input',type=Path)
    p.add_argument('output',type=Path)
    a=p.parse_args(); pin=PINS[a.collection]
    raw=a.input.read_bytes()
    if hashlib.sha256(raw).hexdigest()!=pin['sha256']:
        raise ValueError('Input bytes differ from the frozen release')
    d=json.loads(raw); records=sorted(d['records'],key=lambda r:r['id'])
    counts, rows = validate_records(records)
    n=len(records)
    summary={'collection':a.collection,'version':pin['version'],'input_url':pin['url'],'input_sha256':pin['sha256'],'denominator':n,'unit':'published record, not necessarily a unique event','counts':{k:counts[k] for k in ['day','month','year']},'limits':'Stored precision is not date truth. A date may mark a disclosure or decision. Historical duplicates and other qualifications remain in the frozen input. No prevalence or time trend is estimated.'}
    outputs={'summary.json':json.dumps(summary,ensure_ascii=False,indent=2)+'\n'}
    for name,data,fields in [('dates.csv',rows,list(rows[0])),('counts.csv',[{'precision':k,'records':counts[k],'denominator':n,'percent':f'{100*counts[k]/n:.2f}'} for k in ['day','month','year']],['precision','records','denominator','percent'])]:
        s=io.StringIO(newline='');w=csv.DictWriter(s,fieldnames=fields);w.writeheader();w.writerows(data);outputs[name]=s.getvalue()
    parts=['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 360">','<title>Stored date precision in '+escape(a.collection)+' v'+pin['version']+'</title>','<desc>Selected record counts by stored date precision. Not a daily event count or failure rate.</desc>','<rect width="440" height="360" fill="#faf5ed"/>','<g font-family="sans-serif" fill="#242424">',f'<text x="16" y="30" font-size="19">Date precision: {n} frozen records</text>']
    for i,k in enumerate(['day','month','year']):
        y=65+i*70
        parts += [f'<text x="16" y="{y}" font-size="16">{k.title()}: {counts[k]}</text>',f'<rect x="16" y="{y+10}" width="{360*counts[k]/n:.2f}" height="23" fill="#174f63"/>']
    parts += [f'<text x="16" y="285" font-size="14">{escape(pin["credit"])} · v{pin["version"]} · CC BY 4.0</text>','<text x="16" y="310" font-size="14">Calculated November 21, 2026</text>','<text x="16" y="335" font-size="14">Precision does not establish the event date.</text>','</g></svg>']
    outputs['chart.svg']=''.join(parts)+'\n'
    a.output.mkdir(parents=True,exist_ok=False)
    for name,value in outputs.items(): (a.output/name).write_bytes(value.encode('utf-8'))

if __name__=='__main__': main()
