#!/usr/bin/env python3
"""Metamorphose client-feed bridge (Python 3.8+, standard library only).

Relays position reports from the client's own network to the terminal's
CLIENT FEED over WebSocket. Read-only: nothing is ever sent back to a platform.

Inputs (any mix):
  UDP 4242  Cursor-on-Target XML (ATAK / WinTAK / TAK Server output)
  UDP 5005  MAVLink GLOBAL_POSITION_INT as JSON (e.g. from a GCS script)
  UDP 5006  SAPIENT detection reports as JSON (C-UAS radars, RF and acoustic sensors)
  UDP 8600  ASTERIX Cat 048 radar target reports (needs --radar-lat/--radar-lon)
  MAVLink ODOMETRY / VISION_POSITION_ESTIMATE JSON on 5005 (needs --origin-lat/--origin-lon)
  --mcast 239.2.3.1  join a multicast group for CoT (tactical mesh radios, TAK)
  --demo    built-in test platform orbiting --lat/--lon (for setup checks)

Usage:
  python3 client-feed-bridge.py --ws-port 8088 [--demo --lat 26.57 --lon 56.25]
Then in the terminal: CLIENT FEED -> ws://<this-computer>:8088 -> Connect gateway.
For https sites put the port behind TLS (Caddy/Nginx) and use wss://.
"""
import argparse, base64, hashlib, json, math, socket, struct, threading, time

CLIENTS, LOCK = [], threading.Lock()
ALLOWED_ORIGINS = {"https://metamorphosesystems.com", "https://www.metamorphosesystems.com", "https://metamorphosesystems-com.lovable.app"}
GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

CAMERA = None  # (lat, lon, altM) from --camera-lat/--camera-lon/--camera-alt

def camera_cue(text):
    """Slew-to-cue advice: pan/tilt from the fixed camera to a radar/SAPIENT/MAVLink track. Advice only; never commands the camera."""
    try: o = json.loads(text)
    except ValueError: return None
    if not CAMERA or not isinstance(o, dict): return None
    la, lo, al = o.get("lat"), o.get("lon"), o.get("altM")
    if o.get("mavpackettype") == "GLOBAL_POSITION_INT": la, lo, al = o["lat"] / 1e7, o["lon"] / 1e7, o.get("relative_alt", 0) / 1000
    if not isinstance(la, (int, float)) or not isinstance(lo, (int, float)): return None
    c0, r = CAMERA, math.pi / 180
    dla, dlo = (la - c0[0]) * r, (lo - c0[1]) * r
    rng = 2 * 6371000 * math.asin(math.sqrt(math.sin(dla / 2) ** 2 + math.cos(c0[0] * r) * math.cos(la * r) * math.sin(dlo / 2) ** 2))
    pan = (math.degrees(math.atan2(math.sin(dlo) * math.cos(la * r), math.cos(c0[0] * r) * math.sin(la * r) - math.sin(c0[0] * r) * math.cos(la * r) * math.cos(dlo))) + 360) % 360
    tilt = math.degrees(math.atan2((al if isinstance(al, (int, float)) else c0[2]) - c0[2], max(rng, 1)))
    return {"type": "CAMERA_CUE", "track": o.get("id") or o.get("sysid"), "panDeg": round(pan, 1), "tiltDeg": round(tilt, 1), "rangeM": round(rng)}

def broadcast(text):
    data = text.encode()
    if len(data) > 65536: return
    n = len(data)
    head = b"\x81" + (bytes([n]) if n < 126 else b"\x7e" + struct.pack(">H", n) if n < 65536 else b"\x7f" + struct.pack(">Q", n))
    with LOCK:
        for c in CLIENTS[:]:
            try: c.sendall(head + data)
            except OSError: CLIENTS.remove(c); c.close()

def handshake(conn):
    conn.settimeout(5)
    try:
        req = b""
        while b"\r\n\r\n" not in req and len(req) < 4096:
            part = conn.recv(4096 - len(req))
            if not part: conn.close(); return
            req += part
        req = req.decode(errors="ignore")
    except OSError: conn.close(); return
    origin = next((l.split(":", 1)[1].strip() for l in req.split("\r\n") if l.lower().startswith("origin:")), None)
    if origin not in ALLOWED_ORIGINS:
        conn.sendall(b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n"); conn.close(); return
    key = next((l.split(":", 1)[1].strip() for l in req.split("\r\n") if l.lower().startswith("sec-websocket-key:")), None)
    if not key:
        conn.close(); return
    acc = base64.b64encode(hashlib.sha1((key + GUID).encode()).digest()).decode()
    conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
                  f"Sec-WebSocket-Accept: {acc}\r\n\r\n").encode())
    with LOCK: CLIENTS.append(conn)
    print(f"terminal connected ({len(CLIENTS)} open)", flush=True)

def ws_server(port, bind="127.0.0.1"):
    s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((bind, port)); s.listen(8)
    while True:
        c, _ = s.accept(); threading.Thread(target=handshake, args=(c,), daemon=True).start()

ORIGIN, RADAR = None, None

def local_to_geo(lat0, lon0, north, east):
    return lat0 + north / 111320.0, lon0 + east / (111320.0 * math.cos(math.radians(lat0)))

def nav_from_mavlink(o):
    """MAVLink ODOMETRY (#331) / VISION_POSITION_ESTIMATE (#102) in local NED metres -> NAV_STATE."""
    t = o.get("mavpackettype") or o.get("type")
    if t not in ("ODOMETRY", "VISION_POSITION_ESTIMATE") or not ORIGIN: return None
    la, lo = local_to_geo(ORIGIN[0], ORIGIN[1], float(o.get("x", 0)), float(o.get("y", 0)))
    cov = o.get("pose_covariance") or o.get("covariance") or []
    sig = math.sqrt(max(float(cov[0]), float(cov[6]))) if len(cov) > 6 and cov[0] == cov[0] else None
    vx, vy = float(o.get("vx", 0) or 0), float(o.get("vy", 0) or 0)
    return {"type": "NAV_STATE", "id": f"NAV-{o.get('sysid', 1)}", "lat": la, "lon": lo, "altM": -float(o.get("z", 0)),
            "speedMs": math.hypot(vx, vy), "headingDeg": (math.degrees(math.atan2(vy, vx)) + 360) % 360,
            "sigmaM": sig, "mode": "VIO" if t == "ODOMETRY" else "VISION", "gnssDegraded": bool(o.get("gnss_degraded", False))}

def asterix48(data):
    """Decode ASTERIX Cat 048 target reports (I040 polar position, I161 track no., I200 velocity, I090 FL)."""
    out, i = [], 0
    while i + 3 <= len(data):
        cat, ln = data[i], struct.unpack(">H", data[i+1:i+3])[0]
        blk, i = data[i+3:i+ln], i + max(ln, 3)
        if cat != 48: continue
        j = 0
        while j < len(blk):
            frns, k = [], 0
            while True:
                b = blk[j]; j += 1
                frns += [k * 7 + n + 1 for n in range(7) if b & (0x80 >> n)]; k += 1
                if not b & 1: break
            rec, ok = {}, True
            def var():
                nonlocal j
                while blk[j] & 1: j += 1
                j += 1
            for f in frns:
                if f in (1, 5, 6, 11, 17, 19, 21): v = blk[j:j+2]; j += 2
                elif f in (2, 8): j += 3; v = None
                elif f in (4, 12, 13, 15, 18): v = blk[j:j+4]; j += 4
                elif f == 9: j += 6; v = None
                elif f in (3, 14, 16): var(); v = None
                elif f == 7:
                    p = blk[j]; j += 1 + bin(p & 0xFE).count("1")
                    while p & 1: p = blk[j]; j += 1 + bin(p & 0xFE).count("1")
                    v = None
                elif f == 10: j += 1 + 8 * blk[j]; v = None
                else: ok = False; break
                rec[f] = v
            if 4 in rec and RADAR:
                rho = struct.unpack(">H", rec[4][:2])[0] / 256 * 1852; th = math.radians(struct.unpack(">H", rec[4][2:])[0] * 360 / 65536)
                la, lo = local_to_geo(RADAR[0], RADAR[1], rho * math.cos(th), rho * math.sin(th))
                r = {"type": "RADAR_TRACK", "id": f"RDR-{struct.unpack('>H', rec[11])[0] & 0x0FFF}" if 11 in rec else "RDR", "lat": la, "lon": lo}
                if 6 in rec: r["altM"] = (struct.unpack(">h", bytes([rec[6][0] & 0x3F | (0xC0 if rec[6][0] & 0x20 else 0), rec[6][1]]))[0] / 4) * 30.48
                if 13 in rec:
                    r["speedMs"] = struct.unpack(">H", rec[13][:2])[0] * 2 ** -14 * 1852; r["headingDeg"] = struct.unpack(">H", rec[13][2:])[0] * 360 / 65536
                out.append(r)
            if not ok: break
    return out

UL0601 = bytes([0x06,0x0e,0x2b,0x34,0x02,0x0b,0x01,0x01,0x0e,0x01,0x03,0x01,0x01,0x00,0x00,0x00])
def _ber(b, i):
    f = b[i]
    if f < 0x80: return f, 1
    n = f & 0x7f; return int.from_bytes(b[i+1:i+1+n], "big"), 1 + n
def _ts_payload(b):
    if len(b) < 188 or b[0] != 0x47: return b
    out = bytearray()
    for p in range(0, len(b) - 187, 188):
        if b[p] != 0x47: continue
        afc = (b[p+3] >> 4) & 3
        if not afc & 1: continue
        o = p + 4 + (1 + b[p+4] if afc & 2 else 0); out += b[o:p+188]
    return bytes(out)
def klv0601(data, tail=None):
    """STANAG 4609 / MISB ST 0601 metadata from raw KLV or MPEG-TS -> sensor track records (read only).
    Pass a bytearray as tail to reassemble packets split across datagrams; unconsumed bytes stay in it."""
    buf = bytes(tail or b"") + _ts_payload(data); out, i, done = [], 0, 0
    while True:
        i = buf.find(UL0601, i)
        if i < 0 or i + 17 > len(buf): break
        ln, lb = _ber(buf, i + 16); end = i + 16 + lb + ln
        if end > len(buf): done = i; break
        pkt, j, rec, ok, off = buf[i:end], 16 + lb, {}, False, {}
        while j < len(pkt):
            tag = pkt[j]; l, n = _ber(pkt, j + 1); v = pkt[j+1+n:j+1+n+l]; u = int.from_bytes(v, "big")
            s = int.from_bytes(v, "big", signed=True); full = 2 ** (8 * max(l, 1))
            if tag == 1: ok = u == sum(x << (8 * ((k + 1) % 2)) for k, x in enumerate(pkt[:j+2])) & 0xffff
            elif tag == 2: rec["time"] = u / 1e6
            elif tag == 5: rec["heading"] = u * 360 / (full - 1)
            elif tag == 13: rec["lat"] = s * 180 / (full - 2)
            elif tag == 14: rec["lon"] = s * 360 / (full - 2)
            elif tag == 15: rec["alt"] = -900 + u * 19900 / (full - 1)
            elif tag == 23: rec["frame_center_lat"] = s * 180 / (full - 2)
            elif tag == 24: rec["frame_center_lon"] = s * 360 / (full - 2)
            elif 26 <= tag <= 33: off[tag - 26] = s * 0.15 / (full - 2)
            j += 1 + n + l
        if ok and "lat" in rec and "lon" in rec:
            r = {"source": "STANAG4609", "type": "uas_sensor", "id": "uas-klv", **{k: round(v, 7) for k, v in rec.items()}}
            if len(off) == 8 and "frame_center_lat" in rec and "frame_center_lon" in rec:
                r["footprint"] = [[round(rec["frame_center_lat"] + off[2*k], 6), round(rec["frame_center_lon"] + off[2*k+1], 6)] for k in range(4)]
            out.append(r)
        i = done = end
    if tail is not None:
        rest = buf[done:] if done or i >= 0 else buf[-15:]
        tail[:] = rest[-65536:]
    return out

def udp(port, kind, mcast=None):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); s.bind(("0.0.0.0", port))
    if mcast:
        s.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, struct.pack("4s4s", socket.inet_aton(mcast), socket.inet_aton("0.0.0.0")))
    klv_tail = bytearray()
    while True:
        data, _ = s.recvfrom(65536)
        if kind == "klv":
            try: records = klv0601(data, klv_tail)
            except (IndexError, ValueError, TypeError): records = []
            for r in records: broadcast(json.dumps(r))
            continue
        if kind == "asterix":
            try: records = asterix48(data)
            except (IndexError, ValueError, TypeError, struct.error, ZeroDivisionError): records = []
            for r in records:
                broadcast(json.dumps(r)); cue = camera_cue(json.dumps(r))
                if cue: print(json.dumps(cue), flush=True)
            continue
        text = data.decode(errors="ignore").strip()
        if kind == "cot" and "<event" in text: broadcast(text)
        elif kind in ("json", "sapient") and text.startswith("{"):
            try: nav = nav_from_mavlink(json.loads(text)) if kind == "json" else None
            except (ValueError, TypeError, IndexError): nav = None
            broadcast(json.dumps(nav) if nav else text)
            cue = None if nav else camera_cue(text)
            if cue: print(json.dumps(cue), flush=True)

def demo(lat, lon):
    """Test platform with real-life behaviour: cruise ~23 m/s, gusts, gentle climb/descent,
    GPS wobble of a few metres, 1 Hz reports with occasional dropped packets and a 6 s link gap every ~2 min."""
    import random
    t0 = time.time()
    while True:
        t = time.time() - t0
        a = t / 600 * 2 * math.pi
        gust = 1 + 0.08 * math.sin(t / 7) + random.gauss(0, 0.02)
        spd = 23.0 * gust
        hdg = (math.degrees(a) + 90) % 360
        jit = lambda: random.gauss(0, 2.5) / 111200
        la = lat + 0.02 * math.cos(a) + jit()
        lo = lon + (0.02 * math.sin(a) + jit()) / math.cos(math.radians(lat))
        alt = 120 + 15 * math.sin(t / 45) + random.gauss(0, 0.6)
        vx = spd * math.cos(math.radians(hdg)) * 100; vy = spd * math.sin(math.radians(hdg)) * 100
        gap = (t % 120) > 114
        if not gap and random.random() > 0.03:
            broadcast(json.dumps({"mavpackettype": "GLOBAL_POSITION_INT", "evidence": "synthetic", "sysid": 7, "lat": round(la * 1e7), "lon": round(lo * 1e7),
                                  "relative_alt": round(alt * 1000), "hdg": round(hdg * 100), "vx": round(vx), "vy": round(vy)}))
        time.sleep(1)

if __name__ == "__main__":
    p = argparse.ArgumentParser()
    p.add_argument("--ws-port", type=int, default=8088)
    p.add_argument("--bind", default="127.0.0.1", help="WebSocket listen address; keep loopback behind TLS proxy")
    p.add_argument("--allowed-origin", action="append", default=[], help="Additional exact browser origin; never a wildcard")
    p.add_argument("--cot-port", type=int, default=4242)
    p.add_argument("--json-port", type=int, default=5005)
    p.add_argument("--demo", action="store_true"); p.add_argument("--lat", type=float, default=26.57); p.add_argument("--lon", type=float, default=56.25)
    p.add_argument("--sapient-port", type=int, default=5006); p.add_argument("--asterix-port", type=int, default=8600)
    p.add_argument("--mcast", default=None); p.add_argument("--origin-lat", type=float); p.add_argument("--origin-lon", type=float)
    p.add_argument("--radar-lat", type=float); p.add_argument("--radar-lon", type=float)
    p.add_argument("--klv-port", type=int, default=0, help="STANAG 4609 / MISB 0601 KLV or MPEG-TS UDP port (0 = off)")
    p.add_argument("--camera-lat", type=float); p.add_argument("--camera-lon", type=float); p.add_argument("--camera-alt", type=float, default=0)
    a = p.parse_args()
    ALLOWED_ORIGINS.update(a.allowed_origin)
    if a.origin_lat is not None and a.origin_lon is not None: ORIGIN = (a.origin_lat, a.origin_lon)
    if a.radar_lat is not None and a.radar_lon is not None: RADAR = (a.radar_lat, a.radar_lon)
    if a.camera_lat is not None and a.camera_lon is not None: CAMERA = (a.camera_lat, a.camera_lon, a.camera_alt)
    threading.Thread(target=udp, args=(a.cot_port, "cot", a.mcast), daemon=True).start()
    threading.Thread(target=udp, args=(a.sapient_port, "sapient"), daemon=True).start()
    threading.Thread(target=udp, args=(a.asterix_port, "asterix"), daemon=True).start()
    threading.Thread(target=udp, args=(a.json_port, "json"), daemon=True).start()
    if a.klv_port: threading.Thread(target=udp, args=(a.klv_port, "klv", a.mcast), daemon=True).start()
    if a.demo: threading.Thread(target=demo, args=(a.lat, a.lon), daemon=True).start()
    print(f"bridge on ws://{a.bind}:{a.ws_port}  CoT udp:{a.cot_port}  JSON udp:{a.json_port}{'  demo on' if a.demo else ''}", flush=True)
    ws_server(a.ws_port, a.bind)
