"""Phase 3 end-to-end: waveforms (API + edge HL7 NA), ventilator / pump via edge, device alarms (ORU^R40), therapy board,
CTG, strips, CGM import + AGP, wearables, stethoscope audio, teleconsult with live vitals + patient join, ABDM bundles to a mock bridge,
escalation tree with voice call + keypress acknowledgement, retention purge, simulator."""
import base64, io, json, os, re, shutil, socket, struct, subprocess, sys, threading, time, wave, http.server, datetime as _dt
import requests
sys.path.insert(0, "/home/claude/tests"); sys.path.insert(0, "/home/claude/carepulse/edge")
from e2e_lib import check, csrf, totp, FAILS, BASE
from carepulse_edge import hl7
from tests.test_hl7 import WAVE, VENT, ALARM

PLAT = "/home/claude/carepulse/platform"
EDGE_DIR = "/tmp/edge3"; shutil.rmtree(EDGE_DIR, ignore_errors=True); os.makedirs(EDGE_DIR)
sql = lambda q: subprocess.check_output(["mysql", "-uroot", "-N", "cp_client_demo", "-e", "SET time_zone='+05:30'; " + q]).decode().strip()
def ok(cond, label):
    print(("PASS " if cond else "FAIL ") + label)
    if not cond: FAILS.append(label)
def wait(fn, secs=20):
    t = time.time()
    while time.time() - t < secs:
        r = fn()
        if r: return r
        time.sleep(0.5)
    return None
def worker(*a):
    return subprocess.run(["php", "cron/worker.php", "--client=DEMO", *a], cwd=PLAT, capture_output=True, text=True).stdout

IST = _dt.timezone(_dt.timedelta(hours=5, minutes=30))
now = _dt.datetime.now(IST)
ts = now.strftime("%Y%m%d%H%M%S")
tsms = now.strftime("%Y%m%d%H%M%S.") + f"{now.microsecond // 1000:03d}+0530"

# ---------------- mock ABDM bridge ----------------
BRIDGE = []
class Bridge(http.server.BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def do_POST(self):
        n = int(self.headers.get("Content-Length", 0)); BRIDGE.append((self.path, self.headers.get("Authorization"), json.loads(self.rfile.read(n))))
        self.send_response(202); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(b'{"status":"linked"}')
threading.Thread(target=http.server.ThreadingHTTPServer(("127.0.0.1", 9098), Bridge).serve_forever, daemon=True).start()

def mllp(port, text):
    with socket.create_connection(("127.0.0.1", port), timeout=10) as s:
        s.sendall(hl7.frame(text)); buf = b""
        while b"\x1c" not in buf: buf += s.recv(4096)
    return buf.decode()

# ---------------- sign in ----------------
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"})
if "Set up 2-step" in r.text:
    sec = 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(sec)})
elif "2-step sign-in" in r.text:
    sec = sql("SELECT totp_secret FROM users WHERE email='admin@demo.demo'")
    r = c.post(BASE + "/login/2fa", data={"_csrf": csrf(r.text), "code": totp(sec)})
check(r, "admin signed in", contains="Monitoring dashboard")

harish = sql("SELECT id FROM patients WHERE uhid='IP880102'"); shabana = sql("SELECT id FROM patients WHERE uhid='IP880103'")
pooja = sql("SELECT id FROM patients WHERE uhid='IP880301'"); prakash = sql("SELECT id FROM patients WHERE uhid='IP880210'")
lak = sql("SELECT id FROM patients WHERE name='Lakshmi Iyer'"); ram = sql("SELECT id FROM patients WHERE name='Ramesh Kulkarni'"); gopal = sql("SELECT id FROM patients WHERE name='Gopal Reddy'")

# ---------------- pages ----------------
check(c.get(BASE + "/therapy"), "therapy board", contains="Noradrenaline 8 mg in 50 mL")
r = check(c.get(BASE + f"/patients/{harish}/therapy"), "patient therapy page (vent + pump)", contains="Driving pressure")
ok("Time to empty" in r.text and "Vt per kg PBW" in r.text, "derived: time to empty + Vt/kg PBW shown")
check(c.get(BASE + f"/patients/{prakash}/therapy"), "dialysis session page", contains="UF progress")
check(c.get(BASE + "/therapy?kind=dialysis"), "therapy board filtered", contains="HD 4 h")
check(c.get(BASE + "/therapy?kind=anaesthesia"), "anaesthesia workstation on board", contains="GA – sevoflurane")
check(c.get(BASE + f"/patients/{harish}/waveforms"), "live waveform viewer", contains="ECG II")
j = c.get(BASE + f"/patients/{harish}/waveforms.json?ch=ecg_ii,pleth,paw").json()
ok(j["ok"] and len(j["channels"].get("ecg_ii", {}).get("chunks", [])) > 0 and "paw" in j["channels"], f"waveform JSON: ecg_ii chunks={len(j['channels'].get('ecg_ii', {}).get('chunks', []))}, vent paw present")
ok("peep" in j["vitals"] or "hr" in j["vitals"], "waveform JSON carries recent numerics")
check(c.get(BASE + f"/patients/{pooja}/ctg"), "CTG viewer", contains="FHR now")
j = c.get(BASE + f"/patients/{pooja}/waveforms.json?ch=ctg_fhr,ctg_toco&since={int(time.time()*1000) - 3600000}").json()
ok(sum(len(v) for _, v in j["channels"].get("ctg_fhr", {}).get("chunks", [])) >= 4 * 60 * 45, "CTG JSON returns ~50 min of FHR at 4 Hz")
check(c.get(BASE + "/strips/1"), "seeded rhythm strip", contains="Sinus tachycardia")
r = check(c.get(BASE + f"/patients/{lak}/cgm?days=14"), "CGM AGP report", contains="Time in range 70–180")
ok(re.search(r"Time below 70 / below 54</div><div class=\"v\">[\d.]+% / [\d.]+%", r.text) is not None, "CGM metrics rendered")
check(c.get(BASE + f"/patients/{ram}"), "patient page connected-care card", contains="Connected care")
check(c.get(BASE + "/consults"), "consult list")
check(c.get(BASE + "/consults/new"), "consult form", contains="Schedule teleconsult")
check(c.get(BASE + "/abdm"), "ABDM records list", contains="Home monitoring")
check(c.get(BASE + "/settings/escalation"), "escalation settings", contains="Critical patient alerts")
check(c.get(BASE + "/settings?tab=telehealth"), "telehealth settings", contains="Exotel flow")
check(c.get(BASE + "/settings?tab=alerts"), "waveform settings", contains="Keep monitor waveforms")
steth = sql("SELECT id FROM documents WHERE doc_type='audio' LIMIT 1")
check(c.get(BASE + f"/documents/{steth}"), "stethoscope player page", contains="Heart (20–200 Hz)")
rf = c.get(BASE + f"/documents/{steth}/file"); ok(rf.headers.get("Content-Type", "").startswith("audio/wav") and rf.content[:4] == b"RIFF", "stethoscope WAV served")
icu = sql("SELECT id FROM wards WHERE name='ICU'")
sj = c.get(BASE + f"/station/{icu}/data").json()
tags = {b["bed"]: b["patient"] for b in sj["beds"] if b["patient"]}
ok("ventilation" in tags["ICU-3"]["therapy"] and tags["ICU-3"]["wf"], "station tile: ventilator + live waveform flags")
check(c.get(BASE + f"/platform/settings"), "platform console still guarded", code=200)

# ABDM bundle structure
b = c.get(BASE + "/abdm/1?format=json").json()
comp = b["entry"][0]["resource"]
ok(b["type"] == "document" and comp["resourceType"] == "Composition" and comp["meta"]["profile"][0].endswith("/WellnessRecord") and comp["type"]["text"] == "Wellness Record", "WellnessRecord FHIR document bundle")
ok(any(e["resource"]["resourceType"] == "Patient" and any(i.get("value") == "91512345678901" for i in e["resource"]["identifier"]) for e in b["entry"]), "bundle Patient carries ABHA number")
ok(all(e["fullUrl"] == f'{e["resource"]["resourceType"]}/{e["resource"]["id"]}' for e in b["entry"]), "bundle fullUrls resolve to resources")

# ---------------- gateway via pairing (shared edge) ----------------
r = c.get(BASE + "/gateways")
r = c.post(BASE + "/gateways/new", data={"_csrf": csrf(r.text), "gw_type": "edge", "name": "ICU edge gateway P3"})
code = re.search(r'class="big-code">([A-Z0-9-]+)<', r.text).group(1)
out = subprocess.run([sys.executable, "-m", "carepulse_edge", "--pair", code, "--server", BASE, "--config", EDGE_DIR + "/edge.json"], cwd="/home/claude/carepulse/edge", capture_output=True, text=True)
ok("Paired with" in out.stdout, "edge --pair")
cfg = json.load(open(EDGE_DIR + "/edge.json")); TOKEN = cfg["token"]
H = {"Authorization": "Bearer " + TOKEN}

# ---------------- waveform API ----------------
start = int(time.time() * 1000) - 2000
samples = [round(0.9 if i % 200 == 0 else 0.02 * (i % 7), 3) for i in range(500)]
r = requests.post(BASE + "/api/v1/waveforms", headers=H, json={"device": {"serial": "MR-BV-1001"}, "location": {"ward_code": "ICU", "bed_code": "ICU-1"},
    "waveforms": [{"channel": "ecg_ii", "sample_rate": 250, "unit": "mV", "start": start, "samples": samples},
                  {"channel": "pleth", "sample_rate": 125, "start": start, "data_b64": base64.b64encode(struct.pack("<250h", *[i * 10 for i in range(250)])).decode(), "scale": 0.01},
                  {"channel": "bogus", "sample_rate": 100, "samples": [1, 2]},
                  {"channel": "resp", "sample_rate": 50, "start": int(time.time() * 1000) + 60000, "samples": [1, 2, 3]}]})
j = r.json()
ok(r.status_code == 200 and j["saved"] == 2 and set(j["rejected"]) == {"2", "3"} and j["patient_assigned"], f"API waveforms: 2 saved, bad channel + future start rejected ({j})")
r = requests.post(BASE + "/api/v1/waveforms", headers=H, json={"device": {"serial": "MR-BV-1001"}, "location": {"bed_code": "ICU-1"}, "waveforms": [{"channel": "ecg_ii", "sample_rate": 250, "start": start, "samples": samples}]})
ok(r.json()["saved"] == 0, "duplicate waveform chunk ignored")
p1 = sql("SELECT patient_id FROM admissions a JOIN beds b ON b.id=a.bed_id WHERE b.bed_no='ICU-1' AND a.status='admitted'")
ok(sql(f"SELECT ROUND(MAX(scale),4) FROM waveforms WHERE patient_id={p1} AND channel='pleth' AND start_ms={start}") == "0.0100", "base64 int16 chunk stored with given scale")
w = c.get(BASE + f"/patients/{p1}/waveforms.json?ch=ecg_ii&from={start}&to={start + 2000}").json()["channels"]["ecg_ii"]["chunks"]
ok(any(abs(ch[1][0] - 0.9) < 0.002 and len(ch[1]) == 500 for ch in w), "ECG samples round-trip (int16 scaling)")

# strip save
fd = {"_csrf": csrf(c.get(BASE + "/consults/new").text), "from_ms": str(int(time.time() * 1000) - 70000), "to_ms": str(int(time.time() * 1000) - 60000), "channels": "ecg_ii,pleth"}
j = c.post(BASE + f"/patients/{harish}/strips", data=fd).json()
ok(j.get("ok"), "save 10 s rhythm strip")
if j.get("ok"):
    r = check(c.get(BASE + j["url"]), "strip page with ECG paper", contains="Click two points")
    r = c.post(BASE + j["url"], data={"_csrf": csrf(r.text), "note": "Sinus rhythm, QA"}); check(r, "strip interpretation saved", contains="Sinus rhythm, QA")

# ---------------- edge: waveform NA, ventilator, pump alarm ----------------
cfg.update({"timezone": "+05:30", "data_dir": EDGE_DIR, "hl7_listeners": [{"host": "127.0.0.1", "port": 12585}], "sample_seconds": 0, "monitor_vendor": "Mindray", "waveforms": True})
json.dump(cfg, open(EDGE_DIR + "/edge.json", "w"))
edge = subprocess.Popen([sys.executable, "-m", "carepulse_edge", "--config", EDGE_DIR + "/edge.json"], cwd="/home/claude/carepulse/edge", stdout=open(EDGE_DIR + "/edge.log", "w"), stderr=subprocess.STDOUT)
time.sleep(2)
try:
    before = int(sql(f"SELECT COUNT(*) FROM waveforms WHERE patient_id={harish} AND channel='ecg_ii'"))
    a = mllp(12585, WAVE.replace("20261118103000.000+0530", tsms))
    ok("MSA|AA" in a, "edge ACKs HL7 waveform ORU")
    ok(wait(lambda: int(sql(f"SELECT COUNT(*) FROM waveforms WHERE patient_id={harish} AND channel='ecg_ii'")) > before), "edge NA waveform stored for ICU-3 patient")
    a = mllp(12585, VENT.replace("20261118103000+0530", ts + "+0530"))
    ok(wait(lambda: sql(f"SELECT COUNT(*) FROM readings WHERE patient_id={harish} AND param_code='peep' AND value=8 AND measured_at >= NOW() - INTERVAL 2 MINUTE") != "0"), "edge ventilator PEEP reading saved")
    ok(wait(lambda: sql(f"SELECT COUNT(*) FROM therapy_sessions s JOIN devices d ON d.id=s.device_id WHERE s.patient_id={harish} AND s.kind='ventilation' AND s.label='SIMV-VC' AND d.serial_no LIKE 'MINDRAY_SV800%'") != "0"), "edge started ventilation session with mode from HL7")
    a = mllp(12585, ALARM.replace("20261118103500+0530", ts + "+0530"))
    ok("MSA|AA" in a, "edge ACKs ORU^R40 alarm")
    al = wait(lambda: sql(f"SELECT CONCAT(id,':',severity,':',status) FROM alerts WHERE patient_id={shabana} AND alert_type='device_alarm' AND status='open' ORDER BY id DESC LIMIT 1"))
    ok(al and ":critical:open" in al, f"pump occlusion alarm raised as critical alert ({al})")
    aid = al.split(":")[0] if al else "0"
    ok(sql(f"SELECT escalation_policy_id IS NOT NULL FROM alerts WHERE id={aid}") == "1", "critical device alarm attached to escalation policy")
    mllp(12585, ALARM.replace("20261118103500+0530", ts + "+0530").replace("|start|", "|end|").replace("MSH|^~\\&|BBRAUN_SPACE|BBRAUN|||" + ts, "MSH|^~\\&|BBRAUN_SPACE|BBRAUN|||" + ts).replace("|A1|", "|A2|"))
    ok(wait(lambda: sql(f"SELECT status FROM alerts WHERE id={aid}") == "closed"), "alarm end at device closes the alert")
finally:
    edge.terminate(); edge.wait(5)
print("edge log tail:", open(EDGE_DIR + "/edge.log").read()[-300:].replace("\n", " | "))

# ---------------- alarms API direct ----------------
r = requests.post(BASE + "/api/v1/alarms", headers=H, json={"device": {"serial": "FMC-4008S-9917"}, "patient": {"uhid": "IP880210"}, "alarms": [{"code": "VP_HIGH", "text": "Venous pressure high", "priority": "medium"}]})
ok(r.status_code == 200 and r.json()["alarms"][0]["severity"] == "warning", "alarm API: dialysis venous pressure warning")

# ---------------- therapy via readings batch + manual therapy ----------------
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"serial": "BB-SP-5532"}, "patient": {"uhid": "IP880103"}, "therapy": {"kind": "infusion", "label": "Insulin (Actrapid) 50 IU in 50 mL"},
    "readings": [{"param": "infusion_rate", "value": 3.5, "unit": "ml/h"}, {"param": "vtbi", "value": 12}]})
ok(r.json().get("saved") == 2 and sql(f"SELECT COUNT(*) FROM therapy_sessions WHERE patient_id={shabana} AND kind='infusion' AND status='running'") == "1", "pump readings keep the same running insulin session")
r = c.get(BASE + f"/patients/{gopal}/therapy")
r = c.post(BASE + f"/patients/{gopal}/therapy", data={"_csrf": csrf(r.text), "kind": "oxygen", "d_device": "Nasal prongs", "d_flow": "2"})
check(r, "manual oxygen therapy started", contains="Oxygen therapy")
sid = sql(f"SELECT id FROM therapy_sessions WHERE patient_id={gopal} AND kind='oxygen'")
r = c.post(BASE + f"/therapy/{sid}", data={"_csrf": csrf(r.text), "action": "end", "note": "Weaned to room air"}); check(r, "therapy ended")
ok(sql(f"SELECT status FROM therapy_sessions WHERE id={sid}") == "ended", "session marked ended")

# ---------------- wearables / Health Connect history ----------------
day = (now - _dt.timedelta(days=2)).strftime("%Y-%m-%dT%H:%M:%S+05:30")
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"serial": "HC-PIXEL-QA", "manufacturer": "Health Connect", "model": "Pixel Watch"}, "patient": {"uhid": sql(f"SELECT IFNULL(uhid,'') FROM patients WHERE id={ram}") or None, "id": int(ram)},
    "history": True, "readings": [{"param": "steps", "value": 7421, "measured_at": day, "context": "wearable"}, {"param": "resting_hr", "value": 128, "measured_at": day, "context": "wearable"},
                                  {"param": "hrv_sdnn", "value": 41, "measured_at": day, "context": "wearable"}]})
j = r.json()
ok(j.get("saved") == 3 and not j.get("alerts"), f"wearable history saved without paging ({j.get('saved')} saved, alerts {j.get('alerts')})")
ok(sql(f"SELECT flag FROM readings WHERE patient_id={ram} AND param_code='resting_hr' AND value=128") == "critical", "history value still flagged")

# ---------------- CGM CSV import (LibreView + Dexcom) ----------------
base_t = now - _dt.timedelta(days=3)
lines = ["Glucose Data,Generated on,18-11-2026 10:00 UTC,Generated by,QA", "Device,Serial Number,Device Timestamp,Record Type,Historic Glucose mg/dL,Scan Glucose mg/dL,Non-numeric Rapid-Acting Insulin"]
for i in range(96):
    t = base_t + _dt.timedelta(minutes=15 * i)
    lines.append(f"FreeStyle LibreLink,QA-LIBRE-1,{t.strftime('%d-%m-%Y %H:%M')},0,{100 + (i % 20) * 6},,")
lines.append(f"FreeStyle LibreLink,QA-LIBRE-1,{base_t.strftime('%d-%m-%Y %H:%M')},1,,145,")
csvb = "\n".join(lines).encode()
r = c.get(BASE + f"/patients/{gopal}/cgm")
r = c.post(BASE + f"/patients/{gopal}/cgm/import", data={"_csrf": csrf(r.text), "date_order": "dmy"}, files={"csv": ("libre.csv", csvb, "text/csv")})
check(r, "LibreView import", contains="LibreView import: 96 new readings")
r = c.post(BASE + f"/patients/{gopal}/cgm/import", data={"_csrf": csrf(r.text), "date_order": "dmy"}, files={"csv": ("libre.csv", csvb, "text/csv")})
check(r, "LibreView re-import skips duplicates", contains="0 new readings, 96 already present")
dex = ["Index,Timestamp (YYYY-MM-DDThh:mm:ss),Event Type,Event Subtype,Patient Info,Device Info,Source Device ID,Glucose Value (mg/dL),Insulin Value (u),Carb Value (grams)",
       "1,,FirstName,,QA,,,,,", "2,,Device,,,G7,,,,"]
for i in range(30):
    t = base_t + _dt.timedelta(minutes=5 * i, hours=30)
    dex.append(f"{i+3},{t.strftime('%Y-%m-%dT%H:%M:%S')},EGV,,,,iPhone G7,{'Low' if i == 5 else 160 + i},,")
dex.append(f"99,{base_t.strftime('%Y-%m-%dT%H:%M:%S')},Calibration,,,,iPhone G7,150,,")
r = c.post(BASE + f"/patients/{gopal}/cgm/import", data={"_csrf": csrf(r.text), "date_order": "dmy"}, files={"csv": ("clarity.csv", "\n".join(dex).encode(), "text/csv")})
check(r, "Dexcom Clarity import (Low mapped, calibration skipped)", contains="Dexcom Clarity import: 30 new readings")
ok(sql(f"SELECT COUNT(*) FROM readings WHERE patient_id={gopal} AND context='cgm' AND value=40") == "1", "Dexcom 'Low' stored as 40 mg/dL")
ok(sql(f"SELECT COUNT(*) FROM alerts WHERE patient_id={gopal} AND param_code='glucose' AND raised_at > NOW() - INTERVAL 5 MINUTE") == "0", "historical CGM import did not page anyone")
check(c.get(BASE + f"/patients/{gopal}/cgm?days=7"), "CGM report after import", contains="Ambulatory glucose profile")
print(worker("--force=cgm").strip()[-200:])

# ---------------- stethoscope upload ----------------
buf = io.BytesIO(); wv = wave.open(buf, "wb"); wv.setnchannels(1); wv.setsampwidth(2); wv.setframerate(4000); wv.writeframes(b"\x00\x10" * 8000); wv.close()
r = c.get(BASE + "/documents")
r = c.post(BASE + "/documents/upload", data={"_csrf": csrf(r.text), "patient_id": gopal, "doc_type": "audio", "site": "lung_ll", "device": "Eko CORE 500"}, files={"file": ("lung.wav", buf.getvalue(), "audio/wav")})
check(r, "stethoscope upload", contains="Lung – lower left")

# ---------------- escalation + voice call ----------------
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"serial": "QA-OXI-9"}, "patient": {"id": int(ram)}, "readings": [{"param": "spo2", "value": 82}]})
aid = (r.json().get("alerts") or [{}])[0].get("id")
ok(aid and sql(f"SELECT escalation_policy_id IS NOT NULL AND escalation_next_at IS NOT NULL FROM alerts WHERE id={aid}") == "1", "critical SpO2 alert gets escalation timer")
sql(f"UPDATE alerts SET escalation_next_at = NOW() - INTERVAL 1 MINUTE WHERE id={aid}")
out = worker(); print(out.strip()[-200:])
calls = sql(f"SELECT CONCAT(token,':',status,':',provider) FROM voice_calls WHERE alert_id={aid} ORDER BY id")
ok(calls and ":calling:log" in calls, f"escalation step 1 placed voice call(s): {calls.count(':calling')}")
ok(sql(f"SELECT escalation_step FROM alerts WHERE id={aid}") == "1", "alert moved to escalation step 1")
tok = calls.split("\n")[0].split(":")[0]
r = requests.get(BASE + f"/api/v1/voice/demo/exotel/say?CustomField={tok}&CallSid=x1"); ok(r.status_code == 200 and "Press 1 to acknowledge" in r.text, "Exotel greeting text endpoint")
r = requests.get(BASE + f"/api/v1/voice/demo/exotel/digits?CustomField={tok}&digits=%221%22"); ok("acknowledged" in r.text, "keypress 1 acknowledges")
ok(sql(f"SELECT status FROM alerts WHERE id={aid}") == "acknowledged", "alert acknowledged by phone")
ok(sql(f"SELECT status FROM voice_calls WHERE token='{tok}'") == "acknowledged", "voice call marked acknowledged")
requests.post(BASE + f"/api/v1/voice/demo/{tok}/status", data={"CallStatus": "completed"})
ok(sql(f"SELECT status FROM voice_calls WHERE token='{tok}'") == "acknowledged", "status callback does not downgrade acknowledged call")
check(c.get(BASE + f"/alerts/{aid}"), "alert page shows escalation + calls", contains="Escalation")
ok(requests.get(BASE + f"/api/v1/voice/demo/{'0'*32}/say").status_code == 404, "unknown call token → 404")
# cannot attend → next step pulled forward
r = requests.post(BASE + "/api/v1/readings", headers=H, json={"device": {"serial": "QA-OXI-10"}, "patient": {"id": int(gopal)}, "readings": [{"param": "spo2", "value": 81}]})
a2 = r.json()["alerts"][0]["id"]
sql(f"UPDATE alerts SET escalation_next_at = NOW() - INTERVAL 1 MINUTE WHERE id={a2}"); worker()
t2 = sql(f"SELECT token FROM voice_calls WHERE alert_id={a2} LIMIT 1")
requests.post(BASE + f"/api/v1/voice/demo/{t2}/digits", data={"Digits": "2"})
ok(sql(f"SELECT escalation_next_at <= NOW() FROM alerts WHERE id={a2}") == "1", "keypress 2 pulls the next escalation step forward")
worker()
ok(sql(f"SELECT escalation_step FROM alerts WHERE id={a2}") == "2", "step 2 ran after decline")
# admin test call + new policy via UI
r = c.get(BASE + "/settings/escalation")
r = c.post(BASE + "/settings/escalation", data={"_csrf": csrf(r.text), "action": "policy", "name": "QA ICU policy", "match_type": "device_alarm", "min_severity": "warning", "ward_id": icu, "priority": "10", "active": "1"})
check(r, "create escalation policy", contains="QA ICU policy")
pid = sql("SELECT id FROM escalation_policies WHERE name='QA ICU policy'")
r = c.post(BASE + "/settings/escalation", data={"_csrf": csrf(r.text), "action": "step", "policy_id": pid, "step_no": "1", "delay_min": "2", "channel": "voice", "target_type": "role", "target_role": "nurse"})
check(r, "add escalation step", contains="All Nurses")
r = c.post(BASE + "/settings/escalation", data={"_csrf": csrf(r.text), "action": "test_call"}); check(r, "test call (log provider)", contains="Test call placed to")

# ---------------- teleconsult ----------------
r = c.get(BASE + f"/consults/new?patient={ram}")
doc_id = sql("SELECT id FROM users WHERE email='doctor@demo.demo'")
when = (now + _dt.timedelta(minutes=5)).strftime("%Y-%m-%dT%H:%M")
r = c.post(BASE + "/consults/new", data={"_csrf": csrf(r.text), "patient_id": ram, "doctor_id": doc_id, "scheduled_at": when, "duration_min": "15", "reason": "QA BP review", "meeting_url": "https://meet.example.org/qa-room", "notify": "1"})
check(r, "teleconsult scheduled", contains="QA BP review")
cid = sql("SELECT id FROM teleconsults WHERE reason='QA BP review'")
ok(sql(f"SELECT COUNT(*) FROM notification_queue WHERE related_type='consult' AND related_id={cid} AND channel='whatsapp'") == "1", "patient invited on WhatsApp")
tokp = sql(f"SELECT patient_token FROM teleconsults WHERE id={cid}")
r = c.post(BASE + f"/consults/{cid}", data={"_csrf": csrf(r.text), "action": "start"}); check(r, "consult started → video iframe", contains='allow="camera; microphone')
p = requests.Session()
r = check(p.get(BASE + f"/my/consult/{tokp}?c=demo"), "patient join page", contains="Join video call")
r = p.post(BASE + f"/my/consult/{tokp}/reading?c=demo", data={"_csrf": csrf(r.text), "v[bp_sys]": "152", "v[bp_dia]": "94", "v[pulse]": "88"})
check(r, "patient sends reading during call", contains="Sent to your doctor")
lj = c.get(BASE + f"/patients/{ram}/live.json?since=" + requests.utils.quote(now.strftime("%Y-%m-%d %H:%M:%S"))).json()
ok(any(v["code"] == "bp_sys" and v["v"] == "152" and v["new"] for v in lj["vitals"]), "doctor console sees the new BP live")
ok(requests.get(BASE + f"/my/consult/{'f'*32}?c=demo").status_code == 404, "bad consult token → 404")
# enable ABDM with mock bridge, then complete
r = c.get(BASE + "/settings?tab=telehealth")
r = c.post(BASE + "/settings", data={"_csrf": csrf(r.text), "tab": "telehealth", "abdm_enabled": "1", "abdm_bridge_url": "http://127.0.0.1:9098", "abdm_bridge_key": "bk-qa", "abdm_hip_id": "IN2710000999",
    "abdm_push_path": "/api/abdm/health-records", "abdm_auto_weekly": "1", "abdm_push_consults": "1", "tele_provider": "caremeet", "voice_provider": ""})
check(r, "telehealth settings saved")
r = c.get(BASE + f"/consults/{cid}")
r = c.post(BASE + f"/consults/{cid}", data={"_csrf": csrf(r.text), "action": "complete", "findings": "BP 152/94 on call", "advice": "Increase telmisartan to 80 mg", "follow_up": (now + _dt.timedelta(days=14)).strftime("%Y-%m-%d"), "share": "1"})
check(r, "consult completed → back to patient", contains="Increase telmisartan")
ok(sql(f"SELECT status FROM teleconsults WHERE id={cid}") == "completed", "consult status completed")
rec = sql(f"SELECT CONCAT(id,':',status) FROM abdm_records WHERE source_ref='consult:{cid}'")
ok(rec and rec.endswith(":queued"), f"OPConsultation record queued ({rec})")
out = worker(); print(out.strip()[-200:])
ok(wait(lambda: sql(f"SELECT status FROM abdm_records WHERE source_ref='consult:{cid}'") == "sent", 10), "ABDM record delivered to bridge")
ok(sql("SELECT status FROM abdm_records WHERE id=1") == "sent", "queued wellness record also delivered")
oc = [x for x in BRIDGE if x[2]["hi_type"] == "OPConsultation"]
ok(oc and oc[0][1] == "Bearer bk-qa" and oc[0][2]["hip_id"] == "IN2710000999" and oc[0][2]["patient"]["abha_number"] == "91512345678901", "bridge got HIP ID, ABHA and bearer key")
if oc:
    cb = oc[0][2]["bundle"]; comp = cb["entry"][0]["resource"]
    ok(comp["type"]["coding"][0]["code"] == "371530004" and comp["meta"]["profile"][0].endswith("/OPConsultRecord"), "OPConsultRecord composition (SNOMED 371530004)")
    titles = [s["title"] for s in comp["section"]]
    ok({"Chief complaints", "Physical examination", "Plan / advice", "Follow up"} <= set(titles), f"OPConsult sections {titles}")
    refs = {f'{e["resource"]["resourceType"]}/{e["resource"]["id"]}' for e in cb["entry"]}
    ok(all(en["reference"] in refs for s in comp["section"] for en in s["entry"]), "every section entry resolves inside the bundle")
# share to ABHA from patient page
r = c.get(BASE + f"/patients/{ram}")
r = c.post(BASE + f"/patients/{ram}/abdm", data={"_csrf": csrf(r.text), "from": (now - _dt.timedelta(days=14)).strftime("%Y-%m-%d"), "to": now.strftime("%Y-%m-%d")})
check(r, "share last 14 days to ABHA", contains="queued for the patient")

# ---------------- retention + simulator ----------------
sql("UPDATE settings SET v='1' WHERE k='waveform_retention_hours'") if sql("SELECT COUNT(*) FROM settings WHERE k='waveform_retention_hours'") != "0" else sql("INSERT INTO settings (k, v) VALUES ('waveform_retention_hours','1')")
sql(f"UPDATE waveforms SET start_ms = start_ms - 7200000 WHERE patient_id={p1} AND channel='pleth'")
out = worker("--force=wfpurge"); print(out.strip()[-160:])
ok(sql(f"SELECT COUNT(*) FROM waveforms WHERE patient_id={p1} AND channel='pleth'") == "0", "old monitor waveforms purged by retention")
ok(sql("SELECT COUNT(*) FROM waveforms WHERE channel='ctg_fhr'") != "0", "CTG traces kept (retention 0 = keep)")
sql("UPDATE settings SET v='72' WHERE k='waveform_retention_hours'")
n0 = int(sql("SELECT COUNT(*) FROM waveforms"))
sim = subprocess.run(["php", "tools/waveform_sim.php", "--client=DEMO", "--seconds=3"], cwd=PLAT, capture_output=True, text=True, timeout=60)
ok(sim.returncode == 0 and int(sql("SELECT COUNT(*) FROM waveforms")) > n0 and "Warning" not in sim.stderr + sim.stdout, "waveform simulator streams without errors")

print("\n" + ("0 FAILURES" if not FAILS else f"{len(FAILS)} FAILURES:\n - " + "\n - ".join(FAILS)))
