#!/usr/bin/env python3
"""Volatile console inspection of local RTL-SDR observations and weather candidates."""

import argparse
from collections import Counter, deque
from datetime import datetime, timezone
import json
import math
from pathlib import Path
import select
import shutil
import socket
import subprocess
import sys
import tempfile
import time


class BeastParser:
    """Parse escaped Beast frames, retaining partial frames between TCP reads."""

    def __init__(self):
        self.kind = None
        self.data = bytearray()
        self.escape = False

    def feed(self, chunk):
        frames = []
        for value in chunk:
            if self.escape:
                self.escape = False
                if value != 0x1A:
                    self.kind = value if value in (0x31, 0x32, 0x33) else None
                    self.data.clear()
                    continue
            elif value == 0x1A:
                self.escape = True
                continue
            if self.kind is None:
                continue
            self.data.append(value)
            length = {0x31: 9, 0x32: 14, 0x33: 21}[self.kind]
            if len(self.data) == length:
                frames.append((self.kind, bytes(self.data)))
                self.kind = None
                self.data.clear()
        return frames


def weather_candidate(aircraft):
    """Derive candidates; schema-2 inputs additionally require bounded timing skew."""
    metadata = aircraft.get("weather_provenance")
    flags = ["EXPERIMENTAL"]
    if metadata is None:
        flags.extend(["FIELD_AGES_UNKNOWN", "FRAME_LINK_UNKNOWN"])
    else:
        flags.extend(["FIELD_RECEPTION_TIMES_KNOWN", "MEASUREMENT_TIMES_UNKNOWN"])
    result = {"flags": flags, "wind": None, "temperature": None}
    if aircraft.get("seen", math.inf) > 10:
        flags.append("STALE_TRACK")
        return result
    if aircraft.get("seen_pos", math.inf) > 10 or not all(
        key in aircraft for key in ("lat", "lon")
    ):
        flags.append("NO_FRESH_POSITION")
        return result
    if aircraft.get("alt_baro") == "ground":
        flags.append("GROUND")
        return result
    if "roll" not in aircraft or "track_rate" not in aircraft:
        flags.append("MANEUVER_QC_PARTIAL")
    if abs(aircraft.get("roll", 0)) > 5 or abs(aircraft.get("track_rate", 0)) > 1:
        flags.append("TURNING")
        return result
    keys = ("gs", "tas", "track", "true_heading")
    if all(key in aircraft for key in keys):
        gs, tas = aircraft["gs"], aircraft["tas"]
        if 50 < tas < 750 and 0 <= gs < 900:
            track = math.radians(aircraft["track"])
            heading = math.radians(aircraft["true_heading"])
            east = gs * math.sin(track) - tas * math.sin(heading)
            north = gs * math.cos(track) - tas * math.cos(heading)
            speed = math.hypot(east, north)
            if speed <= 250:
                direction = math.degrees(math.atan2(-east, -north)) % 360
                result["wind"] = (direction if speed > 0.1 else None, speed * 0.514444)
            else:
                flags.append("WIND_RANGE")
        else:
            flags.append("SPEED_RANGE")
    else:
        flags.append("WIND_INPUT_MISSING")
    if "tas" in aircraft and "mach" in aircraft:
        tas, mach = aircraft["tas"], aircraft["mach"]
        if 50 < tas < 750 and 0.395 <= mach <= 1.2:
            temperature = 288.15 * (tas / (661.47 * mach)) ** 2 - 273.15
            if -100 <= temperature <= 60:
                result["temperature"] = temperature
            else:
                flags.append("TEMP_RANGE")
        else:
            flags.append("TEMP_INPUT_RANGE")
    else:
        flags.append("TEMP_INPUT_MISSING")
    if metadata is not None:
        reference = aircraft["_snapshot_utc"]
        if reference is None:
            flags.append("SNAPSHOT_TIME_UNKNOWN")
            result["wind"] = result["temperature"] = None
            return result
        fields = metadata["fields"]

        def coherent(names):
            items = [fields[name] for name in names]
            times = [item["updated_utc"] for item in items]
            return (all(item["valid"] and not item["stale"] for item in items)
                    and all(-.1 <= reference-t <= 5 for t in times)
                    and max(times)-min(times) <= 2)

        context = ("position", "alt_baro", "roll", "track_rate")
        if not coherent(context):
            flags.append("CONTEXT_TIMING_REJECTED")
            result["wind"] = result["temperature"] = None
        if not coherent(("gs", "tas", "track", "true_heading")):
            flags.append("WIND_TIMING_REJECTED")
            result["wind"] = None
        if not coherent(("tas", "mach")):
            flags.append("TEMP_TIMING_REJECTED")
            result["temperature"] = None
        heading = fields["true_heading"]
        if heading["source"] == 1:
            declination = metadata["declination"]
            if (metadata["magnetic_model"] != "WMM2025"
                    or not 2025 <= declination["year"] < 2030
                    or not -.1 <= reference-declination["updated_utc"] <= 10):
                flags.append("HEADING_CORRECTION_REJECTED")
                result["wind"] = None
        if any(fields[k].get("message") is None for k in ("gs", "tas", "track", "true_heading", "mach")):
            flags.append("PARTIAL_FRAME_LINK")
    return result


def value(aircraft, key, precision=1):
    item = aircraft.get(key)
    if item is None:
        return "--"
    if isinstance(item, (int, float)):
        return f"{item:.{precision}f}"
    return str(item)


def render(snapshot, raw, counts, receiver, elapsed, rate, width=160):
    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    age = time.time() - snapshot["now"] if "now" in snapshot else None
    aircraft = [a for a in snapshot.get("aircraft", []) if a.get("seen", 999) <= 10]
    stale = age is not None and age > 5
    candidates = [
        (a, {"flags": ["STALE_SNAPSHOT"], "wind": None, "temperature": None}
         if stale else weather_candidate({**a, "_snapshot_utc": snapshot.get("now")}))
        for a in aircraft
    ]
    candidates.sort(key=lambda pair: (
        pair[1]["wind"] is None and pair[1]["temperature"] is None,
        pair[0].get("seen_pos", 999), pair[0]["hex"],
    ))
    wind_count = sum(c["wind"] is not None for _, c in candidates)
    temp_count = sum(c["temperature"] is not None for _, c in candidates)
    lines = [
        f"ADS-B / MODE-S WETTER-LIVE | {now} | Ctrl+C beendet und gibt SDR frei",
        f"Empfaenger: {receiver} | Laufzeit {elapsed:.0f}s | NUR RAM, kein Archiv, kein Feed",
        f"Beast-Frames: {sum(counts.values())} | {rate:.1f}/s | aktive Tracks: {len(aircraft)}"
        f" | Windkandidaten: {wind_count} | Temperaturkandidaten: {temp_count}",
        "DF-Zaehler: " + (" ".join(f"{key}={count}" for key, count in sorted(counts.items())) or "warte auf Empfang"),
        f"JSON-Alter: {age:.1f}s" if age is not None else "JSON: warte auf Decoder",
        "",
        "FLUGDATEN / WETTERKANDIDATEN (keine validierten meteorologischen Beobachtungen)",
        "ICAO   Flug       Lat      Lon   Hbaro/ft Hgeom/ft PosAge RSSI/dBFS  Wind-von/m/s   OAT/C  NIC NACp SIL",
    ]
    for a, c in candidates[:12]:
        wind = c["wind"]
        direction = "--" if wind is None or wind[0] is None else f"{wind[0]:.0f}"
        wind_text = "--" if wind is None else f"{direction}/{wind[1]:.1f}"
        temperature = "--" if c["temperature"] is None else f"{c['temperature']:.1f}"
        lines.append(
            f"{a['hex']:6} {str(a.get('flight', '--')).strip():8.8} "
            f"{value(a, 'lat', 3):>8} {value(a, 'lon', 3):>8} "
            f"{value(a, 'alt_baro', 0):>8} {value(a, 'alt_geom', 0):>8} "
            f"{value(a, 'seen_pos'):>6} {value(a, 'rssi'):>9} {wind_text:>13} "
            f"{temperature:>7} {value(a, 'nic', 0):>4} {value(a, 'nac_p', 0):>4} {value(a, 'sil', 0):>3}"
        )
    if not candidates:
        lines.append("Noch keine frischen Flugzeug-Tracks. Position braucht ggf. mehrere CPR-Meldungen.")
    lines.extend(["", "EINGABEN / QUALITAET (bis zu 3 Tracks; '--' = nicht empfangen/verfuegbar)"])
    for a, c in candidates[:3]:
        lines.append(
            f"{a['hex']}: GS={value(a, 'gs')} TAS={value(a, 'tas')} kt "
            f"Track={value(a, 'track')} TrueHdg={value(a, 'true_heading')} deg "
            f"Mach={value(a, 'mach', 3)} Roll={value(a, 'roll')} "
            f"TrackRate={value(a, 'track_rate')} deg/s"
        )
        lines.append("  Flags: " + ",".join(c["flags"]))
    lines.extend([
        "",
        "LETZTE ROHMELDUNGEN: UTC-Ankunft | DF | Signal/dBFS | SDR-Ticks(12MHz) | Hex",
        *raw,
        "",
        "Wind: Bodenvektor - Luftvektor (TAS/TrueHdg); Richtung meteorologisch VON, Geschwindigkeit m/s.",
        "OAT: 288.15*(TAS/(661.47*Mach))^2-273.15; ISA-Schallgeschwindigkeitsbezug, keine Direktmessung.",
        "Quelle: readsb-Snapshot; Schema 2 exportiert Feld-Empfangszeiten/-meldungen. Flags zeigen Luecken.",
        "Unsicherheit: NICHT QUANTIFIZIERT; keine Nudging-Freigabe. RSSI relativ dBFS, nicht dBm.",
        "Hbaro = Druckhoehe, Hgeom = geometrische Hoehe; NIC/NACp/SIL sind KEINE Wetterfehlergrenzen.",
        "BDS44/45-Direktwetter wird hier NICHT separat identifiziert; fehlende Werte sind keine Nullen.",
        "Beast zeigt decoder-akzeptierte Meldungen, nicht alle Funkereignisse/CRC-Fehler.",
        "UTC ist Software-Ankunftszeit (Pufferlatenz); SDR-Ticks sind keine absolute UTC-Uhr.",
    ])
    if stale:
        lines.insert(5, "WARNUNG: Decoder-JSON veraltet; Werte nicht als aktuell verwenden!")
    return "\n".join(line[:width] for line in lines)


def run(args):
    parser = BeastParser()
    counts = Counter()
    raw = deque(maxlen=5)
    snapshot = {}
    started = time.monotonic()
    last_draw = started
    last_count = 0
    receiver = f"{socket.gethostname()}/rtl-sdr:{args.device}"
    if not Path("/dev/shm").is_dir():
        raise RuntimeError("/dev/shm fehlt; keine Ausweichdateien auf persistentem Speicher")
    with tempfile.TemporaryDirectory(prefix="adsb-live-", dir="/dev/shm") as directory:
        log_path = Path(directory) / "decoder.log"
        command = [
            args.decoder, "--device-type", "rtlsdr", "--device", args.device,
            "--gain", str(args.gain), "--freq", "1090000000", "--quiet",
            "--net", "--net-bind-address", "127.0.0.1",
            "--net-bo-port", str(args.port), "--net-verbatim",
            "--write-json", directory, "--write-json-every", "1",
        ]
        with log_path.open("w+") as log:
            process = subprocess.Popen(command, stdout=log, stderr=log)
            connection = None
            try:
                deadline = time.monotonic() + 15
                while connection is None:
                    if process.poll() is not None:
                        raise RuntimeError("Decoder-Start fehlgeschlagen: " + log_path.read_text())
                    try:
                        connection = socket.create_connection(("127.0.0.1", args.port), timeout=0.2)
                    except (ConnectionRefusedError, socket.timeout):
                        if time.monotonic() > deadline:
                            raise RuntimeError("Kein Beast-Port nach 15s: " + log_path.read_text())
                        time.sleep(0.1)
                while not args.duration or time.monotonic() - started < args.duration:
                    if process.poll() is not None:
                        raise RuntimeError("Decoder unerwartet beendet: " + log_path.read_text())
                    readable, _, _ = select.select([connection], [], [], 0.2)
                    if readable:
                        chunk = connection.recv(65536)
                        if not chunk:
                            raise RuntimeError("Beast-Verbindung geschlossen: " + log_path.read_text())
                        for kind, frame in parser.feed(chunk):
                            if kind == 0x31:
                                continue
                            payload = frame[7:]
                            df = payload[0] >> 3
                            counts[f"DF{df:02}"] += 1
                            signal = frame[6]
                            dbfs = f"{20 * math.log10(signal / 255):.1f}" if signal else "n/a"
                            timestamp = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
                            raw.append(
                                f"{timestamp} DF{df:02} {dbfs:>6} "
                                f"{int.from_bytes(frame[:6], 'big'):012x} {payload.hex().upper()}"
                            )
                    current = time.monotonic()
                    if current - last_draw >= 1:
                        path = Path(directory) / "aircraft.json"
                        if path.exists():
                            snapshot = json.loads(path.read_text())
                        count = sum(counts.values())
                        screen = render(
                            snapshot, raw, counts, receiver, current - started,
                            (count - last_count) / (current - last_draw),
                            shutil.get_terminal_size((160, 45)).columns,
                        )
                        if sys.stdout.isatty() and not args.plain:
                            print("\033[H\033[2J" + screen, flush=True)
                        else:
                            print(screen + "\n", flush=True)
                        last_draw, last_count = current, count
            finally:
                if connection is not None:
                    connection.close()
                if process.poll() is None:
                    process.terminate()
                    try:
                        process.wait(timeout=8)
                    except subprocess.TimeoutExpired:
                        process.kill()
                        process.wait()
                        print("WARNUNG: Decoder musste nach 8s zwangsbeendet werden.", file=sys.stderr)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--decoder", default="/opt/adsb/readsb")
    parser.add_argument("--device", default="00000010")
    parser.add_argument("--gain", type=float, default=40.2)
    parser.add_argument("--port", type=int, default=30905)
    parser.add_argument("--duration", type=float, default=0, help="Sekunden; 0 = bis Ctrl+C")
    parser.add_argument("--plain", action="store_true", help="Bildschirme ohne ANSI ausgeben")
    args = parser.parse_args()
    if args.duration < 0 or not 1 <= args.port <= 65535:
        parser.error("duration muss >= 0 sein, port zwischen 1 und 65535")
    try:
        # Refuse an occupied port instead of accidentally reading another receiver.
        with socket.socket() as probe:
            probe.bind(("127.0.0.1", args.port))
        run(args)
    except KeyboardInterrupt:
        print("\nLive-Ansicht beendet. Keine Beobachtungen archiviert.")
    except (OSError, RuntimeError, ValueError) as error:
        print(f"FEHLER: {error}", file=sys.stderr)
        return 1
    return 0


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