"""Modbus TCP poller (function 3 / 4) for environment sensors, gas pressure transducers, UPS/DG status."""
from __future__ import annotations

import logging
import socket
import struct
import threading
import time

log = logging.getLogger("edge.modbus")


def read_registers(host: str, port: int, unit: int, address: int, count: int, function: int = 3, timeout: float = 5.0) -> list[int]:
    tid = int(time.time() * 1000) & 0xFFFF
    pdu = struct.pack(">BHH", function, address, count)
    adu = struct.pack(">HHHB", tid, 0, len(pdu) + 1, unit) + pdu
    with socket.create_connection((host, port), timeout=timeout) as s:
        s.sendall(adu)
        hdr = _recv(s, 7)
        _, _, length, _ = struct.unpack(">HHHB", hdr)
        body = _recv(s, length - 1)
    if body[0] & 0x80:
        raise IOError(f"Modbus exception code {body[1]}")
    n = body[1]
    return list(struct.unpack(f">{n // 2}H", body[2:2 + n]))


def _recv(s, n):
    buf = b""
    while len(buf) < n:
        chunk = s.recv(n - len(buf))
        if not chunk:
            raise IOError("connection closed")
        buf += chunk
    return buf


def decode(regs: list[int], i: int, kind: str) -> float:
    if kind == "uint16":
        return regs[i]
    if kind == "int16":
        return struct.unpack(">h", struct.pack(">H", regs[i]))[0]
    if kind in ("float32", "float32_be"):
        return struct.unpack(">f", struct.pack(">HH", regs[i], regs[i + 1]))[0]
    if kind == "float32_le":  # word-swapped
        return struct.unpack(">f", struct.pack(">HH", regs[i + 1], regs[i]))[0]
    if kind == "int32":
        return struct.unpack(">i", struct.pack(">HH", regs[i], regs[i + 1]))[0]
    raise ValueError(kind)


class ModbusPoller(threading.Thread):
    """devices: [{"name","host","port","unit","interval","function","serial","location", "points":[{"register","type","scale","offset","param"}]}]"""

    def __init__(self, devices: list[dict], emit, event=None):
        super().__init__(daemon=True, name="modbus")
        self.devices, self.emit, self.event = devices, emit, event
        self.state: dict = {}
        self.stop = threading.Event()
        self.next = {i: 0.0 for i in range(len(devices))}

    def run(self):
        while not self.stop.is_set():
            now = time.time()
            for i, d in enumerate(self.devices):
                if now < self.next[i]:
                    continue
                self.next[i] = now + int(d.get("interval", 60))
                try:
                    self.poll(d)
                except Exception as e:
                    log.warning("modbus %s (%s): %s", d.get("name"), d.get("host"), e)
            self.stop.wait(1)

    def poll(self, d: dict):
        pts = d["points"]
        lo = min(p["register"] for p in pts)
        hi = max(p["register"] + (2 if p.get("type", "int16").startswith(("float32", "int32")) else 1) for p in pts)
        regs = read_registers(d["host"], int(d.get("port", 502)), int(d.get("unit", 1)), lo, hi - lo, int(d.get("function", 3)))
        ts = time.strftime("%Y-%m-%dT%H:%M:%S%z")
        readings = []
        for p in pts:
            v = decode(regs, p["register"] - lo, p.get("type", "int16")) * float(p.get("scale", 1)) + float(p.get("offset", 0))
            if p.get("nurse_call") and self.event:
                # IO module input wired to a nurse call / bed-exit contact: rising edge = call, falling edge = cancelled at the bed
                nc = p["nurse_call"]
                on = bool(int(v) & int(p.get("mask", 0xFFFF)))
                key = (d.get("host"), d.get("unit", 1), p["register"], p.get("mask"))
                if key in self.state and self.state[key] != on:
                    self.event("nurse_call", {"location": {k: nc[k] for k in ("ward_code", "bed_code", "zone") if k in nc},
                                              "type": nc.get("type", "normal"), "state": "call" if on else "cancel", "source": d.get("name", "IO module"), "at": ts})
                self.state[key] = on
                continue
            readings.append({"param": p["param"], "value": round(v, 3), "measured_at": ts, **({"unit": p["unit"]} if p.get("unit") else {})})
        if not readings:
            return
        self.emit({"device": {"serial": d.get("serial") or f"MODBUS-{d['host']}-{d.get('unit', 1)}", "manufacturer": d.get("manufacturer", "Modbus sensor"), "model": d.get("name")},
                   "location": {"name": d["location"]} if d.get("location") else {}, "readings": readings})
