"""Check the downloaded casebook, independent of the asset preparation script."""
from pathlib import Path
import csv
import hashlib
import json
import re

folder = Path(__file__).resolve().parent
manifest = (folder / 'MANIFEST.sha256').read_text(encoding='utf-8').splitlines()
seen = set()
for line in manifest:
    match = re.fullmatch(r'([0-9a-f]{64})  ([A-Za-z0-9_.-]+)', line)
    assert match, 'Malformed manifest row'
    digest, name = match.groups()
    assert name not in seen and name != 'MANIFEST.sha256', 'Duplicate/self entry'
    seen.add(name)
    assert hashlib.sha256((folder / name).read_bytes()).hexdigest() == digest, name
assert seen == {'cases.json', 'cases.csv', 'review-flow.svg', 'review-sheet.html', 'README.md', 'verify.py'}, 'Incomplete manifest'
payload = json.loads((folder / 'cases.json').read_text(encoding='utf-8'))
assert payload['version'] == 1 and payload['access_date'] == '2026-09-05'
rows = payload['cases']
with (folder / 'cases.csv').open(encoding='utf-8', newline='') as stream:
    assert rows == list(csv.DictReader(stream)), 'CSV and JSON disagree'
expected = {
    'R1': 'Enforced first show: B',
    'R2': 'Enforced first show: A',
    'R3': 'Enforced first show: B',
    'A1': 'Table A and B before further board cards',
    'A2': 'All-in exposure trigger not yet reached',
    'A3': 'Table A, B and C',
    'C1': 'C need not show to collect',
    'C2': 'Table both hole cards to claim a share',
    'C3': 'B has right to request last aggressor A',
    'C4': 'B has lost the request right',
}
assert len(rows) == len(expected)
assert {row['id']: row['answer'] for row in rows} == expected
assert all(set(row) == {'id', 'rule_profile', 'state', 'action_record', 'answer', 'decisive_fact'} for row in rows)
assert all(all(isinstance(value, str) and value.strip() for value in row.values()) for row in rows)
print('PASS: six hashes, CSV/JSON parity, ten manually reviewed answer contracts. Rules still require human review.')
