#!/usr/bin/env python3
"""Template/station eight nonempty read branches; original schema gaps stay open."""
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-template-station-read8-20261011/'
def verify():
    root=tool.ROOT/BASE/'private-evidence'
    for name,size,pin in [('original-manifest.json',69,'0f4938c04b6c96bfc34778015b93c254527cf895c3acdda5e62d7e74e48197a8'),
                         ('final-manifest.json',101,'ec2318da93ad25a2da07505ea1f31cfb9598b428547d4f1949e5ac915ab4b54d')]:
        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']==180 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
    r=json.loads(red.stdout)
    assert r['assertions']==180 and r['failures']==['C:'+n+':full DTO/types/shape/sort/joins/counts' for n in ['templateLists','templateInfo','stationLists','stationInfo']]
    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=oracle_queries=leaf=0
    for lane in ['B','C']:
        for suffix in ['', '-retest']:
            p=root/(lane+'-http'+suffix)/('private-retest-wire.jsonl' if suffix else 'private-wire.jsonl')
            wires=[json.loads(line) for line in p.read_text().splitlines()]
            count+=len(wires);queries+=sum(len(w['prepared_SQL']) for w in wires)
            oracle_queries+=sum(len(w['oracle_native_SELECT']) for w in wires);leaf+=sum(w['media_leaf_calls'] for w in wires)
        clean=tool.load(BASE+'private-evidence/'+lane+'-cleanup.json')
        assert clean['port_closed'] and clean['auth_cache_config_source_runtime_removed'] and clean['original_service_alive']
        assert clean['retained_own_fixture_rows']==(2 if lane=='B' else 4)
        inserts=tool.load(BASE+'private-evidence/'+lane+'-http/private-fixture-insert.json')
        assert len(inserts)==(2 if lane=='B' else 4)
        for q in inserts:
            assert q['queryString'].lstrip().upper().startswith('INSERT ') and q['affected']==1
    assert (count,queries,oracle_queries,leaf)==(24,204,1104,11)
    for relative,digest in {
        'application/p/logic/NutritionTemplate.php':'dd86650ab7cc953d2545f6882ea0d7e454de5c2e86cd452471271074ebd30ed6',
        'application/p/logic/NutritionStation.php':'8abad48c8164bd5eee30994700504812e61ea158bd9dfc8937da318cce07888b',
    }.items():assert sha(tool.ROOT.parent/'zhctproject/store'/relative)==digest

def targets():
    paths=['/p/nutrition_template/lists','/p/nutrition_template/listsAll','/p/nutrition_template/info',
           '/p/nutrition_station/lists','/p/nutrition_station/info','/p/nutrition_station/nutritionList',
           '/p/nutrition_set/listsAll','/m/nutrition/getSport']
    result=[];_,rows,_=tool.read_csv(tool.COVERAGE)
    for path in paths:
        controller=('NutritionTemplate' if 'nutrition_template' in path else 'NutritionStation' if 'nutrition_station' in path else 'NutritionSet' if 'nutrition_set' in path else 'Nutrition')
        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/'+controller+'.php observed POST; exact UI/direct provenance in REPORT',
            parity='partial-full-per-engine-original-template-join-station-association-set-count-Sport-root-type-and-order-not-cross-snapshot-fake-equality',
            boundary_empty_min_max='partial-owned-template-natural-or-virtual-station-selected-product-aggregate-date-field-no-CRUD-real-OSS-or-UUID-unique-proof')
        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) and 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-batch62.json')
    assert not audit.exists(),'Preserve original transition audit'
    tool.main(targets(),audit,verify)
