"""End-to-end test of CarePulse IoT on the local dev server."""
import re, sys, time, hmac, hashlib, base64, struct, json, subprocess
import requests

BASE = "http://localhost:8080"
FAILS = []
BAD = re.compile(r"(Warning:|Notice:|Deprecated:|Fatal error|Something went wrong|Uncaught|Stack trace)")

def totp(secret):
    s = secret.replace(" ", "").upper()
    s += "=" * (-len(s) % 8)
    key = base64.b32decode(s)
    msg = struct.pack(">Q", int(time.time()) // 30)
    h = hmac.new(key, msg, hashlib.sha1).digest()
    o = h[19] & 15
    return "%06d" % ((struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000)

def check(resp, label, code=200, contains=None):
    ok = resp.status_code == code
    body = resp.text
    if BAD.search(body):
        ok = False
        m = BAD.search(body)
        snippet = body[max(0, m.start()-200):m.start()+400]
        label += " | " + re.sub(r"<[^>]+>", " ", snippet)[:500]
    if contains and contains not in body:
        ok = False
        label += f" | missing '{contains}'"
    print(("PASS " if ok else "FAIL ") + f"{resp.status_code} {label}")
    if not ok:
        FAILS.append(label)
    return resp

def csrf(html):
    m = re.search(r'name="_csrf" value="([^"]+)"', html)
    return m.group(1) if m else ""

# ---------------- Level 1 ----------------
p = requests.Session()
r = p.get(BASE + "/platform/login"); t = csrf(r.text)
r = p.post(BASE + "/platform/login", data={"_csrf": t, "email": "owner@caresoft.co.in", "password": "Test@12345abc"})
check(r, "platform login -> 2fa setup", contains="Set up 2-step")
secret = re.search(r'class="code">([A-Z2-7 ]+)<', r.text).group(1)
r = p.post(BASE + "/platform/2fa/setup", data={"_csrf": csrf(r.text), "code": totp(secret)})
check(r, "platform 2fa enabled -> overview", contains="Platform overview")
for path in ["/platform", "/platform/clients", "/platform/models", "/platform/models/new", "/platform/plans", "/platform/leads", "/platform/users", "/platform/settings", "/platform/migrations", "/platform/audit", "/platform/clients/new", "/platform/leads.csv"]:
    check(p.get(BASE + path), "GET " + path)
cid = re.search(r'/platform/clients/(\d+)"><b>Caresoft Demo', p.get(BASE + "/platform/clients").text).group(1)
check(p.get(BASE + f"/platform/clients/{cid}"), "client detail", contains="cp_client_demo")
# onboard new client
r = p.get(BASE + "/platform/clients/new")
r = p.post(BASE + "/platform/clients/new", data={"_csrf": csrf(r.text), "name": "Shiva Test Hospital", "code": "SHIVA", "org_type": "hospital", "city": "Pune", "beds": "80",
    "plan_id": "1", "status": "trial", "trial_ends": "2026-12-31", "his_type": "caresoft", "domain": "shiva.localtest.me", "admin_name": "Shiva Admin", "admin_email": "admin@shiva.test", "send_welcome": "1"})
check(r, "provision client SHIVA", contains="cp_client_shiva")
shiva_pwd = re.search(r'Temporary password: <span class="code">([^<]+)<', r.text).group(1)
sid = re.search(r'/platform/clients/(\d+)/domain', r.text).group(1)
r = p.post(BASE + f"/platform/clients/{sid}/domain", data={"_csrf": csrf(r.text), "domain": "monitor.shiva.localtest.me"})
check(r, "map extra domain", contains="monitor.shiva.localtest.me")
# settings save
r = p.get(BASE + "/platform/settings")
r = p.post(BASE + "/platform/settings", data={"_csrf": csrf(r.text), "email_provider": "log", "whatsapp_provider": "log", "lead_notify_emails": "sales@caresoft.co.in", "lead_notify_whatsapp": "9800012345", "lead_autoreply": "1", "enforce_2fa_client_admin": "1", "allowed_lead_origins": "https://iot.caresoft.co.in"})
check(r, "platform settings save", contains="Settings saved")
r = p.post(BASE + "/platform/test-message", data={"_csrf": csrf(r.text), "channel": "email", "to": "x@y.com"})
check(r, "platform test message", contains="Test sent")
r = p.get(BASE + "/platform/models/new")
r = p.post(BASE + "/platform/models/new", data={"_csrf": csrf(r.text), "category": "bp_monitor", "manufacturer": "BPL", "model": "BPL 120/80 B1", "connection": "ble_standard", "ble_service": "1810", "parameters": "bp_sys,bp_dia,pulse", "phase": "1", "active": "1"})
check(r, "add device model", contains="BPL 120/80 B1")

# ---------------- Website lead API ----------------
site_key = subprocess.check_output(["php", "-r", "require '/home/claude/carepulse/platform/app/bootstrap.php'; echo platform_setting('lead_site_key');"]).decode().strip()
r = requests.post(BASE + "/api/v1/leads", json={"name": "Dr Kiran Rao", "organisation": "Rao Hospital", "email": "kiran@raohospital.in", "mobile": "9876543210", "city": "Nagpur", "interest": "ICU central monitoring", "form_type": "demo", "source_page": "/icu-central-monitoring/", "utm_source": "google"}, headers={"X-Site-Key": site_key})
check(r, "lead API", contains='"ok":true')
r = requests.post(BASE + "/api/v1/leads", json={"name": "x"}, headers={"X-Site-Key": "bad"})
check(r, "lead API bad key -> 401", code=401)
check(p.get(BASE + "/platform/leads"), "leads list shows lead", contains="Rao Hospital")

# ---------------- Level 2/3 DEMO ----------------
c = requests.Session()
r = c.get(BASE + "/login");
r = c.post(BASE + "/login", data={"_csrf": csrf(r.text), "client_code": "DEMO", "email": "admin@demo.demo", "password": "Demo@12345"})
check(r, "client admin login -> forced 2fa", contains="Set up 2-step")
check(c.get(BASE + "/dashboard"), "dashboard blocked until 2fa", contains="Set up 2-step")
secret2 = re.search(r'class="code">([A-Z2-7 ]+)<', r.text).group(1)
r = c.post(BASE + "/account/2fa", data={"_csrf": csrf(r.text), "code": totp(secret2)})
check(r, "client admin 2fa -> dashboard", contains="Monitoring dashboard")
pages = ["/dashboard", "/dashboard/live", "/patients", "/patients?f=alerts", "/patients?f=silent", "/patients/new", "/patients/import-his", "/readings", "/readings/pending", "/alerts", "/alerts?status=all",
         "/devices", "/devices/new", "/devices/labels", "/devices/models", "/gateways", "/programmes", "/programmes/new", "/programmes/1", "/reports", "/reports?days=7",
         "/settings", "/settings?tab=alerts", "/settings?tab=messaging", "/settings?tab=his", "/settings?tab=privacy", "/settings/thresholds", "/users", "/users/2", "/wards", "/audit", "/notifications", "/account"]
for path in pages:
    check(c.get(BASE + path), "GET " + path)
for exp in ["readings", "alerts", "adherence", "devices"]:
    check(c.get(BASE + "/reports/export/" + exp), "export " + exp)
pid = re.search(r'href="/patients/(\d+)"><b>Suresh Patil', c.get(BASE + "/patients?q=Suresh").text).group(1)
for path in [f"/patients/{pid}", f"/patients/{pid}/edit", f"/patients/{pid}/report?days=14", f"/patients/{pid}/enrol", f"/patients/{pid}/consent", f"/patients/{pid}/thresholds", f"/patients/{pid}/reading", f"/patients/{pid}/photo"]:
    check(c.get(BASE + path), "GET " + path)
j = c.get(BASE + f"/patients/{pid}/trend.json?param=bp&days=7").json()
print("PASS trend json" if len(j["series"]) == 2 and len(j["series"][0]["points"]) > 5 else "FAIL trend json")
aid = re.search(r'/alerts/(\d+)"', c.get(BASE + "/alerts").text).group(1)
check(c.get(BASE + f"/alerts/{aid}"), "alert detail", contains="Timeline")
did = re.search(r'/devices/(\d+)"><b>', c.get(BASE + "/devices").text).group(1)
check(c.get(BASE + f"/devices/{did}"), "device detail", contains="QR label")
check(c.get(BASE + f"/devices/{did}/edit"), "device edit")

# add patient + enrol + manual critical reading
r = c.get(BASE + "/patients/new")
r = c.post(BASE + "/patients/new", data={"_csrf": csrf(r.text), "name": "Test Patient One", "uhid": "UHT0001", "gender": "M", "dob": "1960-01-01", "mobile": "9811122233", "height_cm": "170", "language": "en", "notify_patient": "1", "consent": "1", "then_enrol": "1", "caregiver_mobile": "9811122244"})
check(r, "create patient -> enrol page", contains="Enrol Test Patient One")
newpid = re.search(r'/patients/(\d+)"', r.text).group(1)
r = c.post(BASE + f"/patients/{newpid}/enrol", data={"_csrf": csrf(r.text), "programme_id": "1", "doctor_id": "2", "coordinator_id": "5", "start_date": time.strftime("%Y-%m-%d"), "welcome": "1"})
check(r, "enrol patient", contains="Enrolled in")
r = c.post(BASE + f"/patients/{newpid}/reading", data={"_csrf": csrf(r.text), "measured_at": time.strftime("%Y-%m-%dT%H:%M"), "v[bp_sys]": "192", "v[bp_dia]": "104", "v[pulse]": "88", "v[weight]": "80", "v[temp]": "99.1", "temp_unit": "F"})
check(r, "manual reading critical -> alert", contains="alert(s) raised")
check(r, "BMI auto computed", contains="BMI")
r = c.post(BASE + f"/patients/{newpid}/reading", data={"_csrf": csrf(r.text), "measured_at": time.strftime("%Y-%m-%dT%H:%M"), "v[spo2]": "130"})
check(r, "implausible value rejected", contains="Not saved")
r = c.get(BASE + f"/alerts?patient={newpid}")
naid = re.search(r'/alerts/(\d+)"', r.text).group(1)
r = c.post(BASE + f"/alerts/{naid}/ack", data={"_csrf": csrf(r.text), "note": "Calling patient"}, headers={"Referer": BASE + f"/alerts/{naid}"})
check(r, "ack alert", contains="acknowledged")
r = c.post(BASE + f"/alerts/{naid}/close", data={"_csrf": csrf(r.text), "note": ""}, headers={"Referer": BASE + f"/alerts/{naid}"})
check(r, "close critical without note refused", contains="Write what action")
r = c.post(BASE + f"/alerts/{naid}/close", data={"_csrf": csrf(r.text), "note": "Advised to take amlodipine and recheck"}, headers={"Referer": BASE + f"/alerts/{naid}"})
check(r, "close alert", contains="Alert closed")
r = c.post(BASE + f"/patients/{newpid}/review", data={"_csrf": csrf(c.get(BASE + f"/patients/{newpid}").text), "note": "Start telmisartan 40 mg", "share": "1"})
check(r, "review note", contains="Review note saved")
r = c.post(BASE + f"/patients/{newpid}/send-report", data={"_csrf": csrf(r.text), "days": "7"})
check(r, "send report", contains="Summary queued")
r = c.post(BASE + f"/patients/{newpid}/thresholds", data={"_csrf": csrf(r.text), "use[bp_sys]": "1", "wl[bp_sys]": "100", "wh[bp_sys]": "150", "cl[bp_sys]": "90", "ch[bp_sys]": "200"})
check(r, "patient thresholds", contains="Patient-specific alert limits saved")
r = c.post(BASE + f"/patients/{newpid}/portal-invite", data={"_csrf": csrf(r.text)})
check(r, "portal invite", contains="App link sent")

# register device + bind
r = c.get(BASE + "/devices/new")
r = c.post(BASE + "/devices/new", data={"_csrf": csrf(r.text), "model_id": "2", "serial_no": "OMR-778899", "mac": "aa:bb:cc:dd:ee:01", "ownership": "patient_kit", "status": "in_stock"})
check(r, "register device", contains="Device registered")
ndid = re.search(r'/devices/(\d+)/edit', r.text).group(1)
r = c.post(BASE + f"/devices/{ndid}/bind", data={"_csrf": csrf(r.text), "patient_id": newpid, "return": "device"})
check(r, "bind device", contains="Device bound")
check(c.get(BASE + "/devices/labels?ids=" + ndid), "labels for device")
check(c.get(BASE + "/scan/CP" + ndid.zfill(5)), "scan QR tag", contains="QR label")

# gateway pairing + API readings
r = c.get(BASE + "/gateways")
r = c.post(BASE + "/gateways/new", data={"_csrf": csrf(r.text), "gw_type": "android", "name": "Test patient phone", "patient_id": newpid})
check(r, "create pairing code", contains="Pair")
code = re.search(r'class="big-code">([A-Z0-9-]+)<', r.text).group(1)
r = requests.post(BASE + "/api/v1/gateway/pair", json={"code": code, "device_info": "Pixel 8 Android 15", "app_version": "1.0.0", "platform": "android"})
check(r, "API pair", contains='"token"')
tok = r.json()["token"]
H = {"Authorization": "Bearer " + tok}
check(requests.get(BASE + "/api/v1/gateway/config", headers=H), "API config", contains='"schedule"')
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"mac": "AA:BB:CC:DD:EE:01", "battery": 77}, "readings": [{"param": "bp_sys", "value": 128, "unit": "mmHg", "measured_at": time.strftime("%Y-%m-%dT%H:%M:%S+05:30")}, {"param": "bp_dia", "value": 82}, {"param": "pulse", "value": 72}]})
check(r, "API readings known device", contains='"saved":3')
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"mac": "11:22:33:44:55:66", "ble_service": "1822", "manufacturer": "Contec", "model": "CMS50D-BT"}, "readings": [{"param": "spo2", "value": 86}, {"param": "pulse", "value": 112}]})
check(r, "API readings auto-register + critical alert", contains='"severity":"critical"')
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"batches": [{"device": {"mac": "11:22:33:44:55:66"}, "readings": [{"param": "temp", "value": 101.2, "unit": "[degF]", "measured_at": int(time.time()) - 3600}]}, {"readings": [{"param": "glucose", "value": 7.2, "unit": "mmol/L"}]}]})
check(r, "API batch upload + unit conversion", contains='"results"')
print("   ", r.text[:300])
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"mac": "11:22:33:44:55:66"}, "readings": [{"param": "spo2", "value": 86, "measured_at": int(time.time())}]})
r2 = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"mac": "11:22:33:44:55:66"}, "readings": [{"param": "spo2", "value": 86, "measured_at": int(time.time())}]})
check(r2, "API duplicate detection", contains='"duplicates":1')
check(requests.post(BASE + "/api/v1/gateway/heartbeat", headers=H, json={"battery": 55, "devices": [{"mac": "AA:BB:CC:DD:EE:01", "battery": 60}]}), "API heartbeat")
check(requests.get(BASE + "/api/v1/gateway/config", headers={"Authorization": "Bearer cpg_DEMO_deadbeefxxxxxxxxxxxxxxxxxxxxxxx"}), "API bad token -> 401", code=401)
check(requests.get(BASE + "/api/v1/device-models", headers=H), "API device models")
check(requests.get(BASE + "/api/v1/parameters"), "API parameters")

# Adapter API key (shared) -> unassigned reading -> pending -> assign
r = c.get(BASE + "/gateways")
r = c.post(BASE + "/gateways/new", data={"_csrf": csrf(r.text), "gw_type": "api", "name": "Acme OEM cloud"})
akey = re.search(r'class="code" style="font-size:14px">([^<]+)<', r.text).group(1)
r = requests.post(BASE + "/api/v1/readings", headers={"Authorization": "Bearer " + akey}, json={"device": {"serial": "ACME-1"}, "readings": [{"param": "weight", "value": 72.5}]})
check(r, "Adapter API unassigned", contains='"patient_assigned":false')
r = requests.post(BASE + "/api/v1/readings", headers={"Authorization": "Bearer " + akey}, json={"patient": {"uhid": "UHT0001"}, "device": {"serial": "ACME-2"}, "readings": [{"param": "weight", "value": 79.5}]})
check(r, "Adapter API patient by UHID", contains='"patient_assigned":true')
r = c.get(BASE + "/readings/pending")
check(r, "pending list has unassigned", contains="Unassigned")
ids = re.findall(r'name="ids\[\]" value="(\d+)"', r.text)
r = c.post(BASE + "/readings/pending", data={"_csrf": csrf(r.text), "ids[]": ids, "patient_id": newpid, "bind_device": "1", "action": "confirm"}, headers={"Referer": BASE + "/readings/pending"})
check(r, "confirm pending", contains="confirmed")

# photo upload (AI not configured -> manual path)
png = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==")
r = c.get(BASE + f"/patients/{newpid}/photo")
r = c.post(BASE + f"/patients/{newpid}/photo", data={"_csrf": csrf(r.text)}, files={"photo": ("bp.png", png, "image/png")})
check(r, "photo upload manual path", contains="Type the values")
phid = re.search(r'/photos/(\d+)', r.text).group(1)
check(c.get(BASE + f"/photos/{phid}"), "serve photo")

# settings saves
for tab, data in [("branding", {"display_name": "Caresoft Demo Hospital", "theme": "teal", "helpline": "02240001234"}),
                  ("alerts", {"alert_roles[]": ["coordinator", "doctor"], "alert_dedupe_minutes": "60", "notify_patient_critical": "1", "missed_reading_alerts": "1", "reminders_enabled": "1", "auto_register_devices": "1"}),
                  ("his", {"his_enabled": "1", "his_base_url": "http://localhost:9", "his_api_key": "abc", "his_push_readings": "1", "his_auto_bind_bed": "1", "new_inbound_key": "1"}),
                  ("privacy", {"allow_support_access": "1", "consent_text": "", "retention_days": "0", "photo_ai_enabled": "1"})]:
    r = c.get(BASE + "/settings?tab=" + tab)
    d = {"_csrf": csrf(r.text), "tab": tab}; d.update(data)
    r = c.post(BASE + "/settings", data=d)
    check(r, "save settings " + tab, contains="Settings saved")
    if tab == "his":
        inbound = re.search(r'New inbound key \(copy now, shown once\): <span class="code">([^<]+)<', r.text).group(1)
r = c.get(BASE + "/wards")
r = c.post(BASE + "/wards", data={"_csrf": csrf(r.text), "action": "beds", "ward_id": "2", "beds": "ICU-11-12, ISO-1"})
check(r, "add beds", contains="bed(s) added")
r = c.get(BASE + "/users")
r = c.post(BASE + "/users", data={"_csrf": csrf(r.text), "name": "Nurse Two", "email": "nurse2@demo.demo", "role": "nurse", "mobile": "9800000099"})
check(r, "add user", contains="Temporary password")
r = c.post(BASE + "/programmes/1", data={"_csrf": csrf(c.get(BASE + "/programmes/1").text), "code": "HTN", "name": "Hypertension care", "duration_days": "90", "active": "1", "pp[bp_sys][on]": "1", "pp[bp_sys][per_day]": "2", "pp[bp_sys][times]": "08:00,20:00", "pp[bp_sys][wh]": "140", "pp[bp_sys][ch]": "180", "pp[bp_dia][on]": "1", "pp[bp_dia][per_day]": "2"})
check(r, "save programme", contains="Programme saved")
r = c.post(BASE + "/settings/thresholds", data={"_csrf": csrf(c.get(BASE + "/settings/thresholds").text), "wl[spo2]": "94", "cl[spo2]": "90"})
check(r, "client thresholds", contains="saved")

# HIS ADT inbound: bedside device auto-binding
subprocess.run(["mysql", "-uroot", "cp_client_demo", "-e", "UPDATE devices SET bed_id=(SELECT id FROM beds WHERE bed_no='ICU-9') WHERE serial_no='HS5000'"])
r = requests.post(BASE + "/api/v1/his/adt", headers={"X-Client-Code": "DEMO", "X-HIS-Key": inbound}, json={"event": "admit", "patient": {"uhid": "UH999001", "patient_id": 55501, "name": "HIS Admitted Patient", "gender": "Female", "dob": "1975-02-02", "mobile": "9822233344"}, "admission": {"id": "IP-7781", "ward_code": "ICU", "bed_code": "ICU-9", "doctor": "Dr Rao"}, "consent": {"given_by": "Self"}})
check(r, "HIS ADT admit binds bedside device", contains='"bound_devices":1')
r = requests.post(BASE + "/api/v1/his/adt", headers={"X-Client-Code": "DEMO", "X-HIS-Key": inbound}, json={"event": "discharge", "patient": {"uhid": "UH999001"}})
check(r, "HIS ADT discharge", contains='"ok":true')
check(requests.post(BASE + "/api/v1/his/adt", headers={"X-Client-Code": "DEMO", "X-HIS-Key": "wrong"}, json={}), "HIS bad key -> 401", code=401)

# role checks: nurse cannot open settings
n = requests.Session()
r = n.get(BASE + "/login")
r = n.post(BASE + "/login", data={"_csrf": csrf(r.text), "client_code": "DEMO", "email": "nurse@demo.demo", "password": "Demo@12345"})
check(r, "nurse login (no forced 2fa)", contains="Monitoring dashboard")
check(n.get(BASE + "/settings"), "nurse blocked from settings", code=403)
check(n.get(BASE + "/patients"), "nurse can see patients")
b = requests.Session()
r = b.get(BASE + "/login")
r = b.post(BASE + "/login", data={"_csrf": csrf(r.text), "client_code": "DEMO", "email": "biomed@demo.demo", "password": "Demo@12345"})
check(b.get(BASE + "/patients"), "biomed blocked from patients", code=403)
check(b.get(BASE + "/devices"), "biomed sees devices")
# csrf
check(n.post(BASE + "/account", data={"name": "x"}), "missing CSRF -> 419", code=419)
# wrong password lockout message
w = requests.Session(); r = w.get(BASE + "/login")
r = w.post(BASE + "/login", data={"_csrf": csrf(r.text), "client_code": "DEMO", "email": "nurse@demo.demo", "password": "nope"})
check(r, "wrong password", contains="incorrect")

# ---------------- Patient portal ----------------
pt = requests.Session()
r = pt.get(BASE + "/my/login?c=DEMO")
check(r, "portal login page", contains="My health readings")
r = pt.post(BASE + "/my/login", data={"_csrf": csrf(r.text), "mobile": "9811122233"})
check(r, "portal OTP page", contains="Test mode OTP")
otp = re.search(r"Test mode OTP: <b>(\d{6})", r.text).group(1)
r = pt.post(BASE + "/my/verify", data={"_csrf": csrf(r.text), "otp": otp})
check(r, "portal verified -> home", contains="Hello, Test")
for path in ["/my", "/my/reading", "/my/photo", "/my/report", "/my/consent", "/my/trend.json?param=bp", "/manifest.webmanifest"]:
    check(pt.get(BASE + path), "GET " + path)
r = pt.post(BASE + "/my/reading", data={"_csrf": csrf(pt.get(BASE + "/my/reading").text), "v[bp_sys]": "150", "v[bp_dia]": "92", "v[glucose]": "110", "glucose_context": "fasting"})
check(r, "portal add reading", contains="care team")
# caregiver login
cg = requests.Session(); r = cg.get(BASE + "/my/login?c=DEMO")
r = cg.post(BASE + "/my/login", data={"_csrf": csrf(r.text), "mobile": "9811122244"})
otp = re.search(r"Test mode OTP: <b>(\d{6})", r.text).group(1)
check(cg.post(BASE + "/my/verify", data={"_csrf": csrf(r.text), "otp": otp}), "caregiver login", contains="Hello, Test")
# unknown mobile: same response, no OTP
u = requests.Session(); r = u.get(BASE + "/my/login?c=DEMO")
r = u.post(BASE + "/my/login", data={"_csrf": csrf(r.text), "mobile": "9000000001"})
check(r, "unknown mobile does not reveal", contains="If")

# ---------------- Support access + worker ----------------
r = p.get(BASE + f"/platform/clients/{cid}")
s2 = requests.Session(); s2.cookies = p.cookies
r = p.post(BASE + f"/platform/clients/{cid}/support-login", data={"_csrf": csrf(r.text), "reason": "Ticket 4411 alert config"})
check(r, "support access opens client", contains="Caresoft support session")
out = subprocess.run(["php", "/home/claude/carepulse/platform/cron/worker.php", "--force=daily"], capture_output=True, text=True)
print("WORKER:", out.stdout.strip()[:600], out.stderr.strip()[:300])
out = subprocess.run(["php", "/home/claude/carepulse/platform/cron/worker.php", "--force=hourly"], capture_output=True, text=True)
print("WORKER2:", out.stdout.strip()[:600], out.stderr.strip()[:300])

# logout
check(c.get(BASE + "/logout"), "logout", contains="Staff sign in")
print("\n%d FAILURES" % len(FAILS))
for f in FAILS: print(" -", f[:600])
