"""Minimal, dependency-free HL7 v2 parser/builder for monitor (ORU^R01, IHE PCD-01) and ADT messages."""
from __future__ import annotations

import datetime as _dt
import itertools
from dataclasses import dataclass, field

MLLP_START, MLLP_END, CR = b"\x0b", b"\x1c\r", "\r"
_counter = itertools.count(1)


@dataclass
class Message:
    segments: list[list[str]]
    field_sep: str = "|"
    comp_sep: str = "^"
    rep_sep: str = "~"

    # ---- access helpers (HL7 numbering: seg[1] is field 1; for MSH, field 1 is the separator) ----
    def seg(self, name: str) -> list[str] | None:
        return next((s for s in self.segments if s[0] == name), None)

    def segs(self, name: str) -> list[list[str]]:
        return [s for s in self.segments if s[0] == name]

    def field(self, seg: list[str] | None, n: int) -> str:
        if seg is None:
            return ""
        if seg[0] == "MSH":
            n -= 1  # MSH-1 is the field separator itself
        return seg[n] if 0 < n < len(seg) else ""

    def comp(self, seg, n: int, c: int, rep: int = 0) -> str:
        f = self.field(seg, n).split(self.rep_sep)
        f = f[rep] if rep < len(f) else ""
        parts = f.split(self.comp_sep)
        return parts[c - 1] if 0 < c <= len(parts) else ""

    @property
    def type(self) -> str:
        msh = self.seg("MSH")
        return f"{self.comp(msh, 9, 1)}^{self.comp(msh, 9, 2)}"

    @property
    def control_id(self) -> str:
        return self.field(self.seg("MSH"), 10)


def parse(raw: str | bytes) -> Message:
    if isinstance(raw, bytes):
        raw = raw.decode("utf-8", errors="replace")
    raw = raw.strip("\x0b\x1c\r\n ").replace("\r\n", "\r").replace("\n", "\r")
    lines = [l for l in raw.split("\r") if l.strip()]
    if not lines or not lines[0].startswith("MSH"):
        raise ValueError("Not an HL7 message (no MSH)")
    fs = lines[0][3]
    enc = lines[0][4:8] if len(lines[0]) > 8 else "^~\\&"
    segments = []
    for l in lines:
        segments.append(l.split(fs))  # for MSH, index 1 holds MSH-2 (encoding chars); field() handles the offset
    return Message(segments, fs, enc[0], enc[1])


def hl7_time(ts: str, tz: _dt.tzinfo | None = None, ms: bool = False) -> str | None:
    """HL7 TS (YYYYMMDDHHMM[SS[.S+]][+/-ZZZZ]) → ISO-8601 with offset (local tz assumed if none). ms=True keeps fractions."""
    if not ts:
        return None
    ts = ts.split("^")[0]
    off = None
    for sign in ("+", "-"):
        if sign in ts[8:]:
            i = ts.rindex(sign)
            ts, off = ts[:i], ts[i:]
    frac = ts.split(".")[1] if "." in ts else ""
    ts = ts.split(".")[0]
    fmt = {8: "%Y%m%d", 10: "%Y%m%d%H", 12: "%Y%m%d%H%M", 14: "%Y%m%d%H%M%S"}.get(len(ts))
    if not fmt:
        return None
    d = _dt.datetime.strptime(ts, fmt)
    if off and len(off) == 5:
        d = d.replace(tzinfo=_dt.timezone(_dt.timedelta(hours=int(off[1:3]), minutes=int(off[3:5])) * (1 if off[0] == "+" else -1)))
    else:
        d = d.replace(tzinfo=tz or _dt.datetime.now().astimezone().tzinfo)
    if ms and frac.isdigit():
        d = d.replace(microsecond=int((frac + "000000")[:6]))
        return d.isoformat(timespec="milliseconds")
    return d.isoformat()


def now_ts() -> str:
    return _dt.datetime.now().strftime("%Y%m%d%H%M%S")


def ack(msg: Message, code: str = "AA", text: str = "") -> str:
    msh = msg.seg("MSH")
    trig = msg.comp(msh, 9, 2)
    out = [
        f"MSH|^~\\&|CAREPULSE|EDGE|{msg.field(msh, 3)}|{msg.field(msh, 4)}|{now_ts()}||ACK^{trig}^ACK|CP{next(_counter):08d}|P|{msg.field(msh, 12) or '2.6'}",
        f"MSA|{code}|{msg.control_id}" + (f"|{text[:80]}" if text else ""),
    ]
    return CR.join(out) + CR


def frame(text: str) -> bytes:
    return MLLP_START + text.encode("utf-8") + MLLP_END


def build_adt(event: str, patient: dict, ward: str, bed: str, sending="CAREPULSE", facility="EDGE", receiving="MONITORS") -> str:
    """ADT^A01 (admit) / A02 (transfer) / A03 (discharge) / A08 (update) for a monitor central station."""
    name = (patient.get("name") or "").strip().split(" ")
    family, given = (name[-1], " ".join(name[:-1])) if len(name) > 1 else (name[0] if name else "", "")
    dob = (patient.get("dob") or "").replace("-", "")
    sex = {"M": "M", "F": "F"}.get((patient.get("gender") or "")[:1].upper(), "U")
    ctrl = f"CP{next(_counter):08d}"
    return CR.join([
        f"MSH|^~\\&|{sending}|{facility}|{receiving}||{now_ts()}||ADT^{event}^ADT_A01|{ctrl}|P|2.6",
        f"EVN|{event}|{now_ts()}",
        f"PID|1||{patient.get('uhid') or patient.get('patient_id') or ''}^^^CAREPULSE^MR||{family}^{given}||{dob}|{sex}",
        f"PV1|1|I|{ward}^^{bed}||||^{patient.get('doctor', '')}||||||||||||{patient.get('his_admission_id') or ''}",
    ]) + CR


# ---------------------------------------------------------------- monitor observations
@dataclass
class Observation:
    code: str
    text: str
    system: str
    value: float
    unit: str
    time: str | None
    status: str
    equipment: str = ""


@dataclass
class Wave:
    code: str
    text: str
    values: list
    time: str | None
    rate: float | None
    unit: str = ""
    equipment: str = ""


@dataclass
class Alarm:
    code: str
    text: str
    priority: str          # high | medium | low
    state: str             # active | ended
    time: str | None


@dataclass
class ORU:
    patient_id: str = ""
    patient_name: str = ""
    ward: str = ""
    room: str = ""
    bed: str = ""
    facility: str = ""
    sending_app: str = ""
    sending_facility: str = ""
    obs: list[Observation] = field(default_factory=list)
    waves: list[Wave] = field(default_factory=list)
    texts: dict = field(default_factory=dict)   # string observations, e.g. drug name / vent mode
    alarms: list[Alarm] = field(default_factory=list)


def parse_oru(msg: Message, tz=None) -> ORU:
    msh, pid, pv1, obr = msg.seg("MSH"), msg.seg("PID"), msg.seg("PV1"), msg.seg("OBR")
    o = ORU(sending_app=msg.comp(msh, 3, 1), sending_facility=msg.comp(msh, 4, 1))
    if pid:
        o.patient_id = msg.comp(pid, 3, 1)
        o.patient_name = " ".join(x for x in (msg.comp(pid, 5, 2), msg.comp(pid, 5, 1)) if x)
    if pv1:
        o.ward, o.room, o.bed, o.facility = (msg.comp(pv1, 3, i) for i in (1, 2, 3, 4))
    obr_time = hl7_time(msg.field(obr, 7), tz) if obr else None
    rate = None
    for s in msg.segs("OBX"):  # sample rate attribute applies to the waveforms of the message (IHE PCD waveform content)
        ident = (msg.comp(s, 3, 2) or msg.comp(s, 3, 1)).upper()
        if "SAMP_RATE" in ident or "SAMPLE_RATE" in ident:
            try:
                rate = float(msg.comp(s, 5, 1))
            except ValueError:
                pass
    for s in msg.segs("OBX"):
        vtype = msg.field(s, 2)
        ident = (msg.comp(s, 3, 2) or msg.comp(s, 3, 1)).upper()
        if vtype == "NA":
            try:
                vals = [float(x) if x not in ("", "-") else None for x in msg.field(s, 5).split(msg.comp_sep)]
            except ValueError:
                continue
            o.waves.append(Wave(code=msg.comp(s, 3, 1), text=msg.comp(s, 3, 2), values=vals, time=hl7_time(msg.field(s, 14), tz, ms=True) or obr_time,
                                rate=rate, unit=msg.comp(s, 6, 2) or msg.comp(s, 6, 1), equipment=msg.comp(s, 18, 1)))
            continue
        if "SAMP_RATE" in ident or "SAMPLE_RATE" in ident:
            continue
        if vtype in ("ST", "TX", "CWE", "CE") and not _is_number(msg.comp(s, 5, 1)):
            o.texts[ident] = msg.comp(s, 5, 2) or msg.comp(s, 5, 1)
            continue
        if vtype not in ("NM", "SN", "ST", "CWE", ""):
            continue
        raw = msg.field(s, 5).split(msg.comp_sep)
        raw = raw[1] if vtype == "SN" and len(raw) > 1 else raw[0]
        try:
            val = float(raw)
        except ValueError:
            continue
        status = msg.field(s, 11) or "F"
        if status in ("X", "D", "W"):  # cannot obtain / deleted / wrong
            continue
        o.obs.append(Observation(
            code=msg.comp(s, 3, 1), text=msg.comp(s, 3, 2), system=msg.comp(s, 3, 3),
            value=val, unit=msg.comp(s, 6, 2) or msg.comp(s, 6, 1), time=hl7_time(msg.field(s, 14), tz) or obr_time,
            status=status, equipment=msg.comp(s, 18, 1)))
    return o


def _is_number(x: str) -> bool:
    try:
        float(x)
        return True
    except ValueError:
        return False


def parse_alarms(msg: Message, tz=None) -> ORU:
    """ORU^R40 (IHE PCD Alert Communication Management). Each alarm: an event OBX (identifier / text) with priority in
    OBX-8 (PH / PM / PL) and an optional state OBX (MDC_ATTR_ALERT_STATE: start | continue | end). Verify per vendor."""
    o = parse_oru(msg, tz)
    o.alarms = []
    state = "active"
    for s in msg.segs("OBX"):
        ident = (msg.comp(s, 3, 2) or msg.comp(s, 3, 1)).upper()
        if "ALERT_STATE" in ident or "ALARM_STATE" in ident or ident.endswith("EVT_STATE"):
            v = (msg.comp(s, 5, 1) or "").lower()
            state = "ended" if v in ("end", "ended", "stop", "inactive", "resolved") else "active"
    for s in msg.segs("OBX"):
        ident = (msg.comp(s, 3, 2) or msg.comp(s, 3, 1))
        up = ident.upper()
        if not ("EVT" in up or "ALARM" in up or "ALERT" in up) or "STATE" in up or "PRIORITY" in up or "SOURCE" in up:
            continue
        flags = set(msg.field(s, 8).split(msg.rep_sep))
        prio = "high" if "PH" in flags or "H" in flags else ("low" if "PL" in flags or "PN" in flags else "medium")
        text = msg.comp(s, 5, 2) or msg.comp(s, 5, 1) or msg.comp(s, 3, 2) or ident
        o.alarms.append(Alarm(code=msg.comp(s, 3, 2) or msg.comp(s, 3, 1), text=text.replace("_", " ").strip(), priority=prio, state=state,
                              time=hl7_time(msg.field(s, 14), tz)))
    return o


def parse_adt(msg: Message, tz=None) -> dict:
    """ADT → CarePulse /gateway/adt JSON."""
    trig = msg.comp(msg.seg("MSH"), 9, 2)
    event = {"A01": "admit", "A04": "admit", "A02": "transfer", "A03": "discharge", "A08": "patient_update", "A31": "patient_update", "A11": "discharge"}.get(trig)
    if not event:
        raise ValueError(f"ADT {trig} not handled")
    pid, pv1 = msg.seg("PID"), msg.seg("PV1")
    sex = msg.field(pid, 8)[:1]
    dob = msg.field(pid, 7)[:8]
    body = {"event": event, "patient": {
        "uhid": msg.comp(pid, 3, 1), "patient_id": msg.comp(pid, 3, 1),
        "name": " ".join(x for x in (msg.comp(pid, 5, 2), msg.comp(pid, 5, 1)) if x),
        "gender": sex if sex in ("M", "F") else None, "dob": f"{dob[:4]}-{dob[4:6]}-{dob[6:8]}" if len(dob) == 8 else None,
        "mobile": msg.comp(pid, 13, 1) or None, "address": msg.comp(pid, 11, 1) or None, "city": msg.comp(pid, 11, 3) or None}}
    if pv1:
        ward, room, bed = msg.comp(pv1, 3, 1), msg.comp(pv1, 3, 2), msg.comp(pv1, 3, 3)
        body["admission"] = {"id": msg.comp(pv1, 19, 1) or None, "ward_code": ward, "bed_code": bed,
                             "candidates": bed_candidates(ward, room, bed),
                             "doctor": " ".join(x for x in (msg.comp(pv1, 7, 3), msg.comp(pv1, 7, 2)) if x) or None,
                             "at": hl7_time(msg.field(msg.seg("EVN"), 2), tz) or hl7_time(msg.field(pv1, 44), tz)}
    return body


def bed_candidates(ward: str, room: str, bed: str) -> list[str]:
    """Different vendors put the bed label in different PL components; try the common spellings."""
    c = []
    for x in (bed, f"{ward}-{bed}" if ward and bed else "", f"{ward}{bed}" if ward and bed else "", f"{room}-{bed}" if room and bed else "", room, ward if not bed and not room else ""):
        x = (x or "").strip()
        if x and x not in c:
            c.append(x)
    return c
