#!/usr/bin/env python3
"""Read-only independent check of the actual Root DDL journal, not a SQL runner."""
import hashlib
import json
from pathlib import Path
import sys

path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path('/Users/wiscourper/Documents/workspace/local/dm8-batch116-20261012.S1TtvG/billing197-root-events.jsonl')
raw = path.read_bytes()
assert hashlib.sha256(raw).hexdigest() == '194f9c56240854c8f415d243974345f909e280b7189a1a7d1c33491709508887'
events = [json.loads(line) for line in raw.splitlines()]
assert len(events) == 89
assert not any(e['event'].startswith('STOP') for e in events)
base = next(e['snapshot'] for e in events if e['event'] == 'baseline')
names = {
    'UX_YDY_BILLING_RECORD_BILL_NO': ('YDY_BILLING_RECORD', ['BILL_NO']),
    'UX_YDY_BILLING_RECORD_STORE_MONTH_STAFF_DEL': ('YDY_BILLING_RECORD', ['STORE_ID', 'BILL_MONTH', 'STAFF_UUID', 'IS_DELETE']),
    'UX_YDY_BILLING_DETAIL_BILL_MEAL_DEL': ('YDY_BILLING_RECORD_DETAIL', ['BILL_ID', 'MEAL_TYPE', 'IS_DELETE']),
}
assert base['rows']['YDY_BILLING_RECORD']['count'] == 533
assert base['rows']['YDY_BILLING_RECORD_DETAIL']['count'] == 1597
assert len(base['columns']) == 38 and len(base['constraints']) == 2 and not base['triggers']
read_results = [e for e in events if e['event'] == 'read-result']
assert len(read_results) == 39 and all(e['SQLSTATE'] == '00000' for e in read_results)
assert all(e['sql'].startswith('SELECT ') for e in events if e['event'] == 'read-intent')
ddl = [e for e in events if e['event'] == 'ddl-intent']
assert [e['name'] for e in ddl] == list(names)
for e in ddl:
    table, cols = names[e['name']]
    expected = 'CREATE UNIQUE INDEX ZHCT_APP.' + e['name'] + ' ON ZHCT_APP.' + table
    expected += ' (' + ','.join('"' + c + '"' for c in cols) + ')'
    assert e['sql'] == expected and e['sha256'] == hashlib.sha256(expected.encode()).hexdigest()
results = [e for e in events if e['event'] == 'ddl-result']
assert [e['name'] for e in results] == list(names)
assert [e['count'] for e in results] == [1, 2, 3]
assert all(e['SQLSTATE'] == '00000' for e in results)
stages = [e for e in events if e['event'] == 'verified-stage']
assert len(stages) == 3
assert events[-1]['event'] == 'fresh-connection-final'
for count, stage in enumerate(stages + [events[-1]], 1):
    snapshot = stage['snapshot']
    for key in ('rows', 'columns', 'constraints', 'triggers'):
        assert snapshot[key] == base[key]
    old = [r for r in snapshot['indexes'] if r['index_name'] not in names]
    assert old == base['indexes']
    for name, (table, cols) in list(names.items())[:min(count, 3)]:
        rows = [r for r in snapshot['indexes'] if r['index_name'] == name]
        assert [r['column_name'] for r in rows] == cols
        for position, row in enumerate(rows, 1):
            assert row['table_name'] == table and row['column_position'] == position
            assert row['uniqueness'] == 'UNIQUE' and row['status'] == 'VALID' and row['descend'] == 'ASC'
    assert len(snapshot['indexes']) == len(old) + sum(len(cols) for _, cols in list(names.values())[:min(count, 3)])
assert events[-1]['DDL'] == 3 and events[-1]['DML'] == 0 and events[-1]['reads'] == 39
print(json.dumps({'verified': True, 'DDL': 3, 'SELECT': 39, 'DML': 0,
    'actual_table_rows': [533, 1597], 'old_full_rows_and_structure_unchanged': True,
    'exact_new_unique_indexes': 3, 'independent_new_connection': True, 'events': 89}))
