#!/usr/bin/env python3
import hashlib
import json
import pathlib
import sys
from verify_next6 import load,verify,MAIN,DINING

here=pathlib.Path(__file__).resolve().parent
roots={'B':pathlib.Path(sys.argv[1]),'C':pathlib.Path(sys.argv[2])}
b,c=load(roots['B']),load(roots['C'])
result=verify(b,c)
ledger={}
manifest={}
for lane,data in [('B',b),('C',c)]:
    stages=[('',MAIN),('dining-',DINING)] if lane=='B' else [('green-',MAIN),('dining-green-',DINING)]
    cases=[]
    for prefix,names in stages:
        report=data[prefix+'report'];responses=data[prefix+'responses'];sources=data[prefix+'source']
        for case in report['cases']:
            if case['case'] not in names:
                continue
            name=case['case'];response=responses[name];source=sources[name]
            cases.append(case|{'wire_sha256':response['wire_sha256'],'wire_bytes':response['wire_bytes'],
                'source_before_sha256':source['before']['source_digest'],'source_after_sha256':source['after']['source_digest']})
    events=[json.loads(line) for line in (roots[lane]/'queries.jsonl').read_text().splitlines() if line]
    queries=[e for e in events if e['kind']=='query_observed'];ends=[e for e in events if e['kind']=='request_end']
    ledger[lane]={'final_cases':cases,'actual_http_requests_total':len(ends),'query_observed':len(queries),
        'fingerprint_lexical_warnings':sum(e['fingerprint_lexical_warning'] is True for e in queries),
        'observed_http_dml':sum(e['operation'] in ['insert','update','delete','replace','merge'] for e in queries),
        'native_h7':data['h7-native-verification'],'cleanup':data['cleanup']}
    for name in ['H7_NATIVE_HARDWARE4','H7_NATIVE_CHECK4','H7_NATIVE_SEARCH4']:
        source=roots[lane]/('raw-'+name+'-private.json');target=here/'evidence'/lane/(name+'.json')
        target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(source.read_bytes())
        manifest[str(target.relative_to(here))]={'bytes':target.stat().st_size,'sha256':hashlib.sha256(target.read_bytes()).hexdigest()}
for name,obj in [('results.json',result),('FINAL_LEDGER.json',ledger),('MANIFEST.json',manifest)]:
    (here/name).write_text(json.dumps(obj,ensure_ascii=False,indent=2)+'\n')
print(json.dumps({'status':result['status'],'B_actual_http':ledger['B']['actual_http_requests_total'],'C_actual_http':ledger['C']['actual_http_requests_total'],'public_raw_owned_files':len(manifest)}))
