#!/usr/bin/env python3
"""Evidence-limited Healthkit and actual shared missing-table failures."""
import hashlib
import json
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

HERE=Path(__file__).resolve().parent
PRIVATE=Path('/Users/wiscourper/Documents/workspace/local/dm8-resume-connect-20261012.q6m3ar')
B=Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn/runtime')
BASE='work_ai_api/2026-10-12-dm8-hk-course-batch/'
PINS={
 B/'healthkit-fixed-vector-private.jsonl':'39bb288be2b5b7fa2ce531830f54140a52376b6f5ab3fae59e82216a66457a6a',
 PRIVATE/'healthkit-fixed-C.jsonl':'c795d8f44f943766c559740e953bfc9b2247f2c5c0ee42b7137a480220083c06',
 B/'course-missing-http-raw-private.jsonl':'ee76fb23b789d8bf71d1e8c7c42f126ff89824070bd477f752113c824c04a8b5',
 PRIVATE/'course-C.jsonl':'f5e1cb6e75dc24cb4abde7ae9d2488f9a70e9f39f87271f38e978ee35cceb76a'}

def verify():
    data={}
    for p,digest in PINS.items():
        raw=p.read_bytes(); assert hashlib.sha256(raw).hexdigest()==digest
        data[p]=[json.loads(line) for line in raw.splitlines() if line]
    pairs=[data[B/'healthkit-fixed-vector-private.jsonl'],data[PRIVATE/'healthkit-fixed-C.jsonl']]
    normalized=[]
    for rows in pairs:
        assert len(rows)==4
        bodies=[]
        for n,r in enumerate(rows):
            assert r['http']==200
            assert (r['method'],r['path'])==[('GET','/api/Healthkit/status'),('GET','/api/Healthkit/summary'),('POST','/api/Healthkit/unbind'),('GET','/api/Healthkit/status')][n]
            b=json.loads(r['response_raw']);assert b['status']==200
            if n<2: assert b['data']['last_sync_at']==''
            b.pop('trace_id',None);bodies.append(b)
        normalized.append(json.dumps(bodies,sort_keys=True,ensure_ascii=False))
    assert normalized[0]==normalized[1]
    for p,code in [(B/'course-missing-http-raw-private.jsonl','42S02'),(PRIVATE/'course-C.jsonl','-7086')]:
        assert len(data[p])==2
        for r,action in zip(data[p],['create','update']):
            assert r['http']==200 and r['method']=='POST' and r['path']=='/api/user.CourseSchedule/'+action
            b=json.loads(r['response_raw']);assert b['status']==500 and code in r['response_raw']
            if code=='42S02': assert 'user_course_schedule' in r['response_raw'].lower()
            else: assert '对象不存在' in b['message']

def targets():
    out=[]
    for method,action in [('GET','status'),('GET','summary'),('POST','unbind')]:
        out.append(item('ai_api',method,'/api/Healthkit/'+action,BASE,evidence=BASE+'ROOT_REVIEW.md',
            mysql_state='partial-evidence-real-HTTP200-no-persisted-historical-SQL-receipt',
            dm_state='partial-evidence-real-HTTP200-no-persisted-historical-SQL-receipt',
            readback='partial-evidence-executor-stdout-only-historical-SQL-not-independently-persisted',
            mysql_readback='partial-evidence-historical-SQL-stdout-only',dm_readback='partial-evidence-historical-SQL-stdout-only',
            success_case='partial-evidence-fixed-expired-binding-and-unbind-only',
            parity='partial-evidence-full-business-JSON-equal-except-trace-id-last-sync-at-retained',
            cleanup='historical-executor-reported-own-binding-and-token-absent-not-new-replay'))
    for action in ['create','update']:
        out.append(item('ai_api','POST','/api/user.CourseSchedule/'+action,BASE,evidence=BASE+'COURSE_SCHEMA_RED_BC.md',
            mysql_state='tested-fail-shared-missing-user-course-schedule-table',
            dm_state='tested-fail-shared-missing-user-course-schedule-table',
            readback='not-tested-positive-write-blocked-by-missing-table',
            mysql_readback='not-tested-positive-missing-table',dm_readback='not-tested-positive-missing-table',
            success_case='not-tested-shared-missing-table',
            parity='shared-failure-MySQL42S02-DM7086-not-a-positive-business-pass'))
    return out

if __name__=='__main__':
    audit=HERE/'integration-20261012-batch109.json'
    assert not audit.exists(),'Preserve original transition'
    tool.main(targets(),audit,verify)
