"""BLE location gateways → CarePulse /api/v1/rtls/sightings.
Accepts the JSON most BLE gateways can be configured to send (HTTP POST or MQTT):
  [{"mac": "AC233F001122", "rssi": -63}, ...]                         gateway id from ?gw= / topic / "gateway" field
  {"gateway": "GW-ICU-1", "devices"|"beacons"|"obj"|"items": [{"mac"|"dmac"|"tag": ..., "rssi": ..., "battery": .., "button": .., "tamper": ..}]}
Sightings are batched every `interval` seconds (strongest RSSI per tag + gateway kept). Tags not matching `tag_prefixes`
(when set) are ignored so phones and other BLE devices are not uploaded."""
from __future__ import annotations

import json
import logging
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

log = logging.getLogger("edge.rtls")
LIST_KEYS = ("devices", "beacons", "obj", "items", "tags", "data")


def norm_mac(v) -> str:
    s = "".join(ch for ch in str(v or "").upper() if ch.isalnum())
    raw = str(v or "").strip().upper()
    # Only MAC-like ids (12 hex digits, with or without separators) are normalised; anchor codes such as GW-ICU-1 pass through
    if len(s) == 12 and all(ch in "0123456789ABCDEF" for ch in s) and len(raw) in (12, 14, 17):
        return ":".join(s[i:i + 2] for i in range(0, 12, 2))
    return raw


def parse(payload, gateway: str = "") -> list[dict]:
    """Return [{tag, anchor, rssi, battery?, button?, tamper?}]"""
    if isinstance(payload, (bytes, str)):
        payload = json.loads(payload)
    items, gw = [], gateway
    if isinstance(payload, dict):
        gw = str(payload.get("gateway") or payload.get("gw") or payload.get("gmac") or payload.get("gatewayMac") or gw)
        for k in LIST_KEYS:
            if isinstance(payload.get(k), list):
                items = payload[k]
                break
        else:
            items = [payload] if ("mac" in payload or "tag" in payload or "dmac" in payload) else []
    elif isinstance(payload, list):
        items = payload
    out = []
    for it in items:
        if not isinstance(it, dict):
            continue
        tag = it.get("tag") or it.get("mac") or it.get("dmac") or it.get("id")
        rssi = it.get("rssi", it.get("RSSI"))
        anchor = str(it.get("gateway") or it.get("gw") or gw or "")
        if tag is None or rssi is None or not anchor:
            continue
        s = {"tag": norm_mac(tag), "anchor": norm_mac(anchor), "rssi": int(float(rssi))}
        for k in ("battery", "button", "tamper"):
            if k in it:
                s[k] = it[k]
        out.append(s)
    return out


class RtlsCollector(threading.Thread):
    def __init__(self, cfg: dict, queue_put):
        super().__init__(daemon=True, name="rtls")
        self.cfg, self.put = cfg, queue_put
        self.interval = float(cfg.get("interval", 2))
        self.prefixes = ["".join(ch for ch in str(p).upper() if ch.isalnum()) for p in cfg.get("tag_prefixes", [])]
        self.buf: dict = {}
        self.lock = threading.Lock()
        self.stats = {"sightings": 0, "ignored": 0}

    def add(self, sightings: list[dict]):
        with self.lock:
            for s in sightings:
                if self.prefixes and not any(s["tag"].replace(":", "").startswith(p) for p in self.prefixes):
                    self.stats["ignored"] += 1
                    continue
                k = (s["tag"], s["anchor"])
                old = self.buf.get(k)
                if not old:
                    self.buf[k] = dict(s)
                else:   # keep the strongest RSSI in the window; a button press or tamper is never lost
                    old["rssi"] = max(old["rssi"], s["rssi"])
                    for f in ("button", "tamper"):
                        if s.get(f):
                            old[f] = True
                    if "battery" in s:
                        old["battery"] = s["battery"]
                self.stats["sightings"] += 1

    def run(self):
        if self.cfg.get("http_port"):
            threading.Thread(target=self.serve, daemon=True, name="rtls-http").start()
        while True:
            time.sleep(self.interval)
            with self.lock:
                batch, self.buf = list(self.buf.values()), {}
            if batch:
                ts = time.strftime("%Y-%m-%dT%H:%M:%S%z")
                for s in batch:
                    s.setdefault("at", ts)
                self.put({"sightings": batch})

    def serve(self):
        col = self

        class H(BaseHTTPRequestHandler):
            def log_message(self, *a):
                pass

            def do_POST(self):
                try:
                    n = int(self.headers.get("Content-Length", 0))
                    q = parse_qs(urlparse(self.path).query)
                    col.add(parse(self.rfile.read(n), (q.get("gw") or [""])[0]))
                    self.send_response(200)
                except Exception as e:
                    log.warning("bad RTLS payload: %s", e)
                    self.send_response(400)
                self.end_headers()

        srv = ThreadingHTTPServer((self.cfg.get("http_host", "0.0.0.0"), int(self.cfg["http_port"])), H)
        log.info("RTLS HTTP listener on :%s", self.cfg["http_port"])
        srv.serve_forever()
