import json, pathlib, sys
HERE=pathlib.Path(__file__).resolve().parent
sys.path.insert(0,str(HERE))
from browser_boundary import evaluate_flow,evaluate_csp
fx=json.loads((HERE.parent/'fixture/baseline-browser.json').read_text())
policy=json.loads((HERE.parent/'fixture/golden-policy.json').read_text())
results=[]
for req in fx['flows']:
    r=evaluate_flow(req,policy,fx['site_map']); results.append(r)
resources=[]
for res in fx['resources']: resources.append({'id':res['id'],**evaluate_csp(res,policy)})
print(json.dumps({'synthetic_only':True,'flow_results':results,'resource_results':resources},indent=2))
expected={'PREFERENCE_UPDATE_OK':'ALLOW_STATE_CHANGE','PREFERENCE_UPDATE_MISSING_CSRF':'DENY_MISSING_CSRF','PREFERENCE_UPDATE_UNTRUSTED_ORIGIN':'DENY_ORIGIN'}
ok=all(next(x for x in results if x['flow']==k)['csrf']==v for k,v in expected.items())
ok=ok and next(x for x in results if x['flow']=='STATUS_PARTNER_CORS')['cors']['status']=='CORS_SHARED'
ok=ok and next(x for x in results if x['flow']=='STATUS_UNKNOWN_CORS')['cors']['status']=='CORS_NOT_SHARED'
ok=ok and next(x for x in resources if x['id']=='LOCAL_SCRIPT_CSP')['status']=='CSP_ALLOWED'
ok=ok and next(x for x in resources if x['id']=='REMOTE_SCRIPT_CSP_ENFORCE')['status']=='CSP_BLOCKED'
ok=ok and next(x for x in resources if x['id']=='REMOTE_SCRIPT_CSP_REPORT_ONLY')['status']=='CSP_REPORTED_NOT_BLOCKED'
raise SystemExit(0 if ok else 1)
