"""Offline integration contract / regression tests (does not replace live Portal acceptance)."""
from pathlib import Path
import json,re,subprocess
root=Path(__file__).resolve().parents[2]
router=(root/'portal/router.php').read_text()
index=(root/'public/index.php').read_text()
css=(root/'public/assets/app.css').read_text()
helper=(root/'src/helpers.php').read_text()
ui=(root/'portal/portal-ui.js').read_text()
sql=(root/'database/schema.sql').read_text()
checks={
'private peer':"['127.0.0.1','::1']" in router,
'JWT HS256 and constant-time signature':'hash_equals($expected,$sigRaw)' in router,
'jti atomic replay':'INSERT INTO portal_assertion_replay' in router,
'issuer plus subject membership':'p.oidc_issuer=? AND p.subject=?' in router,
'fail closed missing membership':'if(!$member) bx_json(403' in router,
'portal access denial with 200':"'allowed'=>(bool)$member" in router,
'origin + module csrf':"$_SERVER['HTTP_ORIGIN']" in router and 'bx_csrf($cfg,$c)' in router,
'portal csrf separate':'HTTP_X_BEXO_PORTAL_CSRF' in router,
'only explicit member mapping':'portal_identities' in router and 'confirmed' in router,
'broker resolves identity on link':"'resolve?subject='" in router,
'portal form via API':'/api/form' in router and "prefix+'/api/form'" in ui,
'standalone login retained':'attempt_login' in index,
'booking auto post retained':"UPDATE bookings SET status='posted',booking_date=?" in index,
'recurring bookings generator retained':'generate_due_bookings' in index,
'bookkeeper generate permission':"if($op==='generate'){\n            require_write();" in index,
'admin-only template edits':"require_admin();\n\n        if($op==='delete'" in index,
'standalone CSRF retained':"$_POST['csrf']" in helper,
'badge colours retained':'.badge.due-overdue' in css and '.badge.due-soon' in css,
'base tables unchanged in upgrade': 'CREATE TABLE IF NOT EXISTS portal_identities' in (root/'database/update_portal_module.php').read_text(),
'existing bookkeeping schema untouched': 'CREATE TABLE IF NOT EXISTS bookings' in sql,
'no portal credentials in zip':'GENERATE_48_RANDOM_BYTES_BASE64URL' in (root/'portal/buchhaltung.env.example').read_text(),
}
for name,ok in checks.items():print(('PASS' if ok else 'FAIL'),name)
assert all(checks.values())
php=list(root.rglob('*.php'))
for p in php:
  completed=subprocess.run(['php','-l',str(p)],capture_output=True,text=True)
  if completed.returncode:raise AssertionError(f'PHP lint failed {p}: {completed.stderr}')
print('PASS PHP syntax',len(php),'files')
subprocess.run(['node','--check',str(root/'portal/portal-ui.js')],check=True)
print('PASS JS syntax')
