#!/usr/bin/env python3
"""Verify actual two-DDL state; preserve the original Oracle-status gate failure."""
import hashlib
import json
import re
from pathlib import Path

root=Path(__file__).parent
private=root/'schema-private-evidence'
records=[json.loads(line) for line in (private/'C-schema.jsonl').read_text().splitlines()]
def one(kind):
    found=[r['data'] for r in records if r['kind']==kind]
    assert len(found)==1
    return found[0]
starts=[r['data'] for r in records if r['kind']=='DDL-start']
assert len(starts)==2 and len([r for r in records if r['kind']=='DDL-success'])==2
assert starts[0]['SQL'].startswith('ALTER TABLE') and starts[1]['SQL'].startswith('CREATE TRIGGER')
assert all('OR REPLACE' not in e['SQL'] for e in starts)
for entry in starts:
    assert entry['sha256']==hashlib.sha256(entry['SQL'].encode()).hexdigest()
assert one('stopped')=={'class':'RuntimeException','message':'Exact enabled trigger','DDL_started':2,'DML':0,'HTTP':0}
before=one('business-before')
mapped=json.loads(json.dumps(before))
times={'2':'2001-02-03 04:05:06','3':'2001-02-03 04:05:07','4':'2026-10-11 02:21:27','5':'2026-10-11 02:21:28','6':'2026-10-11 02:21:28'}
for row in mapped['material_category']:
    row['create_time']=row['create_time'][:19]
    row['update_time']=times[str(row['id'])]
meta=one('metadata-before')
for step in (1,2):
    assert one('business-after-step-'+str(step))==mapped
    after=one('metadata-after-step-'+str(step))
    for key in ('indexes','index_columns','constraints','constraint_columns'):
        assert after[key]==meta[key]
    assert len(after['columns'])==12
    for old,new in zip(meta['columns'],after['columns']):
        if old['column_name'] in ('UPDATE_TIME','CREATE_TIME'):
            assert new['data_scale']==0 and new['nullable']=='N' and new['data_type']=='DATETIME'
            assert new['data_default']==('CURRENT_TIMESTAMP(0)' if old['column_name']=='UPDATE_TIME' else "'2000-01-01 00:00:00'")
            assert {k:v for k,v in old.items() if k not in ('data_scale','data_default','default_length')}=={k:v for k,v in new.items() if k not in ('data_scale','data_default','default_length')}
        else:
            assert old==new
post=json.loads((private/'C-schema-post-read-v2.json').read_text())
assert post['source']==mapped
assert post['trigger_objects']==[{'object_name':'TRG_YDY_MATERIAL_CATEGORY_UT','object_type':'TRIGGER','status':'VALID'}]
trigger=post['triggers'][0]
assert len(post['triggers'])==1 and trigger['status']=='Y' and trigger['triggering_type']=='BEFORE ROW' and trigger['triggering_event']=='UPDATE'
assert "WHEN O1.INFO1 & 0x1000 = 0x00 THEN 'Y' ELSE 'N'" in post['trigger_view_definition'][0]['text']
definition=post['trigger_ddl'][0]['ddl']
normalized=re.sub(r'^CREATE OR REPLACE\s+TRIGGER','CREATE TRIGGER',definition)
assert ' '.join(normalized.split())==' '.join(starts[1]['SQL'].split())
assert trigger['trigger_body']==definition
cli=json.loads((private/'C-logic-read-only.json').read_text())
assert cli['business_source_exact'] and cli['DML']==cli['DDL']==0
for name in ('create_time','update_time'):
    assert cli['types'][name]=={'type':'string','bytes':19}
assert cli['result']['name']=='CDXC9733C88C1-P' and cli['result']['create_time']==cli['result']['update_time']=='2001-02-03 04:05:06'
summary={'passed':True,'DDL_actual_success':2,'DML':0,'HTTP':0,'approved_5_old_rows_time_mapping':True,'other_10_columns_exact':True,'other_business_source_exact':True,'indexes_constraints_exact':True,'trigger_unique':True,'trigger_native_status':'Y','trigger_enabled_proven_from_current_view_definition':True,'trigger_object_status':'VALID','trigger_definition_matches_approved':True,'CLI_time_type':'string','CLI_time_bytes':19,'original_tool_gate_failure_preserved':'Oracle ENABLED assumption; real native Y','error_view':'USER_ERRORS unavailable (-2106), not claimed empty','business_API_retest':'NOT_YET_AUTHORIZED_NOT_RUN'}
print(json.dumps(summary,ensure_ascii=False,indent=2))
