#!/usr/bin/env python3
"""Ten bounded nutrition product reads, four date defects narrowly corrected."""
import json
from pathlib import Path
import subprocess
import sys
import integrate_20261010 as tool
from integrate_20261011_batches40_42 import private_files, run, sha
from integrate_20261011_batches46_48 import item

BASE=tool.STORE+'parallel-store-nutrition-product-read10-20261011/'
def verify():
    root=tool.ROOT/BASE/'private-evidence'
    for name,size,pin in [('original-manifest.json',62,'fd921ae7592ff1fef5aa2feb4f19a510591132161a2e8207db7f5d5cade3b87e'),
                         ('final-manifest.json',92,'a944cff7a378b25dccbe77e92ff9aca5ac81d370200408bc1996c745011ad5d9')]:
        assert sha(root/name)==pin
        files=tool.load(BASE+'private-evidence/'+name);assert len(files)==size
        private_files(root,files)
        for n,r in files.items():assert (root/n).stat().st_size==r['bytes']
    native=json.loads(run(BASE,sys.executable,'verify-http.py','--native-date'))
    assert native['passed'] and native['assertions']==224 and not native['failures']
    red=subprocess.run([sys.executable,'verify-http.py'],cwd=tool.ROOT/BASE,capture_output=True,text=True)
    assert red.returncode==2 and not red.stderr
    result=json.loads(red.stdout)
    assert result['assertions']==224 and result['failures']==['C:'+n+':full DTO/types/shape/sort/native source' for n in ['pLists','pInfo','mLists','mInfo']]
    final=json.loads(run(BASE,sys.executable,'verify-http.py','--suffix=-retest'))
    assert final['passed'] and final['assertions']==104 and not final['failures']
    run(BASE,sys.executable,'-m','unittest','discover','-p','test_oracle.py')
    count=queries=leaf=0
    for lane in ['B','C']:
        for suffix in ['', '-retest']:
            f=root/(lane+'-http'+suffix)/('private-retest-wire.jsonl' if suffix else 'private-wire.jsonl')
            records=[json.loads(line) for line in f.read_text().splitlines()]
            count+=len(records);queries+=sum(len(r['prepared_SQL']) for r in records);leaf+=sum(r['media_leaf_calls'] for r in records)
        c=tool.load(BASE+'private-evidence/'+lane+'-cleanup.json')
        assert c['port_closed'] and c['runtime_auth_cache_config_source_removed'] and c['original_service_alive']
        assert c['retained_own_fixture_rows']==(0 if lane=='B' else 1)
    assert (count,queries,leaf)==(28,274,23)
    inserted=tool.load(BASE+'private-evidence/C-http/private-fixture-insert.json')
    assert set(inserted)=={'queryString','bindings','affected'} and inserted['affected']==1
    assert inserted['queryString'].lstrip().upper().startswith('INSERT ') and len(inserted['bindings'])==33
    for relative,digest in {
        'application/p/logic/Nutrition.php':'8a53cfd449a77b60461cd316e922a71aac6e28e1407ee25c4038abcffeab7837',
        'application/m/logic/Nutrition.php':'f98219d485b80624c6b0a9ee32b389845e03e1bec67d97e84b857e7a9e809b68',
    }.items():assert sha(tool.ROOT.parent/'zhctproject/store'/relative)==digest

def targets():
    paths=[f'/{side}/nutrition/{action}' for side in ['p','m'] for action in ['lists','info','useTimeList','supplierList']]
    paths+=['/m/nutrition/product','/m/nutrition/NutritionUseTimeGroup']
    result=[];_,rows,_=tool.read_csv(tool.COVERAGE)
    for path in paths:
        target=item('store','POST',path,BASE,
            runtime_observed_method='POST',runtime_inventory_scope='controller-direct-http-observed',
            runtime_direct_http_proof=BASE+'REPORT.md',
            runtime_controller_source='application/'+path.split('/')[1]+'/controller/Nutrition.php actual POST; UI versus direct provenance in REPORT',
            parity='partial-own-source-full-product-associated-dictionaries-FLOAT-null-group-types-no-cross-snapshot-full-body-equality',
            boundary_empty_min_max='partial-one-exact-keyword-product-no-random-multirow-no-recommend-or-CRUD-no-real-OSS')
        matches=[r for r in rows if r['repo'] in ['store','unreviewed'] and tool.norm(r['route_or_command'])==tool.norm(path) and r['method'] in ['POST','*']]
        if not matches:target['register_new_runtime_key']=True
        else:
            assert all(r['repo']=='unreviewed' for r in matches)
            assert len({r['source'] for r in matches})==1
            target.update(from_repo='unreviewed',from_source=matches[0]['source'])
        result.append(target)
    return result

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