import base64,copy,hashlib,json,re,sys
from pathlib import Path
from oracle import oracle
HERE=Path(__file__).resolve().parent;COUNT=0
def check(ok,why):
 global COUNT
 COUNT+=1
 if not ok:raise AssertionError(why)
def exact(a,b,where=''):
 check(type(a) is type(b),where+' type')
 if isinstance(b,dict):
  check(list(a)==list(b),where+' keys/order')
  for k,v in b.items():exact(a[k],v,where+'/'+str(k))
 elif isinstance(b,list):
  check(len(a)==len(b),where+' length')
  for i,v in enumerate(b):exact(a[i],v,where+'/'+str(i))
 else:check(a==b,where+' value')
def load(lane,name):return json.loads((HERE/'private'/lane/name).read_text())
def run():
 report={'HTTP':0,'DML':0,'DDL':0,'logs':0,'native_execute':{},'preflight':{},'full_DTO':{},'negative_cases':0};bodies={}
 for lane in ['B','C']:
  before=load(lane,'before.json');expected=oracle(before,lane);exact(expected,load(lane,'expected-before-http.json'),'immutable preHTTP oracle')
  check(sum(len(before[k]) for k in ['nutrition','nutrition_template','nutrition_set','nutrition_category','nutrition_time','nutrition_template_ext'])==11,'exact11 own')
  source_native=next(r for r in before['nutrition_native'] if r['uuid']==('B8247519-0EDA-6239-9A8A-FEA2D6C86F4B' if lane=='B' else 'FCEECEFB-C32E-4977-8A65-EE2210A42095'))
  check(source_native['fields']['use_weight_computed']['bits64']=='000000403cdd5e40','final Plain new123.4568 promoted32 physical bits')
  lease=load(lane,'lease.json');check(lease['SELECT']==18 and lease['own_rows']==11 and lease['media_empty'],'fresh18 metadata lease');report['preflight'][lane]={'successful_fresh_SELECT':18,'prior_failed_attempts':16 if lane=='C' else 0,'total_attempts':34 if lane=='C' else 18}
  for event in load(lane,'lease-oracle.json'):
   check(event['queryString'].startswith('SELECT'),'all preflight SELECT');check('TRIGGER_TYPE' not in event['queryString'],'mature trigger query in successful lease')
   if 'FROM ydy_config ' in event['queryString']:check(event['rows'] is None and event['rows_count']==6 and len(event['rows_sha256'])==64,'source clock values masked')
  attempts=load(lane,'http-attempts-ro6.json');check(len(attempts)==3,'three actual client requests');report['HTTP']+=len(attempts);total=0;states={}
  for attempt in attempts:
   w=load(lane,'wire-'+attempt['label']+'.json');label=w['label'];check(attempt['complete'] and base64.b64decode(attempt['body_base64']).decode()==w['body'],'actual client/wire exact bytes');check(hashlib.sha256(w['body'].encode()).hexdigest()==w['body_sha256'],'wire bodySHA');check(w['status']==200 and w['last_error'] is None,'actual200 no runtime error');exact(json.loads(w['body']),expected[label],lane+'/'+label+' all DTO keys/types/order')
   check(w['own_source_unchanged'],'own lease protected flag');exact(w['source_before'],before,'full11/actor/config/bits before');exact(w['source_after'],before,'full11/actor/config/bits after')
   executions=[e for e in w['native'] if e['layer']=='actual PDOStatement.execute'];check(len(executions)<=(12 if lane=='B' else 24),'native per-request cap');states[label]=len(executions);total+=len(executions);natural_dict=[]
   for event in w['native']:
    sql=event['queryString'];check(not re.match(r'^\s*(INSERT|UPDATE|DELETE|MERGE|CREATE|ALTER|DROP|TRUNCATE|REPLACE)\b',sql,re.I),'no actual business DMLDDL/log')
    if event['layer']=='actual PDOStatement.execute':check(event['success'] and event['errorInfo'][0]=='00000','native execute success')
    if event['layer']=='actual PDOStatement.fetchAll' and sql.startswith('SELECT ') and 'FROM `ydy_config`' in sql:check('rows' not in event and event['config_values_recorded'] is False,'bootstrap values countSHA only')
    if event['layer']=='actual PDOStatement.fetchAll' and re.match(r'^SELECT .*FROM [`"]?ydy_nutrition_time[`"]? ',sql,re.I):
     check('rows' not in event and event['natural_dictionary_values_recorded'] is False and len(event['rows_sha256'])==64,'Time dictionary not dumped');check(event['rows_count']==load(lane,'metadata.json')['time_dictionary_count'][0]['n'],'original Time dictionary COUNT matches read');check(len(event['own_leaf'])==1,'only one own Time leaf recorded');natural_dict.append({'rows':event['rows_count'],'sha256':event['rows_sha256'],'own_leaf':event['own_leaf']})
   if label=='UseTimeGroup-ro6':check(len(natural_dict)==1,'real unchanged names dictionary read')
   helpers=['NutritionFloat82Write.php','NutritionPlainFloatWeight.php'];check(all('/tmp/cdx-nutrition-physical-ro6-20261011/source/application/common/service/'+h in w['included_files'] for h in helpers),'actual Root two helpers loaded')
   expected_controller={'UseTimeGroup-ro6':'app\\m\\controller\\Nutrition','GetNutritionTime-ro6':'app\\p\\controller\\NutritionScheme','TemplateInfo-ro6':'app\\p\\controller\\NutritionTemplate'}[label];check(expected_controller in w['reflection'],'actual precise controller loaded')
   mapping=json.loads((HERE/'source-lock.json').read_text());ref=w['reflection'][expected_controller];relative=ref['file'].split('/source/application/')[1];check(ref['sha256']==mapping[relative],'controller source SHA exact Root959')
   if label=='TemplateInfo-ro6':check(json.loads(w['body'])['data']['template_ext'][0]['train_time']=='1' and json.loads(w['body'])['data']['template_ext'][0]['use_volume']=='1.25','original string field types retained')
  check(total<=(36 if lane=='B' else 72),'total formal native cap');report['native_execute'][lane]={'per_case':states,'total':total};bodies[lane]=expected;report['full_DTO'][lane]=list(expected)
  exact(load(lane,'after.json'),before,'final full own snapshot invariant');exact(load(lane,'final.json'),{'own_source_unchanged':True,'HTTP':3,'DML':0,'DDL':0,'logs':0},'final exact result')
  receipt=load(lane,'oracle-read-receipts.json');check(all(r['execute_success'] for r in receipt),'per-SELECT durable successful read receipts');check(all('typed_binds' in r and 'rows_count' in r for r in receipt),'per-SELECT typed receipt/raw written')
  resource=load(lane,'resource-check.json');check(all(resource[k] for k in ['own_worker_absent','own_port_closed','original_parent_present','request_absent','cache_absent']) and resource['AppleDouble']==[],'own exact resources cleared')
  provenance=load(lane,'source-provenance.json');check(provenance['source_php_files']==959 and provenance['source_lock_sha256']=='49b1a564de5a93dcd0385659a3d79f2e92256970b7fd7cc0a1adb8d482ccdd57','959 actual immutable runtime pin')
 exact(bodies['B']['GetNutritionTime-ro6']['data']['add_select_phase'],[],'B Set23 native phase empty array');exact(bodies['C']['GetNutritionTime-ro6']['data']['add_select_phase'],{'0':0,'2':1,'11':2,'13':3},'C Set3 native phase object, not washed')
 report['phase_difference']={'B_set_id':23,'C_set_id':3,'B':[],'C':{'0':0,'2':1,'11':2,'13':3},'reason':'Original hardcoded Set primary-ID business classification; not a formatter defect'}
 dto=bodies['C']['GetNutritionTime-ro6']
 for bad in [None,{},[],{**dto,'code':'0'},{**dto,'data':{**dto['data'],'add_select_phase':[]}},{**dto,'data':{**dto['data'],'nutrition_array':[]}},{**dto,'extra':1},{'message':dto['message'],'code':0,'data':dto['data']}]:
  try:exact(bad,dto,'counterexample')
  except AssertionError:report['negative_cases']+=1
  else:raise AssertionError('Accepted invalid DTO')
 report['assertions']=COUNT;report['status']='Three real nonempty read paths per lane pass full source DTO; prior partials regressed; new path awaits Root registration; phase identity differences preserved'
 data=json.dumps(report,ensure_ascii=False,indent=2)+'\n';target=HERE/'verification.json'
 if '--verify' in sys.argv:check(target.read_text()==data,'sealed verification bytes exact')
 else:
  if target.exists():raise AssertionError('Do not overwrite verification')
  target.write_text(data)
 print(json.dumps(report,ensure_ascii=False))
if __name__=='__main__':run()
