"""Select dated milestones without inventing event days.
Python 3.9+; standard library; no network. Original calculation CC BY 4.0.
Usage: python3 date_window.py input.json NEW_OUTPUT_DIRECTORY
The inclusive window and frozen input hash are declared in PIN.
"""
from pathlib import Path
from datetime import date
from calendar import monthrange
from collections import Counter
from html import escape
import argparse, csv, hashlib, io, json, re
PIN = {'collection': 'Tracker', 'version': '2.31', 'url': 'https://www.hallucination-free.org/data/hallucination-tracker-v2.31.json', 'sha256': '049f2dd5c00da66f66611edd079da6baeaee7483686500e27726f6e812157c3f', 'domain': 'hallucination-free.org', 'evidence_field': 'ai_involvement'}
START, END = date(2026, 8, 1), date(2026, 10, 29)
STATES = ('inside', 'boundary_overlap', 'outside')

def interval(value, precision):
    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}'}
    if precision not in patterns or not re.fullmatch(patterns[precision], value):
        raise ValueError('Date precision and value disagree')
    parts = list(map(int, value.split('-')))
    if precision == 'day':
        lo = hi = date(*parts)
    elif precision == 'month':
        lo = date(*parts, 1); hi = date(*parts, monthrange(*parts)[1])
    else:
        lo = date(parts[0], 1, 1); hi = date(parts[0], 12, 31)
    return lo, hi

def classify(value, precision, start=START, end=END):
    if start > end: raise ValueError('Window starts after it ends')
    lo, hi = interval(value, precision)
    state = 'outside' if hi < start or lo > end else ('inside' if start <= lo and hi <= end else 'boundary_overlap')
    return state, lo.isoformat(), hi.isoformat()

def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('input', type=Path); p.add_argument('output', type=Path)
    a = p.parse_args(); raw = a.input.read_bytes()
    if hashlib.sha256(raw).hexdigest() != PIN['sha256']: raise ValueError('Frozen input differs')
    d = json.loads(raw); records = sorted(d['records'], key=lambda r: r['id'])
    if d['version'] != PIN['version']: raise ValueError('Wrong release')
    if len({r['id'] for r in records}) != len(records): raise ValueError('Duplicate ID')
    counts = Counter(); rows = []; members = []
    for r in records:
        if not r['date_basis'].strip(): raise ValueError('Missing date basis')
        state, lo, hi = classify(r['event_date'], r['date_precision'])
        counts[state] += 1
        rows.append(dict(id=r['id'], event_date=r['event_date'], date_precision=r['date_precision'], date_basis=r['date_basis'], interval_start=lo, interval_end=hi, selection=state, evidence_label=r[PIN['evidence_field']], primary_source_url=r['primary_source_url'], source_scope=r['source_scope']))
        members.append(dict(selection=state, comparison_interval=[lo,hi], record=r))
    summary = dict(collection=PIN['collection'], version=PIN['version'], source_url=PIN['url'], source_sha256=PIN['sha256'], window_start=START.isoformat(), window_end=END.isoformat(), inclusive_days=(END-START).days+1, denominator=len(records), unit='stored record with a dated milestone; not an independent event', counts={s:counts[s] for s in STATES}, inside_plus_boundary_candidates=counts['inside']+counts['boundary_overlap'], limits='Calendar bounds are comparison aids, not newly verified dates. Boundary overlap only flags metadata for review; date_basis may already rule out a recent occurrence. Read date_basis: an occurrence, filing, disclosure, study or ruling can be the milestone. Curated coverage, uncertain dates and shared episodes prevent prevalence or trend estimates. No fresh source verification by this script.')
    def encoded(o): return json.dumps(o, ensure_ascii=False, indent=2)+'\n'
    outputs = {'summary.json':encoded(summary), 'records.json':encoded(dict(summary=summary, records=members))}
    for name, rr in [('dates.csv', rows), ('counts.csv', [dict(selection=s, records=counts[s], denominator=len(records)) for s in STATES])]:
        stream=io.StringIO(newline=''); w=csv.DictWriter(stream, fieldnames=list(rr[0])); w.writeheader(); w.writerows(rr); outputs[name]=stream.getvalue()
    labels={'inside':'Inside window', 'boundary_overlap':'Boundary overlap', 'outside':'Outside window'}
    chart=['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 440 370">', '<title>Dated milestone selection, August 1 to October 29, 2026</title>', '<desc>Counts of selected records, not a failure rate or exact event timeline.</desc>', '<rect width="440" height="370" fill="#faf5ed"/>', '<g font-family="sans-serif" fill="#242424">', '<text x="16" y="28" font-size="19">90-day milestone window</text>', f'<text x="16" y="51" font-size="14">{escape(PIN["collection"])} v{PIN["version"]}: {len(records)} records</text>']
    for i,s in enumerate(STATES):
        y=84+i*68; chart += [f'<text x="16" y="{y}" font-size="16">{labels[s]}: {counts[s]}</text>', f'<rect x="16" y="{y+10}" width="{380*counts[s]/len(records):.2f}" height="23" fill="#174f63"/>']
    chart += [f'<text x="16" y="303" font-size="14">{escape(PIN["domain"])} · CC BY 4.0</text>', '<text x="16" y="325" font-size="14">August 1–October 29, 2026 inclusive</text>', '<text x="16" y="347" font-size="14">Milestone dates; not occurrence frequency.</text>', '</g></svg>']
    outputs['chart.svg']=''.join(chart)+'\n'
    a.output.mkdir(parents=True, exist_ok=False)
    for name,text in outputs.items(): (a.output/name).write_bytes(text.encode('utf-8'))

if __name__ == '__main__': main()
