#!/usr/bin/env python3
"""Reference client for an external device (BYOD): reads readings from your own controller and sends them to Lutra.

Built for the PiXtend controller of a private pool, but usable with any controller that has a status file or a
local HTTP status page. Design: docs/superpowers/specs/2026-11-23-externe-apparaten-design.md;
manual: docs/integratie/externe-apparaten.md.

Guarantees this client enforces:
  - Read only from the controller: open a file for reading, or one HTTP GET. Never write, never any other method,
    never send anything back. The controller notices nothing of this client except a read.
  - Write only to Lutra: one POST (HTTPS, port 8443) or one MQTT publish (port 8883) on the device's own
    telemetry topic. The IoT policy allows nothing else either; no message ever comes back.
  - A failure (controller unreachable, Lutra unreachable, odd value) breaks nothing: log, skip, next round.
    Runs as its own process (systemd service), separate from the controller.

Standard library only for HTTPS (ssl, http.client). MQTT only if paho-mqtt (2.x) is installed.

Settings (JSON), for example /etc/lutra-extern/config.json:

    {
      "thing": "lutra-ext-0a1b2c3d4e5f",
      "endpoint": "xxxxxxxx-ats.iot.eu-central-1.amazonaws.com",
      "cert": "/etc/lutra-extern/lutra.crt",
      "key": "/etc/lutra-extern/lutra.key",
      "ca": "/etc/lutra-extern/AmazonRootCA1.pem",
      "protocol": "https",
      "source": {"file": "/run/poolcontrol/status.json"},
      "fields": {"ph": "sensors.ph", "orp": "sensors.orp_mv", "water_temp": "temp.water", "pump_running": "pump.on"},
      "interval_s": 300
    }

`source` is {"file": path} or {"url": "http://127.0.0.1:8080/status"}, with a url optionally plus
"token_file": path to a file holding the token of the local API (header X-Api-Token). Always GET only.
`fields` maps a Lutra quantity (packages/devices/quantities.json) to a path in the controller's JSON (dots between
keys, a number for a position in a list). Units must already be Lutra's (°C, mV, mg/l, ...): this client does not
convert.
A field can also be an object with freshness conditions, so a value left standing after a sensor failure is not sent
as a new reading: {"path": ..., "only_if": path to a flag that must be exactly true, "time": path to the time of the
last good reading (seconds since 1970), "max_age_s": seconds} ("time" and "max_age_s" always together).

    python3 lutra_extern.py --config config.json --once --dry-run   # print one message, send nothing
    python3 lutra_extern.py --config config.json                    # one message every interval_s
"""

from __future__ import annotations

import argparse
import http.client
import json
import logging
import math
import re
import ssl
import sys
import time
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any, Callable

LOG = logging.getLogger("lutra-extern")

THING_RE = re.compile(r"^lutra-ext-[0-9a-f]{12}$")
GROOTHEID_RE = re.compile(r"^[a-z][a-z0-9_]{0,40}$")
MAX_BRON_BYTES = 256 * 1024
MAX_BERICHT_BYTES = 4096   # zelfde grens als de ingest (services/ingest/ingest.py MAX_EXTERN_BYTES)
MIN_INTERVAL_S = 60        # de ingest neemt hoogstens 12 per minuut aan; elke minuut is ruim genoeg
TIMEOUT_S = 10
TOEKOMST_MARGE_S = 120    # tijdstempel van een meting mag hoogstens zoveel vooruit lopen (zelfde marge als de ingest)


class ConfigFout(Exception):
    pass


# ----------------------------------------------------------------------------------------- instellingen


def lees_config(pad: str | Path) -> dict:
    cfg = json.loads(Path(pad).read_text(encoding="utf-8"))
    if not isinstance(cfg, dict):
        raise ConfigFout("config is not an object")
    if not isinstance(cfg.get("thing"), str) or not THING_RE.fullmatch(cfg["thing"]):
        raise ConfigFout("thing: expected lutra-ext- followed by 12 hex characters")
    if cfg.get("protocol", "https") not in ("https", "mqtt"):
        raise ConfigFout("protocol: https or mqtt")
    bron = cfg.get("source")
    if not isinstance(bron, dict) or set(bron) not in ({"file"}, {"url"}, {"url", "token_file"}):
        raise ConfigFout('source: {"file": path} or {"url": "http://...", "token_file"?: path}')
    if "url" in bron and urllib.parse.urlparse(bron["url"]).scheme not in ("http", "https"):
        raise ConfigFout("source.url: http or https")
    if "token_file" in bron and not (isinstance(bron["token_file"], str) and bron["token_file"]):
        raise ConfigFout("source.token_file: path to a file with the API token")
    velden = cfg.get("fields")
    if not isinstance(velden, dict) or not velden:
        raise ConfigFout("fields: at least one quantity")
    for q, p in velden.items():
        if not GROOTHEID_RE.fullmatch(q) or not (_pad_ok(p) or (isinstance(p, dict) and _veld_ok(p))):
            raise ConfigFout(f'fields.{q}: quantity name and a path, or {{"path", "only_if"?, "time"?, '
                             f'"max_age_s"?}} ("time" and "max_age_s" together)')
    cfg["interval_s"] = max(MIN_INTERVAL_S, int(cfg.get("interval_s", 300)))
    return cfg


def _pad_ok(p: Any) -> bool:
    return isinstance(p, str) and bool(p)


def _veld_ok(v: dict) -> bool:
    if not set(v) <= {"path", "only_if", "time", "max_age_s"} or not _pad_ok(v.get("path")):
        return False
    if "only_if" in v and not _pad_ok(v["only_if"]):
        return False
    if ("time" in v) != ("max_age_s" in v):
        return False
    if "time" in v:
        m = v["max_age_s"]
        return _pad_ok(v["time"]) and isinstance(m, (int, float)) and not isinstance(m, bool) and m > 0
    return True


# ------------------------------------------------------------------------------- lezen (alleen lezen)


def lees_bron(bron: dict, opener: Callable = urllib.request.urlopen) -> Any:
    """Status van de besturing als JSON. Alleen lezen: een bestand openen, of één GET. Gooit bij een fout."""
    if "file" in bron:
        with open(bron["file"], "rb") as f:
            data = f.read(MAX_BRON_BYTES + 1)
    else:
        kop = {"accept": "application/json"}
        if "token_file" in bron:
            # Token van de lokale API van de besturing (bijv. poolctrl: X-Api-Token). Alleen uit een bestand dat
            # alleen deze gebruiker kan lezen; komt nooit in de config, de log of een foutmelding.
            kop["x-api-token"] = Path(bron["token_file"]).read_text(encoding="utf-8").strip()
        req = urllib.request.Request(bron["url"], method="GET", headers=kop)
        with opener(req, timeout=TIMEOUT_S) as r:
            data = r.read(MAX_BRON_BYTES + 1)
    if len(data) > MAX_BRON_BYTES:
        raise ValueError("status too large")
    return json.loads(data.decode("utf-8"))


def pak(doc: Any, pad: str) -> Any:
    """'sensors.ph' of 'temps.0.value' uit geneste JSON; None als het er niet is."""
    cur = doc
    for deel in pad.split("."):
        if isinstance(cur, dict) and deel in cur:
            cur = cur[deel]
        elif isinstance(cur, list) and deel.isdigit() and int(deel) < len(cur):
            cur = cur[int(deel)]
        else:
            return None
    return cur


def vers(doc: Any, veld: dict, nu: int) -> bool:
    """Mag deze waarde mee? "only_if": pad dat precies true moet zijn (bijv. online/ok van de sensor).
    "time" + "max_age_s": pad naar het tijdstip (seconden sinds 1970) van de laatste geslaagde meting.
    Ontbreekt of twijfelt iets, dan niet: een waarde die blijft staan na een sensorfout is erger dan geen waarde."""
    if "only_if" in veld and pak(doc, veld["only_if"]) is not True:
        return False
    if "time" in veld:
        t = pak(doc, veld["time"])
        if isinstance(t, bool) or not isinstance(t, (int, float)) or not math.isfinite(t):
            return False
        if not -TOEKOMST_MARGE_S <= nu - t <= veld["max_age_s"]:
            return False
    return True


def bericht(doc: Any, velden: dict[str, Any], nu: int, seq: int | None = None) -> dict | None:
    """Telemetrie v3 voor Lutra. Alleen getallen (eindig) en ja/nee; de rest valt weg. None als er niets over is."""
    pts: dict[str, Any] = {}
    for q, veld in velden.items():
        if isinstance(veld, dict):
            if not vers(doc, veld, nu):
                continue
            veld = veld["path"]
        v = pak(doc, veld)
        if isinstance(v, bool):
            pts[q] = v
        elif isinstance(v, (int, float)) and math.isfinite(v):
            pts[q] = round(float(v), 4) if isinstance(v, float) else v
        elif isinstance(v, str) and v in ("open", "closed", "moving", "unknown", "heat", "cool", "auto"):
            pts[q] = v
    if not pts:
        return None
    msg: dict[str, Any] = {"v": 3, "ts": nu, "pts": pts}
    if seq is not None:
        msg["seq"] = seq
    return msg


# ------------------------------------------------------------------------------ versturen (alleen schrijven)


def tls_context(cfg: dict) -> ssl.SSLContext:
    ctx = ssl.create_default_context(cafile=cfg["ca"])
    ctx.minimum_version = ssl.TLSVersion.TLSv1_2
    ctx.load_cert_chain(cfg["cert"], cfg["key"])
    return ctx


def topic(thing: str) -> str:
    return f"lutra/v1/{thing}/telemetry"


def verstuur_https(cfg: dict, payload: bytes, verbinding: Callable | None = None) -> int:
    """POST /topics/<topic>?qos=1 op poort 8443, met het clientcertificaat. Geeft de HTTP-status."""
    pad = "/topics/" + urllib.parse.quote(topic(cfg["thing"]), safe="") + "?qos=1"
    maak = verbinding or (lambda: http.client.HTTPSConnection(cfg["endpoint"], 8443, context=tls_context(cfg),
                                                              timeout=TIMEOUT_S))
    c = maak()
    try:
        c.request("POST", pad, body=payload, headers={"content-type": "application/json"})
        r = c.getresponse()
        r.read(4096)
        return r.status
    finally:
        c.close()


def verstuur_mqtt(cfg: dict, payload: bytes) -> int:  # pragma: no cover  (vraagt een broker)
    import paho.mqtt.client as mqtt

    c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=cfg["thing"])
    c.tls_set_context(tls_context(cfg))
    c.connect(cfg["endpoint"], 8883, keepalive=30)
    c.loop_start()
    try:
        info = c.publish(topic(cfg["thing"]), payload, qos=1)
        info.wait_for_publish(timeout=TIMEOUT_S)
        return 200 if info.is_published() else 504
    finally:
        c.disconnect()
        c.loop_stop()


def ronde(cfg: dict, nu: int, seq: int, lees: Callable = lees_bron, stuur: Callable | None = None,
          droog: bool = False) -> str:
    """Eén keer lezen en versturen. Gooit nooit: geeft een korte uitkomst voor het log."""
    try:
        doc = lees(cfg["source"])
    except Exception as e:  # noqa: BLE001  (besturing onbereikbaar of rare status: overslaan)
        return f"read failed: {type(e).__name__}"
    msg = bericht(doc, cfg["fields"], nu, seq)
    if msg is None:
        return "nothing to send"
    payload = json.dumps(msg, separators=(",", ":")).encode()
    if len(payload) > MAX_BERICHT_BYTES:
        return "message too large"
    if droog:
        print(payload.decode())
        return "dry run"
    stuur = stuur or (verstuur_mqtt if cfg.get("protocol") == "mqtt" else verstuur_https)
    try:
        status = stuur(cfg, payload)
    except Exception as e:  # noqa: BLE001  (Lutra onbereikbaar: volgende ronde opnieuw)
        return f"send failed: {type(e).__name__}"
    return f"sent {len(msg['pts'])} values, status {status}"


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="Send readings from your own controller to Lutra (write only).")
    ap.add_argument("--config", required=True)
    ap.add_argument("--once", action="store_true", help="one round, then stop")
    ap.add_argument("--dry-run", action="store_true", help="print the message, send nothing")
    a = ap.parse_args(argv)
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
    try:
        cfg = lees_config(a.config)
    except (OSError, ValueError, ConfigFout) as e:
        LOG.error("config: %s", e)
        return 2
    seq = 0
    while True:
        LOG.info(ronde(cfg, int(time.time()), seq, droog=a.dry_run))
        seq += 1
        if a.once:
            return 0
        time.sleep(cfg["interval_s"])


if __name__ == "__main__":
    sys.exit(main())
