#!/usr/bin/env python3
"""Evidence-checked H5 bill list and newly registered concrete detail route."""
import hashlib
import json
import re
import subprocess
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

HERE = Path(__file__).resolve().parent
PRIVATE = tool.ROOT.parent / 'worktrees/dm8-compat-20261012/private-prepay-harness/batch196-h5-bill-read'
BASE = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-h5-bill-read-20261013/'


def equal_typed(a, b):
    assert type(a) is type(b), (type(a), type(b))
    if isinstance(a, dict):
        assert list(a) == list(b)
        for k in a:
            equal_typed(a[k], b[k])
    elif isinstance(a, list):
        assert len(a) == len(b)
        for av, bv in zip(a, b):
            equal_typed(av, bv)
    else:
        assert a == b, (a, b)


def verify():
    for name, digest in [
        ('REPORT.md', 'a33b179f119e76413dd7b60c0147fe78ffafc7e287b835d7a504d3b88da8a8c4'),
        ('verify_green_offline.php', 'a92007238c5cbb06e1ab080cc39e0222adb3ccdf5c697b7b4419d354179f8884'),
    ]:
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest
    r = json.loads(subprocess.check_output(['/opt/homebrew/opt/php@7.4/bin/php', str(PRIVATE / 'verify_green_offline.php')]))
    assert r['status'] == 'verified-green' and r['total_http'] == 9 and r['new_green_http'] == 4
    assert r['setup_insert_per_lane'] == 2 and r['green_business_dml'] == r['ddl'] == 0
    for lane in ('B', 'C'):
        setup = json.loads((PRIVATE / (lane + '-196-bill-prepared.json')).read_text())
        b = setup['bill_row']
        d = setup['detail_row']
        def date(value):
            if lane == 'C' and re.fullmatch(r'\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.0{1,6}', value):
                return value[:19]
            return value
        expected = dict(id=int(b['id']), record_id=int(b['id']), bill_id=b['bill_no'],
            bill_no=b['bill_no'], student_name=b['student_name'], student_no=b['student_no'],
            dept_name=b['department_name'], bill_month=b['bill_month'], payable_amount=float(b['amount']),
            status='已缴费', expire_time=date(b['expire_time']), paid_time=date(b['pay_time']),
            detail_count=int(d['adjusted_count']), details=[dict(meal_type=int(d['meal_type']),
                fee_type='早餐', adjusted_count=int(d['adjusted_count']), subtotal='0.01')])
        for route in ('bills', 'detail'):
            body = json.loads((PRIVATE / f'{lane}-196-h5-{route}-green.raw').read_text())
            row = body['data']['list'][0] if route == 'bills' else body['data']
            if route == 'bills':
                assert len(body['data']['list']) == 1
            equal_typed(row, expected)
    for name, digest in [
        ('app/api/service/H5Bill.php', 'a903f672432780e58e023d91b81fdf2bf5a8d62a629061007cfae5c5d24c1aab'),
        ('tests/H5BillTimeContract.check.php', 'ad3471e9f428ee0c844aa4c0c0b496372bf4c6bde2e9f121817b980c5a8d061d'),
    ]:
        assert hashlib.sha256((tool.source_root('ai_api') / name).read_bytes()).hexdigest() == digest
    routes = (tool.source_root('ai_api') / 'route/app.php').read_text()
    assert "Route::rule('h5/bills/:billId', 'api/H5/billDetail', 'GET')" in routes


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-batch196.json'
    assert not audit.exists()
    specs = []
    for path in ('/api/h5/bills', '/api/h5/bills/:billId'):
        s = item('ai_api', 'GET', path, BASE,
            readback='tested-pass-synthetic-paid-state-bill-detail-and-two-users-unchanged-not-payment-proof',
            success_case='partial-evidence-one-owned-nonempty-paid-state-read-only',
            parity='partial-evidence-full-DTO-derived-from-own-source-dates-fixed-identity-time-differences-attributed',
            cleanup='own-marked-fixture-retained-short-token-removed-readonly-workers-reused')
        if path.endswith(':billId'):
            s.update(register_new_runtime_key=True, runtime_observed_method='GET',
                runtime_inventory_scope='controller-direct-http-observed',
                runtime_direct_http_proof=BASE + 'REPORT.md',
                runtime_controller_source='ai_api/route/app.php:34 and app/api/controller/H5.php:58; actual original HTTP observed')
        specs.append(s)
    tool.main(specs, audit, verify)
