#!/usr/bin/env python3
"""Root one-time evidence integration of three real nutrition survey writers."""
import json
from pathlib import Path
import subprocess
import sys
import integrate_20261010 as tool
from integrate_20261011_batches40_42 import sha
from integrate_20261011_batches46_48 import item

BASE=tool.AI+'parallel-ai-investigate-write3-20261011/'
FINISH=BASE+'finish-phase/'
RUNNER='''import runpy,sys
from pathlib import Path
from unittest.mock import patch
root=Path(sys.argv[1]);sys.path.insert(0,str(root))
def check_only(path,data,*args,**kwargs):
 assert path.is_file() and path.read_text()==data,'sealed derived content changed: '+str(path)
 return len(data)
with patch.object(Path,'write_text',check_only):runpy.run_path(str(root/'test_verify.py'),run_name='__main__')
'''

def verify():
    base=tool.ROOT/BASE;root=tool.ROOT/FINISH
    assert sha(base/'first-phase/seal.json')=='0adcd1622d73000b9d155c1a4838b1512d5e37038aaf4ff2b44859f663134e48'
    old=tool.load(BASE+'first-phase/seal.json');assert len(old['files'])==74
    for name,record in old['files'].items():
        relative=Path(name);assert not relative.is_absolute() and '..' not in relative.parts
        path=base/relative;assert path.is_file() and not path.is_symlink()
        assert path.stat().st_size==record['bytes'] and sha(path)==record['sha256']
    assert sha(root/'finish-seal.json')=='4e7d2a43e55704eb9ad691bb0afa689bb5ce9773896704f6c83bdea31bda41a2'
    manifest=tool.load(FINISH+'finish-seal.json');assert len(manifest['files'])==160
    result=subprocess.run([sys.executable,'-B',str(root/'seal.py'),'--verify'],capture_output=True,text=True)
    assert result.returncode==0,result.stderr
    assert json.loads(result.stdout)['SHA_bytes_modes_nolink_exact']
    result=subprocess.run([sys.executable,'-B',str(root/'verify.py'),'--verify'],capture_output=True,text=True)
    assert result.returncode==0,result.stderr
    report=json.loads(result.stdout)
    assert report['assertions']==29829 and report['HTTP_total']==48 and report['full_final_DTO_dual_equal']
    assert report['B_attempts']=={'INSERT':23,'UPDATE':10,'DELETE':3}
    assert report['C_attempts']=={'INSERT':25,'UPDATE':7,'DELETE':3}
    result=subprocess.run([sys.executable,'-B','-c',RUNNER,str(root)],capture_output=True,text=True)
    assert result.returncode==0,result.stderr
    negative=json.loads(result.stdout)
    assert negative['negative_cases']==11 and negative['all_rejected'] and negative['final_green_assertions']==29828
    assert sha(tool.ROOT.parent/'zhctproject/ai_api/app/store/model/nutrition/NutritionLack.php')==manifest['final_model_sha256']
    for name,record in manifest['files'].items():
        assert sha(root/name)==record['sha256']

def targets():
    return [item('ai_api','POST','/store/investigate.NutritionLack/'+action,FINISH,
        terminal='PC-store-only-no-terminal-alias-inferred',
        risk='owned-real-survey-create-update-soft-and-hard-delete-full-readback-real-transactions',
        parity='partial-48-real-HTTP-full-final-three-DTO-typed-parity-B-original-raw-control-unchanged-outside-trace',
        boundary_empty_min_max='partial-cross-tenant-and-missing-Staff-DML0-default-missing-allergy-and-camel-text-first-write-tested',
        cleanup='marked-survey-rows-retained-own-workers-ports-cache-tokens-and-clones-cleared-no-index-before-after-proof')
        for action in ['setProblem','setMeals','setFood']]

if __name__=='__main__':
    audit=Path(__file__).with_name('integration-20261011-batch73.json')
    assert not audit.exists(),'Preserve original transition audit'
    tool.main(targets(),audit,verify)
