"""Phase 2 end-to-end: edge gateway (HL7 ORU + ADT in, ADT out, Modbus, ECG folder) → platform → station, NEWS2, charting → FHIR to HIS."""
import json, os, re, socket, socketserver, struct, subprocess, sys, threading, time, shutil, http.server
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 MINDRAY, PHILIPS, ADT
import datetime as _dt
_now = _dt.datetime.now(_dt.timezone(_dt.timedelta(hours=5, minutes=30))).strftime("%Y%m%d%H%M%S")
MINDRAY = MINDRAY.replace("20261118103000", _now).replace("ICU-3", "ICU-8"); PHILIPS = PHILIPS.replace("20261118104500", _now); ADT = ADT.replace("ICU-3", "ICU-8")

EDGE_DIR = "/tmp/edge"; shutil.rmtree(EDGE_DIR, ignore_errors=True); os.makedirs(EDGE_DIR + "/ecg")
sql = lambda q: subprocess.check_output(["mysql", "-uroot", "-N", "cp_client_demo", "-e", q]).decode().strip()

# ---------------- mocks: HIS (HTTP), monitor central station (MLLP), Modbus sensor ----------------
HIS_POSTS = []
class HIS(http.server.BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def do_GET(self):
        body = json.dumps({"patient": {"uhid": "UH555", "patient_id": 555, "name": "Lookup Person", "gender": "F", "dob": "1970-01-01"}}).encode()
        self.send_response(200); self.send_header("Content-Type", "application/json"); self.end_headers(); self.wfile.write(body)
    def do_POST(self):
        n = int(self.headers.get("Content-Length", 0)); HIS_POSTS.append((self.headers.get("Content-Type"), json.loads(self.rfile.read(n))))
        self.send_response(201); self.end_headers(); self.wfile.write(b"{}")
threading.Thread(target=http.server.ThreadingHTTPServer(("127.0.0.1", 9099), HIS).serve_forever, daemon=True).start()

MONITOR_MSGS = []
class Monitor(socketserver.BaseRequestHandler):
    def handle(self):
        buf = b""
        while True:
            c = self.request.recv(4096)
            if not c: break
            buf += c
            if b"\x1c" in buf:
                m = hl7.parse(buf); MONITOR_MSGS.append(buf.decode()); self.request.sendall(hl7.frame(hl7.ack(m))); buf = b""
socketserver.ThreadingTCPServer.allow_reuse_address = True
threading.Thread(target=socketserver.ThreadingTCPServer(("127.0.0.1", 12576), Monitor).serve_forever, daemon=True).start()

FRIDGE = {"v": 45}
class Modbus(socketserver.BaseRequestHandler):
    def handle(self):
        hdr = self.request.recv(7)
        if len(hdr) < 7: return
        tid, pid, ln, unit = struct.unpack(">HHHB", hdr)
        fn, addr, cnt = struct.unpack(">BHH", self.request.recv(ln - 1))
        regs = [FRIDGE["v"] & 0xFFFF] * cnt
        pdu = struct.pack(">BB", fn, cnt * 2) + struct.pack(f">{cnt}H", *regs)
        self.request.sendall(struct.pack(">HHHB", tid, 0, len(pdu) + 1, unit) + pdu)
threading.Thread(target=socketserver.ThreadingTCPServer(("127.0.0.1", 15020), Modbus).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()

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

# ---------------- admin login ----------------
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 "2-step sign-in" in r.text and "Set up" not 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)})
elif "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)})
check(r, "admin signed in", contains="Monitoring dashboard")

# HIS settings → FHIR
r = c.get(BASE + "/settings?tab=his")
r = c.post(BASE + "/settings", data={"_csrf": csrf(r.text), "tab": "his", "his_enabled": "1", "his_format": "fhir", "his_base_url": "http://localhost:9099", "his_api_key": "k1",
    "his_patient_path": "/api/carepulse/patients/{uhid}", "his_vitals_path": "/api/carepulse/vitals", "his_push_readings": "1", "his_auto_bind_bed": "1"})
check(r, "HIS settings FHIR", contains="Settings saved")
r = c.post(BASE + "/settings", data={"_csrf": csrf(c.get(BASE + "/settings?tab=alerts").text), "tab": "alerts", "alert_roles[]": ["coordinator", "doctor"], "hospital_alert_roles[]": ["nurse", "doctor"],
    "env_alert_roles[]": ["biomed", "client_admin"], "news2_enabled": "1", "news2_window_min": "60", "station_stale_min": "5", "charting_window_min": "120", "alert_dedupe_minutes": "60",
    "notify_patient_critical": "1", "missed_reading_alerts": "1", "reminders_enabled": "1", "auto_register_devices": "1", "weight_gain_alert": "1", "weight_gain_kg": "2"})
check(r, "alert settings with hospital roles", contains="Settings saved")

# Env location
r = c.get(BASE + "/environment/new")
check(r, "new location form", contains="Limits")
r = c.post(BASE + "/environment/new", data={"_csrf": csrf(r.text), "name": "QA blood fridge", "kind": "blood_bank", "active": "1", "wl[fridge_temp]": "2", "wh[fridge_temp]": "6", "cl[fridge_temp]": "1", "ch[fridge_temp]": "8"})
check(r, "create env location", contains="QA blood fridge")
loc_id = re.search(r"/environment/(\d+)/edit", r.text).group(1)

# Edge gateway pairing
r = c.get(BASE + "/gateways")
r = c.post(BASE + "/gateways/new", data={"_csrf": csrf(r.text), "gw_type": "edge", "name": "ICU edge gateway"})
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)
check(type("R", (), {"status_code": 200 if "Paired with" in out.stdout else 500, "text": out.stdout + out.stderr})(), "edge --pair", contains="Paired with")
cfg = json.load(open(EDGE_DIR + "/edge.json"))
cfg.update({"timezone": "+05:30", "data_dir": EDGE_DIR, "hl7_listeners": [{"host": "127.0.0.1", "port": 12575}], "sample_seconds": 0, "monitor_vendor": "Mindray",
    "modbus": [{"name": "BB fridge probe", "host": "127.0.0.1", "port": 15020, "unit": 1, "interval": 2, "serial": "BB-FRIDGE-1", "location": "QA blood fridge",
                "points": [{"register": 0, "type": "int16", "scale": 0.1, "param": "fridge_temp"}]}],
    "folders": [{"path": EDGE_DIR + "/ecg", "doc_type": "ecg", "patterns": ["*.xml", "*.pdf"], "settle_seconds": 0, "device_serial": "ECG-1", "manufacturer": "GE", "model": "MAC 2000"}],
    "adt_out": {"host": "127.0.0.1", "port": 12576, "interval": 2}})
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:
    # ADT in from HIS via edge
    a = mllp(12575, ADT)
    check(type("R", (), {"status_code": 200, "text": a})(), "HL7 ADT^A01 accepted (ACK AA)", contains="MSA|AA|A900")
    adm = wait(lambda: sql("SELECT b.bed_no FROM admissions a JOIN patients p ON p.id=a.patient_id JOIN beds b ON b.id=a.bed_id WHERE p.uhid='UH777001' AND a.status='admitted'"))
    print(("PASS" if adm == "ICU-8" else "FAIL") + f" ADT created admission in bed: {adm}")
    if adm != "ICU-8": FAILS.append("adt admission")
    pid = sql("SELECT id FROM patients WHERE uhid='UH777001'")

    # ORU from Mindray monitor
    a = mllp(12575, MINDRAY)
    check(type("R", (), {"status_code": 200, "text": a})(), "HL7 ORU^R01 accepted", contains="MSA|AA|1001")
    n = wait(lambda: int(sql(f"SELECT COUNT(*) FROM readings WHERE patient_id={pid}")) >= 6 or None)
    vals = sql(f"SELECT GROUP_CONCAT(CONCAT(param_code,'=',value+0) ORDER BY param_code) FROM readings WHERE patient_id={pid}")
    print(("PASS" if n else "FAIL") + f" monitor vitals stored for bed patient: {vals}")
    if not n: FAILS.append("oru readings")
    print(("PASS" if sql(f"SELECT COUNT(*) FROM readings WHERE patient_id={pid} AND charted_at IS NULL") != "0" else "FAIL") + " monitor vitals wait for nurse charting")
    news = wait(lambda: sql(f"SELECT CONCAT(score,'/',risk) FROM news2_scores WHERE patient_id={pid} ORDER BY id DESC LIMIT 1"))
    print(("PASS" if news and news.startswith("10/high") else "FAIL") + f" NEWS2 computed: {news}")
    if not (news and news.startswith("10/high")): FAILS.append("news2")
    na = sql(f"SELECT CONCAT(severity,'|',message) FROM alerts WHERE patient_id={pid} AND alert_type='news2'")
    print(("PASS" if na.startswith("critical") else "FAIL") + f" NEWS2 alert: {na}")
    dev = sql("SELECT CONCAT(serial_no,'|',(SELECT bed_no FROM beds WHERE id=bed_id)) FROM devices WHERE serial_no='BED3-MON'")
    print(("PASS" if dev == "BED3-MON|ICU-8" else "FAIL") + f" monitor auto-registered at bedside: {dev}")

    # Philips text-coded ORU → patient by PID (not admitted, has consent)
    mllp(12575, PHILIPS)
    ph = wait(lambda: sql("SELECT COUNT(*) FROM readings r JOIN patients p ON p.id=r.patient_id WHERE p.uhid='UH240104' AND r.batch_ref='hl7-PX55'") not in ("0", "") or None)
    print(("PASS" if ph else "FAIL") + " Philips text-code ORU mapped to patient")
    if not ph: FAILS.append("philips")

    # ADT out to monitor central station
    got = wait(lambda: any("UH777001" in m and "ADT^A01" in m for m in MONITOR_MSGS), 15)
    print(("PASS" if got else "FAIL") + f" ADT^A01 pushed to monitor central station ({len(MONITOR_MSGS)} msgs)")
    if not got: FAILS.append("adt out")

    # Modbus cold chain: normal → excursion → back in range (auto close)
    ok = wait(lambda: sql(f"SELECT COUNT(*) FROM readings WHERE location_id={loc_id}") not in ("0", "") or None)
    print(("PASS" if ok else "FAIL") + " Modbus fridge readings arriving at location")
    FRIDGE["v"] = 95
    exc = wait(lambda: sql(f"SELECT CONCAT(severity,'|',status,'|',message) FROM alerts WHERE location_id={loc_id} AND alert_type='env_excursion' ORDER BY id DESC LIMIT 1"))
    print(("PASS" if exc and exc.startswith("critical|open") else "FAIL") + f" cold-chain excursion alert: {exc}")
    if not (exc and exc.startswith("critical|open")): FAILS.append("env alert")
    FRIDGE["v"] = 40
    closed = wait(lambda: sql(f"SELECT status FROM alerts WHERE location_id={loc_id} AND alert_type='env_excursion' ORDER BY id DESC LIMIT 1") == "closed" or None)
    print(("PASS" if closed else "FAIL") + " excursion auto-closed when back in range")
    if not closed: FAILS.append("env autoclose")
    print(("PASS" if sql("SELECT COUNT(*) FROM notification_queue WHERE related_type='alert' AND related_id=(SELECT MAX(id) FROM alerts WHERE alert_type='env_excursion')") != "0" else "FAIL") + " excursion notified biomed/admin")

    # ECG folder watch
    open(EDGE_DIR + "/ecg/ecg_001.xml", "w").write("<RestingECG><PatientDemographics><PatientID>UH777001</PatientID></PatientDemographics><RestingECGMeasurements><VentricularRate>96</VentricularRate></RestingECGMeasurements></RestingECG>")
    doc = wait(lambda: sql(f"SELECT CONCAT(id,'|',status) FROM documents WHERE patient_id={pid} LIMIT 1"))
    print(("PASS" if doc else "FAIL") + f" ECG XML uploaded as document: {doc}")
    if not doc: FAILS.append("ecg doc")
    doc_id = (doc or "0|").split("|")[0]
    print(("PASS" if os.path.exists(EDGE_DIR + "/ecg/_uploaded/ecg_001.xml") else "FAIL") + " ECG file moved to _uploaded")
    print(("PASS" if sql(f"SELECT COUNT(*) FROM readings WHERE patient_id={pid} AND batch_ref='doc:{doc_id}'") == "1" else "FAIL") + " ECG heart rate stored")
finally:
    edge.terminate(); edge.wait(5)
print("EDGE LOG TAIL:\n" + "".join(open(EDGE_DIR + "/edge.log").readlines()[-6:]))

# ---------------- UI ----------------
icu = sql("SELECT id FROM wards WHERE name='ICU'")
for path in ["/station", f"/station/{icu}", f"/station/{icu}?tv=1", "/deterioration", f"/charting?ward={icu}", "/environment", f"/environment/{loc_id}", f"/environment/{loc_id}/edit",
             "/environment/report", "/documents", "/documents?status=pending", f"/documents/{doc_id}", f"/patients/{pid}", "/dashboard", "/alerts?type=news2", "/alerts?type=env_excursion&status=all", "/devices/new", "/settings?tab=alerts", "/settings?tab=his"]:
    check(c.get(BASE + path), "GET " + path)
j = c.get(BASE + f"/station/{icu}/data").json()
bed3 = next(b for b in j["beds"] if b["bed"] == "ICU-8")
print(("PASS" if bed3["patient"] and bed3["patient"]["uhid"] == "UH777001" and bed3["patient"]["vals"]["hr"]["v"] in ("112", "96") and bed3["patient"]["news2"]["score"] >= 9 else "FAIL") + f" station JSON bed ICU-8: {json.dumps(bed3)[:1200]}")
check(c.get(BASE + f"/environment/{loc_id}/trend.json?param=fridge_temp&days=1"), "env trend json", contains='"series"')
check(c.get(BASE + "/environment/report?csv=1"), "env report CSV", contains="QA blood fridge")
check(c.get(BASE + f"/documents/{doc_id}/file"), "document file", contains="VentricularRate")
r = c.post(BASE + f"/documents/{doc_id}", data={"_csrf": csrf(c.get(BASE + f"/documents/{doc_id}").text), "action": "review", "note": "Sinus tachycardia"})
check(r, "ECG reviewed", contains="reviewed")

# Patient page admission flags → NEWS2 recompute
r = c.post(BASE + f"/patients/{pid}/admission", data={"_csrf": csrf(c.get(BASE + f"/patients/{pid}").text), "on_oxygen": "1", "consciousness": "A", "spo2_scale": "1"})
check(r, "O2 flag recomputes NEWS2", contains="NEWS2 now 11")

# Nurse charting → FHIR to HIS
r = c.get(BASE + f"/charting?ward={icu}")
check(r, "charting lists ICU patient", contains="Vinod Kale")
data = {"_csrf": csrf(r.text), "ward": icu, f"p[{pid}][on]": "1", f"p[{pid}][acvpu]": "A", f"p[{pid}][o2]": "1"}
for rid, val in re.findall(rf'name="p\[{pid}\]\[r\]\[(\d+)\]" value="([^"]+)"', r.text): data[f"p[{pid}][r][{rid}]"] = val
first = re.findall(rf'name="p\[{pid}\]\[r\]\[(\d+)\]" value="([^"]+)"', r.text)
hr_id = sql(f"SELECT id FROM readings WHERE patient_id={pid} AND param_code='hr' AND charted_at IS NULL AND batch_ref LIKE 'hl7%' LIMIT 1")
data[f"p[{pid}][r][{hr_id}]"] = "110"   # nurse corrects artefact
r = c.post(BASE + "/charting", data=data)
check(r, "chart vitals", contains="Vitals charted for 1 patient(s), 1 value(s) corrected and sent to the HIS")
print(("PASS" if sql(f"SELECT COUNT(*) FROM readings WHERE patient_id={pid} AND charted_at IS NOT NULL") != "0" else "FAIL") + " readings marked charted")
subprocess.run(["php", "/home/claude/carepulse/platform/cron/worker.php", "--client=DEMO"], capture_output=True)
fh = [b for t, b in HIS_POSTS if t and "fhir" in t]
ok = fh and fh[-1]["resourceType"] == "Bundle" and any(e["resource"]["code"]["coding"][0].get("code") == "8867-4" and e["resource"]["valueQuantity"]["value"] == 110 for e in fh[-1]["entry"])
print(("PASS" if ok else "FAIL") + f" FHIR Bundle received by HIS ({len(HIS_POSTS)} posts, {len(fh[-1]['entry']) if fh else 0} observations, corrected HR 110 charted)")
if not ok: FAILS.append("fhir")
print("\n%d FAILURES" % len(FAILS))
for f in FAILS: print(" -", f[:300])
