"""Portable standard-library reproduction of the five-county annual aggregate table.

Runs offline. No original source acquisition, court-record linkage or publication.
"""
import csv
import hashlib
import json
import pathlib

P = pathlib.Path(__file__).resolve().parent
manifest = json.loads((P / 'MANIFEST.json').read_text())
for name, expected in manifest['files'].items():
    path = pathlib.PurePosixPath(name)
    if path.is_absolute() or '..' in path.parts or not (P / name).is_file() or (P / name).is_symlink():
        raise ValueError('Invalid candidate input')
    if hashlib.sha256((P / name).read_bytes()).hexdigest() != expected:
        raise ValueError('Candidate checksum mismatch: ' + name)
rows = list(csv.DictReader((P / 'annual-source-cells.csv').open()))
county_names = ['Bexar', 'Harris', 'Travis', 'Dallas', 'Tarrant']
assert len(rows) == 110 and set(r['county'] for r in rows) == set(county_names)
cells = {}
for r in rows:
    assert r['court_type'] == 'Statutory County' and r['period'] == 'fy2025'
    assert r['from'] == '09/01/2024' and r['to'] == '08/31/2025'
    assert r['category'] == 'Drug Possession - Marijuana'
    key = r['county'], r['section'], r['field']
    assert key not in cells and r['value'].isdigit()
    cells[key] = int(r['value'])
summary = []
for county in county_names:
    get = lambda section, field: cells[county, section, field]
    assert get('docket', 'Total Cases Disposed') == get('dispositions', 'Total Cases Disposed')
    leaves = sum(v for (c, s, f), v in cells.items() if c == county and s == 'dispositions' and f != 'Total Cases Disposed')
    assert leaves == get('dispositions', 'Total Cases Disposed')
    summary.append({'county': county, 'new_filings': get('docket', 'New Cases Filed'),
        'dispositions': get('dispositions', 'Total Cases Disposed'), 'dismissals': get('dispositions', 'Dismissals'),
        'reported_conviction_row_sum': sum(get('dispositions', f) for f in
            ['Convictions Guilty Plea', 'Convictions By The Court', 'Convictions By The Jury'])})
expected = list(csv.DictReader((P / 'county-summary.csv').open()))
assert len(expected) == 5
for result, row in zip(summary, expected):
    assert all(str(value) == row[field] for field, value in result.items())
print(json.dumps({'status': 'reproduced', 'countyTable': summary, 'filesVerified': len(manifest['files']),
    'boundary': 'Annual aggregate arithmetic only, not independent raw extraction/monthly reconciliation, unique people, final marijuana convictions or a linked cohort.'}, indent=2))
