#!/usr/bin/env python3
"""Metamorphose Systems edge daemon (Python 3.8+, standard library only).

Listens on your local network for sensor tracks, sends them each second to the
Metamorphose cueing service, and republishes ranked cues:
  * to a local live feed  http://127.0.0.1:8765/events  (the Swarm defence page connects to it)
  * optionally as Cursor-on-Target to a TAK server / ATAK multicast (--tak host:port)

Inputs (any mix):
  UDP 4242  Cursor-on-Target XML events (radar, RF DF, ATAK, WinTAK)
  UDP 5005  JSON: {"id","lat","lon","altM","speedKmh","headingDeg","cls","confidence","rf"}

Cues are for a human operator. This daemon never commands a weapon.
Usage:
  python3 metamorphose-edge.py --lat 51.50 --lon -0.12 [--tak 239.2.3.1:6969] [--offline]
"""
import argparse, json, socket, threading, time, math, urllib.request, xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

TRACKS, LOCK, SUBS, LATEST = {}, threading.Lock(), [], {"cues": []}
EFFECTORS = [("jam", 3, 1, True), ("laser", 2, 5, False), ("hpm", 1.5, 10, False), ("interceptor", 5, 2000, False), ("gun", 2.5, 6000, False), ("sam", 8, 150000, False)]

def local_cue(site, t):
    """Offline fallback: same rule as the cloud service (range, closing, time-to-go, cheapest in-range effector)."""
    r = 6371.0088; la1, lo1, la2, lo2 = map(math.radians, (site[0], site[1], t["lat"], t["lon"]))
    h = math.sin((la2-la1)/2)**2 + math.cos(la1)*math.cos(la2)*math.sin((lo2-lo1)/2)**2
    km = 2*r*math.asin(min(1, math.sqrt(h)))
    brg = (math.degrees(math.atan2(math.sin(lo2-lo1)*math.cos(la2), math.cos(la1)*math.sin(la2)-math.sin(la1)*math.cos(la2)*math.cos(lo2-lo1)))+360) % 360
    closing = t["speedKmh"]*math.cos(math.radians(t["headingDeg"]-(brg+180) % 360))
    tgo = round(km/closing*3600) if closing > 1 else None
    eff = [e for e in sorted(EFFECTORS, key=lambda e: e[2]) if e[1] >= km and not (e[3] and t.get("rf") is False)]
    pri = "A" if tgo is not None and (tgo <= 60 or km <= 1.5) else "B" if tgo is not None and km <= 5 else "C"
    act = "request-engage" if pri == "A" and eff else "monitor" if pri == "C" else "track"
    return {"id": t["id"], "rangeKm": round(km, 2), "bearingDeg": round(brg), "closingKmh": round(closing), "tGoS": tgo, "priority": pri, "effector": eff[0][0] if eff else None, "action": act}

def parse_cot(data):
    e = ET.fromstring(data); p = e.find("point"); tr = e.find("detail/track")
    return {"id": e.get("uid"), "lat": float(p.get("lat")), "lon": float(p.get("lon")), "altM": float(p.get("hae", 0)),
            "speedKmh": float(tr.get("speed", 0))*3.6 if tr is not None else 0, "headingDeg": float(tr.get("course", 0)) % 360 if tr is not None else 0,
            "cls": e.get("type", "unknown"), "confidence": 0.5}

def listen(port, parser):
    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))
    while True:
        data, _ = s.recvfrom(65535)
        try:
            t = parser(data); t["t"] = int(time.time()*1000)
            with LOCK: TRACKS[t["id"]] = t
        except Exception as ex: print("skipped packet on", port, ex)

def cot_out(t, c):
    iso = lambda ms: time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(ms/1000))
    return (f'<event version="2.0" uid="{t["id"]}" type="a-h-A-M-F-Q" how="m-g" time="{iso(t["t"])}" start="{iso(t["t"])}" stale="{iso(t["t"]+30000)}">'
            f'<point lat="{t["lat"]:.6f}" lon="{t["lon"]:.6f}" hae="{t["altM"]:.0f}" ce="25" le="25"/><detail><track course="{t["headingDeg"]}" speed="{t["speedKmh"]/3.6:.1f}"/>'
            f'<remarks>PRI {c["priority"]} {c["action"]} effector {c["effector"]} tgo {c["tGoS"]}s (cue, human authorisation required)</remarks></detail></event>').encode()

def loop(a):
    tak = None
    if a.tak: h, p = a.tak.split(":"); tak = (h, int(p)); ts = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); ts.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
    while True:
        time.sleep(1); now = time.time()*1000
        with LOCK:
            for k in [k for k, t in TRACKS.items() if now - t["t"] > a.stale*1000]: del TRACKS[k]
            tracks = list(TRACKS.values())
        if not tracks: continue
        body, source = None, "edge"
        if not a.offline:
            try:
                req = urllib.request.Request(a.api, json.dumps({"site": {"lat": a.lat, "lon": a.lon}, "tracks": tracks[:500]}).encode(), {"Content-Type": "application/json"})
                body = json.load(urllib.request.urlopen(req, timeout=2)); source = "cloud"
            except Exception as ex: print("cloud unreachable, cueing locally:", ex)
        if body is None:
            cues = sorted((local_cue((a.lat, a.lon), t) for t in tracks), key=lambda c: ("ABC".index(c["priority"]), c["tGoS"] or 1e9))
            body = {"cues": cues, "inbound": sum(c["closingKmh"] > 1 for c in cues), "priorityA": sum(c["priority"] == "A" for c in cues)}
        body.update(site={"lat": a.lat, "lon": a.lon}, tracks=tracks, source=source); LATEST.clear(); LATEST.update(body)
        msg = f"event: cues\ndata: {json.dumps(body)}\n\n".encode()
        for w in SUBS[:]:
            try: w.write(msg); w.flush()
            except Exception: SUBS.remove(w)
        byid = {t["id"]: t for t in tracks}
        if tak:
            for c in body["cues"]: ts.sendto(cot_out(byid[c["id"]], c), tak)
        top = body["cues"][0]; print(f'{len(tracks)} tracks, {body["priorityA"]} priority A, top {top["id"]} {top["rangeKm"]} km tgo {top["tGoS"]}s -> {top["action"]} ({source})')

class Feed(BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def do_GET(self):
        if self.path.startswith("/events"):
            self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.send_header("Cache-Control", "no-cache")
            self.send_header("Access-Control-Allow-Origin", "*"); self.send_header("Access-Control-Allow-Private-Network", "true"); self.end_headers()
            SUBS.append(self.wfile)
            while self.wfile in SUBS: time.sleep(1)
        else:
            self.send_response(200); self.send_header("Content-Type", "application/json"); self.send_header("Access-Control-Allow-Origin", "*"); self.end_headers()
            self.wfile.write(json.dumps(LATEST).encode())

if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--lat", type=float, required=True); ap.add_argument("--lon", type=float, required=True)
    ap.add_argument("--api", default="https://metamorphosesystems.com/api/public/cuas/assess")
    ap.add_argument("--cot-port", type=int, default=4242); ap.add_argument("--json-port", type=int, default=5005)
    ap.add_argument("--feed-port", type=int, default=8765); ap.add_argument("--tak", help="host:port for CoT cues, e.g. 239.2.3.1:6969")
    ap.add_argument("--stale", type=float, default=10, help="drop tracks not updated for this many seconds")
    ap.add_argument("--offline", action="store_true", help="never call the cloud; cue on this machine only")
    a = ap.parse_args()
    threading.Thread(target=listen, args=(a.cot_port, parse_cot), daemon=True).start()
    threading.Thread(target=listen, args=(a.json_port, lambda d: json.loads(d)), daemon=True).start()
    threading.Thread(target=loop, args=(a,), daemon=True).start()
    print(f"Edge daemon up: CoT UDP {a.cot_port}, JSON UDP {a.json_port}, live feed http://127.0.0.1:{a.feed_port}/events")
    ThreadingHTTPServer(("127.0.0.1", a.feed_port), Feed).serve_forever()
