#!/usr/bin/env python3
"""
Forwards Inmarsat-C SafetyNET warnings from stdcdec to Submarine Cable Status (https://submarinecablestatus.com/receivers).

stdcdec's stdc_parser sends every decoded packet as JSON over UDP (--out-udp 127.0.0.1 15005). This listens there,
keeps ONLY SafetyNET navigational warnings (EGC packets B1/B2 with service code 0x04, 0x13, 0x24 or 0x31), and posts
them every 30 seconds. Everything else, including private messages to ships and FleetNET, never leaves this computer.

    python3 scs-egc-forward.py --key YOUR-KEY            (standard library only, Python 3.8+)

Options: --port (UDP port to listen on, default 15005), --url (default the site's address), --interval (seconds).
"""
import argparse, gzip, json, socket, sys, threading, time, urllib.request

SAFETYNET_NAV_CODES = {0x04, 0x13, 0x24, 0x31}
EGC_DESCRIPTORS = {0xB1, 0xB2}

def is_safetynet(packet):
    try:
        return int(packet.get("packetDescriptor", -1)) in EGC_DESCRIPTORS and int(packet.get("packetVars", {}).get("messageType", -1)) in SAFETYNET_NAV_CODES
    except (TypeError, ValueError):
        return False

def main():
    ap = argparse.ArgumentParser(description="Forward SafetyNET warnings from stdcdec to Submarine Cable Status")
    ap.add_argument("--key", required=True, help="your receiver key (from the approval email)")
    ap.add_argument("--port", type=int, default=15005, help="UDP port stdc_parser sends to (default 15005)")
    ap.add_argument("--url", default="https://submarinecablestatus.com/api/v1/feed/egc", help=argparse.SUPPRESS)
    ap.add_argument("--interval", type=int, default=30, help="seconds between posts (default 30)")
    a = ap.parse_args()

    batch, lock = [], threading.Lock()
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(("127.0.0.1", a.port))
    print(f"Listening for stdc_parser on udp://127.0.0.1:{a.port}; posting SafetyNET warnings every {a.interval} s", flush=True)

    def listen():
        while True:
            data, _ = sock.recvfrom(65535)
            try:
                packet = json.loads(data.decode("utf-8", "replace"))
            except ValueError:
                continue
            if is_safetynet(packet):
                with lock:
                    batch.append(json.dumps(packet, ensure_ascii=False))

    threading.Thread(target=listen, daemon=True).start()
    while True:
        time.sleep(a.interval)
        with lock:
            lines, batch[:] = list(batch), []
        if not lines:
            continue  # nothing heard: nothing to send
        body = gzip.compress("\n".join(lines).encode("utf-8"))
        req = urllib.request.Request(a.url, data=body, method="POST", headers={"Authorization": f"Bearer {a.key}", "Content-Type": "application/x-ndjson", "Content-Encoding": "gzip", "User-Agent": "scs-egc-forward/1"})
        try:
            with urllib.request.urlopen(req, timeout=20) as r:
                print(time.strftime("%H:%M:%S"), r.read().decode()[:200], flush=True)
        except Exception as e:  # keep going: the next batch tries again
            body_text = getattr(e, "read", lambda: b"")().decode(errors="replace")[:200]
            print(time.strftime("%H:%M:%S"), "post failed:", e, body_text, file=sys.stderr, flush=True)

if __name__ == "__main__":
    main()
