from pathlib import Path
import json,re,hashlib,datetime,sys
from decimal import Decimal
H=Path(__file__).resolve().parent;R=Path('/tmp/cdx-ai-disease-owned-flow-20261011');N=0
def j(p):return json.loads(p.read_text())
def lines(p):return list(map(json.loads,p.read_text().splitlines()))
def ck(v,m):
 global N
 N+=1
 assert v,m
def expectedInfo(cat):
 disease=[{'name':n,'value':i+1,'is_checked':int(i==3)} for i,n in enumerate(['糖尿病','高血压','高血脂','高尿酸'])]+[{'name':'无','value':0,'is_checked':0}]
 habit=[{'enum_key':x['enum_key'],'enum_name':x['enum_name'],'people':x['people'],'ratio':None if x['ratio'] is None else format(Decimal(str(x['ratio'])).quantize(Decimal('.01')),'f'),'checked':int(str(x['enum_key'])=='3')} for x in cat['2']]
 out={'disease':disease,'habit':habit,'sport':{'id':0,'name':''}}
 for t,n in [('14','foodAllergy'),('15','foodAvoidance'),('16','dietaryPreference'),('17','otherConcerns')]:out[n]=[{'enum_key':x['enum_key'],'enum_name':x['enum_name'],'is_checked':0} for x in cat[t]]
 return out
summary={}
for lane in ('B','C'):
 p=R/f'private-{lane}-final';a=j(p/'owned-actor.json');pre=j(p/'preflight-state.json');final=j(p/'final-capture.json');native=lines(p/'business-native.jsonl');budget=lines(p/'sql-budget.jsonl');schema=j(p/'schema.json')
 ck([x['n'] for x in budget]==list(range(1,len(budget)+1)) and len(budget)<=600,'Unified monotonic600');ck(final['SQL']==len(budget),'Exact total');ck(j(p/'preflight-ready.json')['SQL']<=180,'Preflight/constructor180')
 ck(j(p/'run-final.json')['actual_total_HTTP']==2 and j(p/'run-final.json')['R1_pass'] and j(p/'run-final.json')['W1_not_replayed'],'Exactly2HTTP no replay');ck(len(list(p.glob('client-attempt-*.json')))==len(list(p.glob('request-*.json')))==2,'Only two original attempts')
 ck(not any('error' in x for x in native),'No swallowed native errors');ck(not (p/'prepare-attempt.json').exists() and not (p/'userapi-denied.jsonl').exists(),'0prepare/UserApi0run')
 writes=[x for x in native if x['layer']=='actual PDOStatement.execute' and x.get('operation') in ('INSERT','UPDATE')];ck(len(writes)==2 and all(x['scenario']=='W1_DISEASE_EDIT' and x['operation']=='INSERT' and x['success'] and x['rowCount']==1 for x in writes),'Actual2I/affected1/0U')
 ck(set(j(p/'after-W1_DISEASE_EDIT.json')['counts'])=={'INSERT.yoshop_user_disease','INSERT.yoshop_habit'},'Exact two tables');ck(any(x['layer']=='actual PDO.commit' and x['success'] for x in native),'Original disease transaction commit')
 plans={}
 for x in native:
  key=(x['scenario'],x['connection'],x.get('queryString'))
  if x['layer']=='original framework bind plan':plans[key]=x['bind_plan']
  elif x['layer']=='actual PDOStatement.execute':
   ck(key in plans,'Original plan before native execute');plan=plans[key];ck(len(plan)==len(x['bindValue']),'All native binds paired')
   for k,pair in (enumerate(plan) if isinstance(plan,list) else plan.items()):
    value,t=pair if isinstance(pair,list) else (pair,2)
    if t==21 and isinstance(value,str):value=float(value)
    if t==1 and value=='':value=0
    b=x['bindValue'][str(k+1) if isinstance(k,int) else ':'+k];ck(type(value)==type(b['value']) and value==b['value'] and b['pdo_type']==(2 if t==21 else t) and b['ok'],'Original value/PHP/nativePDO type')
 rows=final['rows'];ck([len(rows[t]) for t in ['user_disease','habit','user_other_info']]==[1,1,0],'Only two new marked rows/OtherInfo0');ck(rows==j(p/'after-W1_DISEASE_EDIT.json')['rows']==j(p/'after-R1_DISEASE_INFO.json')['rows'],'Reader changes no own data')
 r=j(p/'response-W1_DISEASE_EDIT.json');time0=r['business_start'];time1=r['business_end']
 for t in ['user_disease','habit']:
  row=rows[t][0];cols={x['column_name'].lower():x for x in schema[t]['columns']};ck(set(row)==set(cols),'Every physical column covered')
  expected={'id':row['id'],'store_id':10001,'is_delete':0}
  expected.update({'user_id':a['user_id'],'disease_type':4} if t=='user_disease' else {'staff_id':a['staff_id'],'habit':3,'create_by':a['marker']})
  ck(isinstance(row['id'],int) and row['id']>0,'Real generated native identity')
  for k,c in cols.items():
   v=row[k];typ=c['data_type'].lower()
   if k in expected:ck(type(v)==type(expected[k]) and v==expected[k],k+' exact original type/value')
   elif k in ['create_time','update_time']:
    if 'int' in typ:ck(isinstance(v,int) and time0-2<=v<=time1+2,k+' INT source clock')
    else:
     ck(isinstance(v,str) and re.fullmatch(r'\d{4}-\d\d-\d\d \d\d:\d\d:\d\d'+(r'\.\d{6}' if lane=='C' else ''),v)!=None,k+' DATETIME native precision')
     ts=datetime.datetime.fromisoformat(v).replace(tzinfo=datetime.timezone(datetime.timedelta(hours=8))).timestamp();ck(time0-2<=ts<=time1+2,k+' auto source time')
   else:
    default=c.get('column_default',c.get('data_default'));want=None if default is None else int(default) if 'int'in typ else str(default).strip("'");ck(v==want,k+' physical default')
 ck(final['all_protection_match'] and final['protection']==pre['protection'] and final['unrelated_hashes']==pre['unrelated_hashes'],'OldWeight9/13/funds/prepay/nonown3hash exact')
 ck(final['protection']['weight9']==j(p/'weight-baseline.json'),'Sealed own9 unchanged');ck(final['protection']['weight9']['user_bind'][0]['zhct_user_id']==0,'Whole Bind0 remains')
 for label in ['W1_DISEASE_EDIT','R1_DISEASE_INFO']:
  r=j(p/f'response-{label}.json');c=j(p/f'client-{label}.json');d=json.loads(r['raw_response_body']);ck(r['raw_response_body']==c['body_raw'] and r['http_status']==c['http_status']==200,'Original immutable full wire/client bytes');ck(r['business_end']<=r['captured_microtime']<=c['end'],'Response preserved before send')
  ck(list(d)==['status','message','data','trace_id'] and d['status']==200 and re.fullmatch('[0-9a-f]{13}',d['trace_id'])!=None,'Full envelope order/types')
  if label.startswith('W1'):
   ck(d['message']=='恭喜您，信息修改成功' and d['data']==[],'Source BaseController string success message/empty array')
   ck(j(p/'observer-error-W1_DISEASE_EDIT.json')['message']=='Full original envelope' and j(p/'expected-DTO.json')['W1_DISEASE_EDIT']=='恭喜您，信息修改成功','First frozen wrong oracle/failure untouched')
   ck(j(p/'oracle-v2-W1_DISEASE_EDIT.json')['initial_frozen_oracle_was_wrong'],'Separate source-only correction not false first-pass')
  else:
   want=expectedInfo(j(p/'catalog-oracle.json'));ck(d['message']=='success' and json.dumps(d['data'],ensure_ascii=False,separators=(',',':'))==json.dumps(want,ensure_ascii=False,separators=(',',':')),'Whole ordered typed independent nonempty DTO')
   ck(d['data']==j(p/'expected-DTO.json')['R1_DISEASE_INFO'],'R1 first frozen oracle unchanged')
  inc=j(p/f'included-{label}.json');pins=j(H/'source-frozen-sha.json')['files'];ck(all(pins.get(k)==v for k,v in inc['files'].items()),'Every actual include SHA');cap=(80 if lane=='B' else 160) if label.startswith('W1') else (60 if lane=='B' else 120);ck(inc['native_count']<=cap,'Exact native request cap')
  req=j(p/f'request-{label}.json');ck(req['method']=='POST' and req['body_raw']==('{"form":{"disease":[4],"habit":3}}' if label.startswith('W1') else '{}'),'Actual client POST methods/body types')
 queue=lines(p/'serve-captures.jsonl');ck(len(queue)==2 and all(x['owned_parameters_valid'] and not x['real_queue_executed'] for x in queue),'Exactly2own queue captures/no real call')
 ck(j(p/'cleanup.json')['tokens']['U1']=='revoked' and j(p/'worker-stopped.json')['port_closed'],'One token/own PID/port cleared');ck(len(j(p/'cache-cleanup.json')['own_cache_files_removed'])==2,'Only2own caches removed')
 source=j(p/'source-actual-fileset.json');ck(source['actual_regular_files']==6168 and source['appledouble_magic_count']==0 and set(source['files'])==set(pins),'Actual6168 fileset noAppleDouble');ck(all(v['sha256']==pins[k] for k,v in source['files'].items()),'All6168 frozen bytes')
 ck(j(p/'helper-actual-fileset.json')['files']==j(H/'helper-sha.json'),'First22actual helper frozen');ck(j(p/'helper-final-actual-fileset.json')['files']==j(H/'helper-final-sha.json'),'Final24actual helper frozen')
 summary[lane]={'HTTP':2,'prepare_DML':0,'formal_INSERT':2,'formal_UPDATE':0,'DELETE':0,'DDL':0,'total_SQL':len(budget),'preflight_SQL':j(p/'preflight-ready.json')['SQL'],'relation_ids':{t:rows[t][0]['id'] for t in ['user_disease','habit']},'native_errors':0,'first_W1_oracle_error_preserved':True,'source_corrected_full_W1_pass':True,'R1_first_frozen_full_DTO_pass':True,'protection':True,'resources_cleaned':True}
out={'status':'PASS_OWNED_DISEASE_NONEMPTY_FIRST_W1_ORACLE_TOOL_ERROR_RETAINED','checks':N,'lanes':summary,'scope':'No true external call; Bind0 skips UserApi; Serve2 captured; CourseSchedule table missing B/C source-only blocked'}
if '--record'in sys.argv:
 ck(not (H.parent/'manifest.json').exists(),'No overwrite sealed evidence');(H/'audit-result.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n')
print(json.dumps(out,ensure_ascii=False))
