import csv,hashlib,json,stat
from pathlib import Path
from verify_final import verify_all
from sql_audit import all_audits
P=Path(__file__).resolve().parent
result=verify_all();sql=all_audits()
for lane in 'BC':
    folder=P/'private-evidence'/f'{lane}-final'
    old=(folder/'oracle-final.jsonl').read_bytes();combined=(folder/'cleanup-oracle-combined.jsonl').read_bytes()
    assert combined.startswith(old)
    extra=combined[len(old):];records=[json.loads(x) for x in extra.splitlines() if x.strip()]
    assert len(records)==(43 if lane=='B' else 44)
    (folder/'cleanup-oracle-only.jsonl').write_bytes(extra);(folder/'cleanup-oracle-only.jsonl').chmod(0o600)
    cleanup=json.loads((P/f'resource-cleanup-{lane}.json').read_text())
    assert cleanup['independent_final36_exact'] and cleanup['retained7_full_rows_exact']==7 and cleanup['Auth_cache_files_before_cleanup']==0 and cleanup['own_source_cache_runtime_removed']
    assert cleanup['final_source_pins_verified']==6168 and all(x['absent'] for x in cleanup['original_and_final_workers_absent'].values())
    for row in records:
        assert row['queryString'].startswith('SELECT ') and row['layer']=='independent physical PDO oracle'
    assert (P/'private-evidence'/lane/'run-NA.json').is_file() and (folder/'run-FINAL.json').is_file()
    for d in (P/'private-evidence'/lane).rglob('*'):
        if d.is_file() and '/cache/' in str(d):raise AssertionError('Unexpected local Auth cache file')
with (P/'interface-ledger.csv').open('w',newline='') as f:
    w=csv.writer(f);w.writerow(['repo','method','path','status','business_evidence','limits'])
    for module in ('store','terminal'):
        w.writerow(['ai_api','GET',f'/{module}/market.Points/log','dual_business_partial','nonempty marked zero points log with full own User-avatar DTO; original DM reserved alias prepare red to accepted u alias green; source and full rows exact','one zero movement row; no real points mutation; singleton order only; no RBAC lifecycle'])
        w.writerow(['ai_api','GET',f'/{module}/user.Balance/log','dual_business_partial','nonempty marked zero balance log with full own User-avatar DTO and legacy text money/balance_after; original DM alias red to green; complete B body control','zero money only; no recharge or account update; NULL money only pure Model test; singleton order only'])
        w.writerow(['ai_api','GET',f'/{module}/User/list','dual_business_partial','one marked active zero-balance user; complete27 physical columns and avatar and null grade; original DM money number/text red to actual-connection response-only green; full B body control','zero financial values only; no user login or user write API; grade positive relation not tested'])
    w.writerow(['ai_api','GET','/store/user.UserFeedback/info','dual_business_partial','own nonempty feedback all9 physical columns plus joined marker user and decoded images and fixed status/cate labels; missing/cross tenant boundaries','one status1/cate6 feedback only; no write API; metadata images only'])
    w.writerow(['ai_api','GET','/store/user.UserFeedback/list','dual_business_partial','original fetchSql chain actually delegates paginate and executes real nonempty count/select; complete physical list DTO and JSON text images per own oracle','exact nickname is original ORM IN predicate; wildcard search and multi-row order not tested; no source patch'])
    w.writerow(['ai_api','GET','/store/dishes.Dishes/all','shared_source_failure','both real HTTP status500 fixed method not exist:think\\db\\Query->getAll; actual original Controller/service/model paths recorded','common pre-existing missing method; no DB-positive compatibility claim or invented semantics'])
    w.writerow(['ai_api','GET','/terminal/recommend.Recommend/foodCategory','no_database_static_enum','real original Controller/Auth returns complete12-item source-defined enum; HTTP business SQL0','static no-DB path; not dual_business_partial or DB adaptation coverage'])
(P/'comparison-final.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
(P/'sql-audit.json').write_text(json.dumps(sql,indent=2)+'\n')
public=[];private=[]
for path in sorted(P.rglob('*')):
    if not path.is_file() or path.is_symlink():continue
    name=str(path.relative_to(P))
    if name in ('manifest.json','MANIFEST.sha256') or '__pycache__' in path.parts:continue
    info={'path':name,'bytes':path.stat().st_size,'sha256':hashlib.sha256(path.read_bytes()).hexdigest()}
    if name.startswith('private-evidence/'):
        assert stat.S_IMODE(path.stat().st_mode)==0o600,(name,oct(stat.S_IMODE(path.stat().st_mode)))
        private.append(info)
    else:public.append(info)
manifest={'scope':'sealed original54 and necessary22 actual HTTP; eight partial one common failure one static noDB; seven marked rows retained each; no Git/shared matrix writes by owner','public':public,'private':private,'validation':{'HTTP':76,'wire':76,'B_trace_only_raw_body_unchanged':6,'strict_complete_BC_pairs':6,'original_C_failures_retained':16,'final_BC_complete_DTO_passes':22,'all_original_source_pins':6168,'Root_only_changed_models':6,'pure_Python_tests':4,'Python_rejected_mutations':270,'PHP_SQL_gate_assertions':26,'PHP_request_gate_assertions':7},'private_permissions':'all retained files0600; dirs0700; no Auth/cache/headerful reports; environment values not stored'}
(P/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
(P/'MANIFEST.sha256').write_text(''.join(f"{x['sha256']}  {x['path']}\n" for x in public))
print(json.dumps({'public_files':len(public),'private_files':len(private),'HTTP':76,'wire':76,'seven_rows_retained_each':True,'public_manifest_SHA':hashlib.sha256((P/'MANIFEST.sha256').read_bytes()).hexdigest()}))
