from pathlib import Path
import json,re,hashlib,sys
H=Path(__file__).resolve().parent;R=Path('/tmp/cdx-ai-scale-datetime-read4-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(x,m):
 global N
 N+=1
 assert x,m
def independent(case,rows,lane):
 yun='Yunkangbao'in case['path'];byDate='byDate'in case['path'];sessions=[s for s in rows['sessions'] if s['is_valid']==1 and s['device_type']=='body_scale' and (not yun or s['vendor']=='yunkangbao') and (not byDate or s['start_time'][:10]=='2026-10-11')];s=sorted(sessions,key=lambda x:(x['start_time'],x['session_id']),reverse=True)[0];rs=[r for r in rows['records'] if r['session_id']==s['session_id']];raw=next(r for r in rows['raw'] if r['session_id']==s['session_id']);summary={};segments={}
 for r in rs:
  v={'value':float(r['value']),'unit':r['unit']}
  if not r['segment']:summary[r['metric_code']]=v
  else:segments.setdefault(r['segment'],{})[r['metric_code']]=v
 time=s['start_time'];ck(re.fullmatch(r'2026-10-11 \d\d:\d\d:\d\d'+(r'\.000000' if lane=='C' else ''),time)!=None,'Native physical0/6 retained')
 return {'session_id':s['session_id'],'measured_at':time[:19] if lane=='C' else time,'vendor':s['vendor'],'device_type':'body_scale','algorithm_vendor':rs[0]['algorithm_vendor'],'algorithm_version':rs[0]['algorithm_version'],'summary':summary,'segments':[] if not segments else segments,'raw':json.loads(raw['data']),'bmi_cn':'标准'}
summary={};dto={};plan=j(H/'execution-plan.json');pins=j(H/'source-frozen-sha.json')['files']
ck(len(pins)==6169,'Root exact6169 runtime manifest')
for lane in ('B','C'):
 p=R/f'private-{lane}-final';pre=j(p/'preflight-state.json');final=j(p/'final-capture.json');native=lines(p/'business-native.jsonl');budget=lines(p/'sql-budget.jsonl');dto[lane]={}
 ck([x['n'] for x in budget]==list(range(1,len(budget)+1)) and len(budget)<=600 and final['SQL']==len(budget),'Unified allSQL cap600 no reset');ck(j(p/'preflight-ready.json')['SQL']<=180,'Pref/constructor cap180')
 ck(not any('error'in x for x in native) and not list(p.glob('*error-*.json')),'No swallowed native/observer/harness error')
 ck(not any(x.get('operation')in('INSERT','UPDATE','DELETE') or x['layer']in('actual PDO.beginTransaction','actual PDO.commit','actual PDO.exec transaction') for x in native),'Zero business DML/transaction')
 ck(not (p/'prepare-attempt.json').exists() and not list(p.glob('serve-captures*')) and not list(p.glob('userapi-captures*')),'Zero prepare/UserApi/Serve')
 ck(j(p/'run-complete.json')['actual_HTTP']==4 and len(list(p.glob('request-*.json')))==len(list(p.glob('client-attempt-*.json')))==4,'Only4actualHTTP/no retry')
 ck(final['all_protection_match'] and final['protection']==pre['protection'] and final['scale']==pre['scale'] and final['unrelated_hashes']==pre['unrelated_hashes'],'All exactscope fullrows and nonownStore3hash unchanged')
 ck(final['scale']==j(p/'scale-baseline.json') and final['protection']['AI']==j(p/'AI-baseline.json') and final['protection']['related']==j(p/'disease-baseline.json') and final['protection']['funds']==j(p/'fund-baseline.json'),'Matches prior immutable sealed rows/ledger baseline')
 ck([len(final['scale'][t]) for t in ['sessions','raw','records']]==[2,2,6],'Exactly original10 Store rows/no new')
 for x in lines(p/'independent-native.jsonl'):ck(re.search(r'\bydy_(?:staff|prepay_order)\b',x['queryString'],re.I) is None,'No globalStoreStaff/oldPrepay raw data query')
 dates=j(p/'fresh-date-precision.json')['columns'];ck(len(dates)==2,'Exactly start/end freshmetadata')
 if lane=='B':ck(all(x['column_type']=='datetime' and x['data_type']=='datetime' and x['datetime_precision']==0 for x in dates),'Actual MySQL DATETIME_PRECISION0')
 warm=j(p/'constructor-warm.json')['connections']
 for db,alias,port,sc in [('AI','mysql','5238','AIZHCT_APP'),('ZHCT','mysql_zhct','5237','ZHCT_APP')]:
  x=warm[db];ck(x['alias']==alias and x['PDO']=='OwnedPDO','Original app dual PDO aliases')
  if lane=='C':ck(x['driver']=='dm' and x['connector']=='CoreDm' and x['source_connector']=='app\\common\\database\\Dm' and x['host']=='127.0.0.1' and x['port']==port and x['actual_schema'][0]['schema_name']==sc,'Actual SourceDm/nativeDm/liveschema both C connections')
  else:ck(x['driver']=='mysql' and x['actual_schema'][0]['version'].startswith('5.6.'),'True B two MySQL56 connections')
 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,'Every native statement paired sourceplan');bp=plans[key];ck(len(bp)==len(x['bindValue']),'Every source/native binding paired')
   for k,pair in (enumerate(bp) if isinstance(bp,list) else bp.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(b['value'])==type(value) and b['value']==value and b['pdo_type']==(2 if t==21 else t) and b['ok'],'Original exact native PHP/PDO value/type')
 for case in plan['cases']:
  label=case['label'];r=j(p/f'response-{label}.json');c=j(p/f'client-{label}.json');d=json.loads(r['raw_response_body']);want=independent(case,pre['scale'],lane);dto[lane][label]=d['data']
  ck(r['http_status']==c['http_status']==200 and r['raw_response_body']==c['body_raw'],'Full original wire/client bytes/status');ck(r['business_end']<=r['captured_microtime']<=c['end'],'Immutable response first save before send')
  ck(list(d)==['status','message','data','trace_id'] and d['status']==200 and d['message']=='ok' and re.fullmatch('[0-9a-f]{13}',d['trace_id'])!=None,'Complete original envelope/type/order')
  ck(json.dumps(d['data'],ensure_ascii=False,separators=(',',':'))==json.dumps(want,ensure_ascii=False,separators=(',',':')),'Independent full10fields/arraysequence/type/value DTO')
  ck(len(d['data']['measured_at'])==19 and isinstance(d['data']['measured_at'],str),'Only legitimate zero-fraction display correct19')
  ck(d['data']==j(p/'expected-DTO.json')[label] and j(p/f'oracle-{label}.json')['full_typed_ordered_DTO'],'Pre-frozen whole oracle unchanged')
  oldlabel='R1_WELLAND_BY_DATE' if 'WellandScale'in case['path'] else 'R2_YUNKANGBAO_BY_DATE';old=json.loads(j(p/f'old-response-{oldlabel}.json')['raw_response_body'])
  if lane=='B':
   old.pop('trace_id');current=dict(d);current.pop('trace_id');ck(json.dumps(current,ensure_ascii=False,separators=(',',':'))==json.dumps(old,ensure_ascii=False,separators=(',',':')),'B entire old contract unchanged excluding only dynamic trace')
  else:
   old['data']['measured_at']=old['data']['measured_at'][:19];ck(d['data']==old['data'],'C exactly single display field changed vs old red, no other projection changes')
  ck(j(p/f'read-scale-{label}.json')==pre['scale'],'All10physical rows same after each HTTP');inc=j(p/f'included-{label}.json');ck(all(pins.get(k)==v for k,v in inc['files'].items()),'All actualincluded Root newSHA');ck(inc['native_count']<=(60 if lane=='B' else 120) and inc['counts']==[],'Reader nativecaps and0DML')
  ck(j(p/f'request-{label}.json')['case']==case,'Exact authorisedmethods/queries/rawbody')
 ck(j(p/'cleanup.json')['tokens']['U1']=='revoked' and j(p/'worker-stopped.json')['port_closed'] and len(j(p/'cache-cleanup.json')['own_cache_files_removed'])==2,'Only token1/cache2/PID/port cleared')
 fs=j(p/'source-actual-fileset.json');ck(fs['actual_regular_files']==6169 and fs['appledouble_magic_count']==0 and set(fs['files'])==set(pins) and all(v['sha256']==pins[k] for k,v in fs['files'].items()),'Actual6169 source全set/allSHA/magic0')
 ck(j(p/'helper-actual-fileset.json')['files']==j(H/'helper-sha.json'),'Whole23actualhelpers frozen')
 summary[lane]={'HTTP':4,'prepare':0,'DMLDDL':0,'SQL':len(budget),'preflight_SQL':j(p/'preflight-ready.json')['SQL'],'full_DTO_pass':4,'all_date_strings19':True,'all10physical_rows_unchanged':True,'ownAI_funds_protection':True,'global_StoreStaff_claim':False,'resources_cleaned':True}
for lane in ('B','C'):
 ck(dto[lane]['R1_WL_BY_DATE']==dto[lane]['R3_WL_LATEST'] and dto[lane]['R2_QN_BY_DATE']==dto[lane]['R4_QN_LATEST'],'Original latest/bounded day choose correct existing sessions')
for label in ['R2_QN_BY_DATE','R4_QN_LATEST']:
 b=dict(dto['B'][label]);c=dict(dto['C'][label]);b.pop('session_id');c.pop('session_id');ck(json.dumps(b,ensure_ascii=False,separators=(',',':'))==json.dumps(c,ensure_ascii=False,separators=(',',':')) and b['measured_at']=='2026-10-11 08:30:00','Fixed QN entire cross DTO/value/types/array order equal except genuine session ID')
out={'status':'PASS_SCALE_DATETIME_DISPLAY_READ4_NO_WRITER_REPLAY','checks':N,'lanes':summary,'cross_fixed_QN_DTO_except_real_session_ID':'PASS','WL_natural_clock':'B11:57:21/C11:57:20 original independent native source preserved, shape19 only aligned','scope':'No globalStoreStaff unchanged claim; oldRead8 drift unattributed; Prepay oldraw released; true Store sync separately pending'}
if '--record'in sys.argv:
 ck(not (H/'manifest.json').exists(),'No sealed overwrite');(H/'audit-result.json').write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n')
print(json.dumps(out,ensure_ascii=False))
