"""Satelliitide ülelennud (sgp4 + celestrak TLE). Referentspunkt: Tallinn (piisavalt täpne ülelennu aegadeks).
Kasutus: python passes.py [--hours 24] [--min-el 20] [--sat "METEOR-M2 3" --sat "ISS (ZARYA)" ...]
TLE-d laetakse celestrakist (weather + stations + amateur), vahemälu SDR/captures/tle_*.txt (uuendatakse iga 12 h).
"""
import argparse, math, os, sys, time, urllib.request
from datetime import datetime, timedelta, timezone
from pathlib import Path
from sgp4.api import Satrec, jday

ROOT = Path(__file__).resolve().parent.parent
REF_LAT, REF_LON, REF_ALT = 59.44, 24.75, 0.03          # Tallinn, km
GROUPS = {"weather": "weather", "stations": "stations", "amateur": "amateur"}
DEFAULT_SATS = ["METEOR-M2 3", "METEOR-M2 4", "ISS (ZARYA)", "SO-50", "NOAA 19", "NOAA 15"]
FREQ = {"METEOR-M2 3": "137.900 LRPT", "METEOR-M2 4": "137.900 LRPT (2025+ ka 137.9)", "ISS (ZARYA)": "145.825 APRS / 145.800 hääl",
        "SO-50": "436.795 FM alla / 145.850 üles", "NOAA 19": "137.100 (välja lülitatud 2025)", "NOAA 15": "137.620 (välja lülitatud 2025)"}


def load_tles():
    cache = ROOT / "captures"
    cache.mkdir(exist_ok=True)
    lines = []
    for g in GROUPS:
        f = cache / f"tle_{g}.txt"
        if not f.exists() or time.time() - f.stat().st_mtime > 12 * 3600:
            url = f"https://celestrak.org/NORAD/elements/gp.php?GROUP={g}&FORMAT=tle"
            req = urllib.request.Request(url, headers={"User-Agent": "eeter-sdr/1.0"})
            try:
                f.write_bytes(urllib.request.urlopen(req, timeout=30).read())
            except Exception as e:
                print(f"TLE {g}: {e}", file=sys.stderr)
        if f.exists():
            lines += f.read_text().splitlines()
    sats = {}
    for i in range(0, len(lines) - 2):
        if lines[i + 1].startswith("1 ") and lines[i + 2].startswith("2 "):
            sats[lines[i].strip()] = (lines[i + 1].strip(), lines[i + 2].strip())
    return sats


def look_angles(r_teme, jd, fr):
    """ECI (TEME) -> asimuut/elevatsioon vaatleja suhtes (lihtsustatud, GMST-ga)."""
    # GMST
    t = (jd + fr - 2451545.0) / 36525.0
    gmst = (280.46061837 + 360.98564736629 * (jd + fr - 2451545.0) + 0.000387933 * t * t) % 360
    lat, lon = math.radians(REF_LAT), math.radians(REF_LON)
    theta = math.radians(gmst) + lon                       # vaatleja kohalik siderilne aeg
    Re = 6378.137
    # vaatleja ECI
    ox = Re * math.cos(lat) * math.cos(theta); oy = Re * math.cos(lat) * math.sin(theta); oz = Re * math.sin(lat)
    rx, ry, rz = r_teme[0] - ox, r_teme[1] - oy, r_teme[2] - oz
    # topotsentriline: S (lõuna), E (ida), Z (üles)
    s = math.sin(lat) * math.cos(theta) * rx + math.sin(lat) * math.sin(theta) * ry - math.cos(lat) * rz
    e = -math.sin(theta) * rx + math.cos(theta) * ry
    z = math.cos(lat) * math.cos(theta) * rx + math.cos(lat) * math.sin(theta) * ry + math.sin(lat) * rz
    rng = math.sqrt(s * s + e * e + z * z)
    el = math.degrees(math.asin(z / rng)); az = (math.degrees(math.atan2(e, -s)) + 360) % 360
    return az, el, rng


def passes(name, tle, hours, min_el, step=20):
    sat = Satrec.twoline2rv(*tle)
    t0 = datetime.now(timezone.utc)
    out, cur = [], None
    for k in range(int(hours * 3600 / step)):
        t = t0 + timedelta(seconds=k * step)
        jd, fr = jday(t.year, t.month, t.day, t.hour, t.minute, t.second)
        e, r, v = sat.sgp4(jd, fr)
        if e != 0:
            continue
        az, el, rng = look_angles(r, jd, fr)
        if el > 0:
            if cur is None:
                cur = {"aos": t, "max_el": el, "max_t": t, "az_aos": az}
            elif el > cur["max_el"]:
                cur["max_el"], cur["max_t"] = el, t
            cur["los"], cur["az_los"] = t, az
        elif cur is not None:
            if cur["max_el"] >= min_el:
                out.append(cur)
            cur = None
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--hours", type=float, default=24); ap.add_argument("--min-el", type=float, default=20)
    ap.add_argument("--sat", action="append")
    a = ap.parse_args()
    sats = load_tles()
    names = a.sat or DEFAULT_SATS
    rows = []
    for n in names:
        if n not in sats:
            print(f"{n}: TLE puudub", file=sys.stderr); continue
        for p in passes(n, sats[n], a.hours, a.min_el):
            rows.append((p["aos"], n, p))
    rows.sort()
    loc = datetime.now().astimezone().tzinfo
    print(f"Ülelennud järgmise {a.hours:.0f} h, max elevatsioon >= {a.min_el}°, kohalik aeg:")
    for aos, n, p in rows:
        print(f"  {p['aos'].astimezone(loc):%d.%m %H:%M} – {p['los'].astimezone(loc):%H:%M}  {n:14} max {p['max_el']:4.0f}° kl {p['max_t'].astimezone(loc):%H:%M}"
              f"  {p['az_aos']:3.0f}°→{p['az_los']:3.0f}°  {FREQ.get(n, '')}")


if __name__ == "__main__":
    main()
