#!/usr/bin/env python3
"""Close the observed Plain overflow defect with new real B/C vectors."""
import hashlib
import json
from pathlib import Path
import stat
import subprocess
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

PARENT=tool.STORE+'parallel-store-nutrition-plain-scalar-20261011/'
BASE=PARENT+'repaired-new-vectors/'

def sealed(relative,pin,count):
    root=tool.ROOT/relative
    manifest=root/'manifest.json'
    assert hashlib.sha256(manifest.read_bytes()).hexdigest()==pin
    records=json.loads(manifest.read_text())['assets']
    assert len(records)==count
    for record in records:
        rel=Path(record['file'])
        assert not rel.is_absolute() and '..' not in rel.parts
        path=root/rel
        assert not path.is_symlink() and path.is_file()
        body=path.read_bytes()
        assert len(body)==record['bytes'] and hashlib.sha256(body).hexdigest()==record['sha256']
        assert format(stat.S_IMODE(path.stat().st_mode),'04o')==record['mode']
    for lane in ['B','C']:assert stat.S_IMODE((root/'private'/lane).stat().st_mode)==0o700

def verify():
    sealed(PARENT,'438ce8a9af8b9ac88587987c49e2b23d3856830f0d44318bbd3799f014d56758',110)
    sealed(BASE,'df7e4e82a1865411a497b9739ec07fc0d86bf24a53bfdd7a43563eead6a325d9',99)
    root=tool.ROOT/BASE
    for cmd,key,count in [(['docker','exec','zhctapp_v2_0','/usr/local/php7.3/bin/php',
                           '/workspace/zhct/zhctprompt/'+BASE+'verify.php'],'assertions',1377),
                          (['node',str(root/'verify-dependencies.mjs')],'checks',2764)]:
        result=subprocess.run(cmd,capture_output=True,text=True)
        assert result.returncode==0,result.stderr
        report=json.loads(result.stdout)
        assert report[key]==count
        if key=='assertions':
            assert report['mutations_rejected']==12
            for lane in ['B','C']:
                assert report['lanes'][lane]['HTTP']==6
                assert report['lanes'][lane]['target_UPDATE_attempts']==3
        else:assert report['actual_included_records']==1131
    old=json.loads((tool.ROOT/PARENT/'source-lock.json').read_text())
    new=json.loads((root/'source-lock.json').read_text())
    helper='common/service/NutritionPlainFloatWeight.php'
    assert set(old)==set(new) and len(new)==959
    assert {p for p in new if old[p]!=new[p]}=={helper}
    assert old[helper]=='4365553757a84ecc1fe0a79fe7360a2e5624b0360b350ad1f5b096adbf37f121'
    assert new[helper]=='2e9db900b7f88dd32ccd6c6ebaff208cb48324ca61be43369fa2351e705f9993'
    for lane in ['B','C']:
        receipt=json.loads((tool.ROOT/PARENT/'private'/lane/'resource-check.json').read_text())
        actual=receipt['runtime_actual_fileset_excluding_this_receipt']
        captured={p.removeprefix('source/application/'):r['sha256'] for p,r in actual.items() if p.startswith('source/application/')}
        assert captured==old,'Original HTTP remains tied to original complete source'

def targets():
    return [item('store','POST','/m/nutrition/update',BASE,
        risk='owned-plain-FLOAT-string-overflow-clamp32-only-actual-native-HTTP-regression',
        parity='partial-new-positive-negative-overflow-and-legal-finish-full-DTO-physical-bits-equal-old-failure-retained',
        invalid_type='partial-original-prefix-validator-rejection-preserved-no-broad-new-rejection',
        boundary_empty_min_max='partial-new-1e998-minus1e999-and-12.348-native-bits-and-DTO-pass-no-all-scalar-claim'),
        item('store','POST','/m/nutrition/info',BASE,evidence_only=True,
             risk='readonly-own-complete-DTO-physical-FLOAT-six-significant-digit-contract')]

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