"""CarePulse platform client + offline store-and-forward queue (SQLite)."""
from __future__ import annotations

import json
import logging
import mimetypes
import sqlite3
import ssl
import threading
import time
import urllib.error
import urllib.request
import uuid

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


class ApiError(Exception):
    def __init__(self, status: int, msg: str):
        super().__init__(f"{status}: {msg}")
        self.status = status


class Platform:
    def __init__(self, server: str, token: str, timeout: int = 20, verify_tls: bool = True):
        self.server = server.rstrip("/")
        if not (self.server.startswith("https://") or "://localhost" in self.server or "://127.0.0.1" in self.server):
            raise ValueError("server must use https://")
        self.token = token
        self.timeout = timeout
        self.ctx = ssl.create_default_context() if verify_tls else ssl._create_unverified_context()

    def _req(self, method: str, path: str, body: bytes | None = None, ctype: str = "application/json"):
        req = urllib.request.Request(self.server + path, data=body, method=method, headers={
            "Authorization": f"Bearer {self.token}", "Accept": "application/json", "User-Agent": "CarePulse-Edge/2.0", **({"Content-Type": ctype} if body is not None else {})})
        try:
            with urllib.request.urlopen(req, timeout=self.timeout, context=self.ctx if self.server.startswith("https") else None) as r:
                return json.loads(r.read() or b"{}")
        except urllib.error.HTTPError as e:
            try:
                msg = json.loads(e.read()).get("error", e.reason)
            except Exception:
                msg = e.reason
            raise ApiError(e.code, str(msg)) from None

    def post(self, path: str, data: dict):
        return self._req("POST", path, json.dumps(data).encode())

    def get(self, path: str):
        return self._req("GET", path)

    def upload(self, path: str, file_path: str, meta: dict):
        boundary = uuid.uuid4().hex
        fname = file_path.replace("\\", "/").split("/")[-1]
        with open(file_path, "rb") as f:
            content = f.read()
        ctype = mimetypes.guess_type(fname)[0] or "application/octet-stream"
        body = (f"--{boundary}\r\nContent-Disposition: form-data; name=\"meta\"\r\n\r\n{json.dumps(meta)}\r\n"
                f"--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"{fname}\"\r\nContent-Type: {ctype}\r\n\r\n").encode() + content + f"\r\n--{boundary}--\r\n".encode()
        return self._req("POST", path, body, f"multipart/form-data; boundary={boundary}")


class Queue:
    """Every batch is written to disk first, then uploaded; survives internet outages and restarts."""

    def __init__(self, path: str):
        self.db = sqlite3.connect(path, check_same_thread=False, isolation_level=None)
        self.db.execute("PRAGMA journal_mode=WAL")
        self.db.execute("CREATE TABLE IF NOT EXISTS q (id INTEGER PRIMARY KEY, kind TEXT NOT NULL, body TEXT NOT NULL, created REAL NOT NULL, attempts INTEGER DEFAULT 0)")
        self.lock = threading.Lock()

    def put(self, kind: str, body: dict):
        if kind in ("waveforms", "rtls"):
            body = dict(body, _queued=time.time())
        with self.lock:
            self.db.execute("INSERT INTO q (kind, body, created) VALUES (?, ?, ?)", (kind, json.dumps(body), time.time()))

    def take(self, kind: str, n: int = 100):
        with self.lock:
            return [(i, json.loads(b)) for i, b in self.db.execute("SELECT id, body FROM q WHERE kind = ? ORDER BY id LIMIT ?", (kind, n))]

    def done(self, ids):
        if ids:
            with self.lock:
                self.db.execute(f"DELETE FROM q WHERE id IN ({','.join('?' * len(ids))})", list(ids))

    def bump(self, ids):
        if ids:
            with self.lock:
                self.db.execute(f"UPDATE q SET attempts = attempts + 1 WHERE id IN ({','.join('?' * len(ids))})", list(ids))

    def size(self) -> int:
        return self.db.execute("SELECT COUNT(*) FROM q").fetchone()[0]


class Uploader(threading.Thread):
    """Sends queued reading batches (max 100 per call) and ADT events; exponential backoff when offline."""

    def __init__(self, platform: Platform, queue: Queue, stats: dict):
        super().__init__(daemon=True, name="uploader")
        self.p, self.q, self.stats = platform, queue, stats
        self.wake = threading.Event()
        self.stop = threading.Event()
        self.max_wave_age = 600

    def run(self):
        backoff = 2
        while not self.stop.is_set():
            try:
                sent = self.flush()
                backoff = 2
                if not sent:
                    self.wake.wait(2)
                    self.wake.clear()
            except ApiError as e:
                log.error("platform refused upload: %s", e)
                if e.status in (401, 403):
                    self.stats["auth_error"] = str(e)
                self.stop.wait(backoff); backoff = min(backoff * 2, 300)
            except Exception as e:  # network down
                self.stats["last_error"] = str(e)
                log.warning("upload failed (%s) – retry in %ss, %d queued", e, backoff, self.q.size())
                self.stop.wait(backoff); backoff = min(backoff * 2, 300)

    def flush(self) -> int:
        sent = 0
        rows = self.q.take("readings", 100)
        if rows:
            res = self.p.post("/api/v1/readings", {"batches": [b for _, b in rows]})
            self.q.done([i for i, _ in rows])
            for r in res.get("results", []):
                self.stats["saved"] = self.stats.get("saved", 0) + int(r.get("saved", 0))
                for a in r.get("alerts", []):
                    log.warning("ALERT %s: %s", a.get("severity"), a.get("message"))
                if not r.get("ok"):
                    log.error("batch rejected: %s", r.get("error"))
                elif r.get("rejected"):
                    log.warning("values rejected by platform: %s", r.get("rejected"))
                if r.get("ok") and not r.get("patient_assigned") and not r.get("location_id"):
                    log.info("readings saved but not matched to a patient/bed – staff will assign (check ward/bed codes)")
            sent += len(rows)
        rows = self.q.take("waveforms", 30)
        if rows:
            # Waveforms are live data: anything older than the backlog limit is dropped instead of flooding the server after an outage
            fresh = [(i, b) for i, b in rows if time.time() - b.get("_queued", time.time()) < self.max_wave_age]
            if fresh:
                res = self.p.post("/api/v1/waveforms", {"batches": [{k: v for k, v in b.items() if k != "_queued"} for _, b in fresh]})
                for r in res.get("results", []):
                    if not r.get("ok"):
                        log.warning("waveform batch rejected: %s", r.get("error"))
            self.q.done([i for i, _ in rows])
            sent += len(rows)
        rows = self.q.take("rtls", 50)
        if rows:
            # Location is live: drop sightings older than 60 s after an outage instead of replaying history
            fresh = [s for _, b in rows if time.time() - b.get("_queued", time.time()) < 60 for s in b["sightings"]]
            if fresh:
                res = self.p.post("/api/v1/rtls/sightings", {"sightings": fresh[:5000]})
                if res.get("unknown_anchors"):
                    log.info("RTLS: %s sightings from gateways not placed on any floor map", res["unknown_anchors"])
            self.q.done([i for i, _ in rows])
            sent += len(rows)
        for i, body in self.q.take("nurse_call", 50):
            try:
                self.p.post("/api/v1/nurse-calls", body)
            except ApiError as e:
                if e.status >= 500:
                    raise
                log.error("nurse call rejected: %s", e)
            self.q.done([i])
            sent += 1
        for i, body in self.q.take("alarms", 20):
            try:
                res = self.p.post("/api/v1/alarms", body)
                for a in res.get("alarms", []):
                    log.warning("DEVICE ALARM %s %s → alert %s", a.get("code"), a.get("state"), a.get("alert_id"))
            except ApiError as e:
                if e.status >= 500:
                    raise
                log.error("alarm rejected: %s", e)
            self.q.done([i])
            sent += 1
        for i, body in self.q.take("adt", 20):
            try:
                self.p.post("/api/v1/gateway/adt", body)
            except ApiError as e:
                if e.status >= 500:
                    raise
                log.error("ADT rejected: %s", e)
            self.q.done([i])
            sent += 1
        if sent:
            self.stats["last_upload"] = time.time()
        return sent
