#!/usr/bin/env python3
"""Read-only civil MQTT, RTSP health and NMEA receiver diagnostics. Python 3.8+."""
import argparse
import importlib.util
import json
import os
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit

MAX_BYTES = 131072


def health_module():
    spec = importlib.util.spec_from_file_location("equipment_health", Path(__file__).with_name("equipment-health.py"))
    if spec is None or spec.loader is None:
        raise ValueError("Download equipment-health.py beside this adapter")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def health(device, status):
    if not isinstance(device, str) or not device.strip() or len(device) > 128:
        raise ValueError("Invalid device ID")
    return {"schema": "equipment-health/v1", "device_id": device.strip(),
            "timestamp": datetime.now(timezone.utc).isoformat(), "status": status}


def emit(record):
    print(json.dumps(record, allow_nan=False), flush=True)


def mqtt_record(payload, config):
    if len(payload) > MAX_BYTES:
        raise ValueError("Payload exceeds 128 KiB")
    module = health_module()
    result = module.normalize(json.loads(payload), config)
    if result.get("temperature_c", 0) > 10000:
        raise ValueError("Temperature exceeds diagnostics contract")
    return result


def nmea_health(line, device):
    """Valid RMC/GGA fix state only; coordinates and navigation commands discarded."""
    line = line.strip()
    if len(line) > 1024 or not line.startswith("$") or "*" not in line:
        raise ValueError("Invalid NMEA framing")
    body, checksum = line[1:].rsplit("*", 1)
    calculated = 0
    for char in body:
        if ord(char) > 127:
            raise ValueError("NMEA must be ASCII")
        calculated ^= ord(char)
    if len(checksum) != 2 or calculated != int(checksum, 16):
        raise ValueError("NMEA checksum mismatch")
    fields = body.split(",")
    sentence = fields[0]
    if len(sentence) != 5 or not sentence[:2].isalpha():
        raise ValueError("Invalid sentence identifier")
    kind = sentence[2:]
    if kind == "RMC":
        if len(fields) < 10 or fields[2] not in {"A", "V"}:
            raise ValueError("Invalid RMC status")
        status = "ok" if fields[2] == "A" else "warning"
    elif kind == "GGA":
        if len(fields) < 15 or fields[6] not in set("012345678"):
            raise ValueError("Invalid GGA fix quality")
        # Estimated/manual/simulation modes are not a healthy measured GNSS fix.
        status = "ok" if fields[6] in {"1", "2", "3", "4", "5"} else "warning"
    else:
        raise ValueError("Only RMC and GGA receiver diagnostics accepted")
    return health(device, status)


def rtsp_health(url, device, timeout=10, runner=subprocess.run):
    parsed = urlsplit(url)
    if parsed.scheme not in {"rtsp", "rtsps"} or not parsed.hostname:
        raise ValueError("RTSP or RTSPS URL required")
    if not 1 <= timeout <= 60:
        raise ValueError("Timeout must be 1 to 60 seconds")
    # No shell. Do not print URL, ffprobe stderr or vendor metadata: may contain secrets.
    try:
        result = runner(["ffprobe", "-v", "error", "-rtsp_transport", "tcp", "-show_entries",
                         "stream=codec_type", "-of", "json", url],
                        stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
    except subprocess.TimeoutExpired:
        return health(device, "warning")
    except FileNotFoundError:
        raise ValueError("Install FFmpeg/ffprobe on the local gateway") from None
    if result.returncode != 0:
        return health(device, "warning")
    if len(result.stdout) > MAX_BYTES:
        raise ValueError("Probe output too large")
    data = json.loads(result.stdout)
    available = any(isinstance(s, dict) and s.get("codec_type") == "video"
                    for s in data.get("streams", []))
    return health(device, "ok" if available else "warning")


def receive_mqtt(args):
    try:
        import paho.mqtt.client as mqtt
    except ImportError:
        raise ValueError("Install requirements-civil.txt on the gateway") from None
    if not args.topic or any(char in args.topic for char in "#+\x00"):
        raise ValueError("Use one explicit diagnostics topic; no wildcards")
    if args.plaintext_local and args.host not in {"localhost", "127.0.0.1", "::1"}:
        raise ValueError("Plaintext allowed only on loopback for bench testing")
    with open(args.config, encoding="utf-8") as handle:
        config = json.load(handle)
    health_module().validate_config(config)
    client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
    if not args.plaintext_local:
        client.tls_set(ca_certs=args.ca)
    username = os.environ.get("MQTT_USERNAME")
    password = os.environ.get("MQTT_PASSWORD")
    if password and not username:
        raise ValueError("MQTT_USERNAME required when password is set")
    if username:
        client.username_pw_set(username, password)
    failed = [False]

    def on_connect(c, userdata, flags, reason, properties):
        if reason.is_failure:
            failed[0] = True
            print("MQTT connection refused", file=sys.stderr)
            c.disconnect()
        else:
            c.subscribe(args.topic, qos=1)

    def on_message(c, userdata, message):
        if message.retain or message.topic != args.topic:
            return  # Retained diagnostics must not look like new measurements.
        try:
            emit(mqtt_record(message.payload, config))
        except (ValueError, TypeError, KeyError, OverflowError, UnicodeError):
            print("Rejected MQTT diagnostics record", file=sys.stderr)

    client.on_connect = on_connect
    client.on_message = on_message
    client.connect_timeout = 10
    client.max_queued_messages_set(100)
    port = args.port or (1883 if args.plaintext_local else 8883)
    client.connect(args.host, port, keepalive=30)
    try:
        client.loop_forever()
    finally:
        client.disconnect()
    return 2 if failed[0] else 0


def receive_nmea(args):
    serial_stream = None
    stream = None
    rejected = False
    try:
        if args.serial:
            try:
                import serial
            except ImportError:
                raise ValueError("Install requirements-civil.txt on the gateway") from None
            serial_stream = serial.Serial(args.serial, args.baud, timeout=2, write_timeout=2)
            while True:
                line = serial_stream.read_until(b"\n", 1025)
                if not line:
                    continue
                try:
                    emit(nmea_health(line.decode("ascii"), args.device))
                except (ValueError, UnicodeError):
                    print("Rejected NMEA sentence", file=sys.stderr)
        else:
            stream = sys.stdin if args.input == "-" else open(args.input, encoding="ascii")
            while True:
                line = stream.readline(1026)
                if not line:
                    break
                try:
                    emit(nmea_health(line, args.device))
                except ValueError:
                    rejected = True
                    print("Rejected NMEA sentence", file=sys.stderr)
    finally:
        if serial_stream is not None:
            serial_stream.close()
        if stream is not None and stream is not sys.stdin:
            stream.close()
    return 1 if rejected else 0


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    commands = parser.add_subparsers(dest="command", required=True)
    mqtt = commands.add_parser("mqtt", help="Subscribe to one civil health topic; never publish")
    mqtt.add_argument("--host", required=True)
    mqtt.add_argument("--port", type=int)
    mqtt.add_argument("--topic", required=True)
    mqtt.add_argument("--config", required=True)
    mqtt.add_argument("--ca", help="Local CA certificate file; certificate verification remains enabled")
    mqtt.add_argument("--plaintext-local", action="store_true")
    nmea = commands.add_parser("nmea", help="NMEA receiver fix-health only, no location output")
    nmea.add_argument("--device", required=True)
    sources = nmea.add_mutually_exclusive_group()
    sources.add_argument("--input", default="-")
    sources.add_argument("--serial", help="COM3 on Windows, /dev/ttyUSB0 on Linux, owner-selected port")
    nmea.add_argument("--baud", type=int, choices=[4800, 9600, 19200, 38400, 57600, 115200], default=4800)
    rtsp = commands.add_parser("rtsp", help="One-shot video stream availability probe; no imagery or detections")
    rtsp.add_argument("--device", required=True)
    rtsp.add_argument("--timeout", type=int, default=10)
    args = parser.parse_args()
    try:
        if args.command == "mqtt":
            return receive_mqtt(args)
        if args.command == "nmea":
            return receive_nmea(args)
        url = os.environ.get("RTSP_URL")
        if not url:
            raise ValueError("Set RTSP_URL locally; never paste camera credentials into the platform")
        emit(rtsp_health(url, args.device, args.timeout))
        return 0
    except KeyboardInterrupt:
        return 0
    except Exception:
        # Exceptions from third-party libraries can include credentials or addresses.
        print("Adapter failed. Check local configuration, dependencies and connection permissions; source data withheld.", file=sys.stderr)
        return 2


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