import pathlib,subprocess,sys,os,json
ROOT=pathlib.Path(__file__).resolve().parents[4]
LAB=pathlib.Path(__file__).resolve().parents[1]
q=subprocess.run([sys.executable,str(LAB/'src/static_preflight_q1.py')],capture_output=True,text=True,env={**os.environ,'PYTHONDONTWRITEBYTECODE':'1'})
checks=[]
for line in q.stdout.splitlines():
    if line.startswith('PASS '): checks.append(('q1_'+line[5:].strip(),True))
    if line.startswith('FAIL '): checks.append(('q1_'+line[5:].strip(),False))
if (ROOT/'internal_verification/semantic_bundle_q2.py').is_file():
    sys.path.insert(0,str(ROOT/'internal_verification'))
    from semantic_bundle_q2 import semantic_checks
    checks+=semantic_checks(ROOT)[:14]
else:
    tool=json.loads((LAB/'toolchain-policy.json').read_text()); req=json.loads((LAB/'requirements.json').read_text()); pol=json.loads((LAB/'fixture/golden-policy.json').read_text()); ev=json.loads((LAB/'evidence/At-Rest_Encryption_and_Key_Boundary_Record_v1.template.json').read_text()); val=json.loads((LAB/'evidence/validation-status.json').read_text()); dec=json.loads((LAB/'submission/decision.template.json').read_text())
    def c(n,x): checks.append((n,bool(x)))
    c('q2_local_only',tool.get('local_only') is True)
    c('q2_network_forbidden',tool.get('network_forbidden') is True)
    c('q2_external_target_forbidden',tool.get('external_target_forbidden') is True)
    c('q2_real_key_material_forbidden',tool.get('real_key_material_forbidden') is True)
    c('q2_custom_crypto_forbidden',tool.get('custom_crypto_forbidden') is True)
    c('q2_external_key_manager_forbidden',tool.get('external_key_manager_forbidden') is True)
    c('q2_production_false',tool.get('production_proof') is False and pol.get('production_proof') is False)
    c('q2_requirements_transfer',req.get('changed_context_transfer_required') is True)
    c('q2_requirements_negative',req.get('must_preserve_negative_evidence') is True)
    c('q2_validation_unrun',val.get('status')=='NOT_RUN' and val.get('all_checks_passed') is False)
    c('q2_decision_blank',all(dec.get(k,'')=='' for k in ['bounded_decision','residual_risk','owner_acceptance']))
    c('q2_evidence_blank',ev.get('rows')==[] and ev.get('positive_evidence')==[] and ev.get('negative_evidence')==[] and ev.get('owner_acceptance')=='')
    c('q2_contexts_exact',set(pol.get('contexts',{}))=={'primary_database','backup_archive'})
    c('q2_boundary_separated',all(v.get('storage_boundary') and v.get('ciphertext_location') and v.get('key_storage_model')=='separate_key_authority' and v.get('kek_authority')!=v.get('storage_boundary') and v.get('same_compromise_path') is False for v in pol.get('contexts',{}).values()))
for n,ok in checks: print(('PASS' if ok else 'FAIL'),n)
print(f'SUMMARY {sum(x[1] for x in checks)}/{len(checks)} PASS')
raise SystemExit(0 if q.returncode==0 and all(x[1] for x in checks) else 1)
