"""Reproduce the Quizzman Astro ISS audit with a fixed 2026-07-26 TLE.

Install sgp4==2.25, then run: python3 check_iss.py
To probe a reachable Astro origin, add: --origin https://astro.example
The independent reference uses WGS84, GMST with UTC approximating UT1,
and no polar motion or refraction. Do not use it as a live ISS tracker.
"""
import argparse
import json
import math
from urllib.parse import urlencode
from urllib.request import urlopen

from sgp4.api import Satrec, WGS84

TLE = (
    "1 25544U 98067A   26207.41084145  .00010751  00000+0  20166-3 0  9995",
    "2 25544  51.6317 105.9876 0006941 339.4731  20.5977 15.49181604577830",
)
SAT = Satrec.twoline2rv(*TLE, WGS84)
EPOCH = SAT.jdsatepoch + SAT.jdsatepochF
# Origin observations on 2026-11-09, elevation=0 and refraction=none.
CASES = (
    ("matched", -57.9853756307, -164.0726625097,
     (11517.999921798304, 2.10012380445056, 86.63726057494421, True)),
    ("equator", 0.0, 0.0,
     (1654.649320175976, 11.96358646940693, 270.00014966597297, True)),
    ("Honolulu", 21.3069, -157.8583,
     (12913.22887043663, 9.475992252902158, 93.73236775903308, True)),
)


def reference(jd, lat_deg, lon_deg):
    whole = math.floor(jd)
    status, (x, y, z), _ = SAT.sgp4(whole, jd - whole)
    if status:
        raise RuntimeError(f"SGP4 status {status}")
    d = jd - 2451545.0
    t = d / 36525.0
    theta = math.radians(
        (280.46061837 + 360.98564736629 * d + 0.000387933 * t*t - t**3 / 38710000) % 360
    )
    c, s = math.cos(theta), math.sin(theta)
    lat, lon = map(math.radians, (lat_deg, lon_deg))
    cp, sp, cl, sl = math.cos(lat), math.sin(lat), math.cos(lon), math.sin(lon)
    f = 1 / 298.257223563
    e2 = f * (2 - f)
    n = 6378.137 / math.sqrt(1 - e2 * sp*sp)
    dx, dy, dz = x*c + y*s - n*cp*cl, -x*s + y*c - n*cp*sl, z - n*(1-e2)*sp
    east = -sl*dx + cl*dy
    north = -sp*cl*dx - sp*sl*dy + cp*dz
    up = cp*cl*dx + cp*sl*dy + sp*dz
    alt = math.degrees(math.atan2(up, math.hypot(east, north)))
    az = math.degrees(math.atan2(east, north)) % 360
    return math.hypot(dx, dy, dz), alt, az, alt > 0


def query(origin, lat, lon):
    params = urlencode(dict(jd=EPOCH, lat=lat, lon=lon, refraction="none", elevation=0, magLimit=0))
    with urlopen(f"{origin.rstrip('/')}/viewer/sky?{params}", timeout=20) as response:
        return json.load(response)["data"]["iss"]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--origin", help="Reachable Astro origin; omit to use recorded API output.")
    args = parser.parse_args()
    print("case       source     range km       alt deg       az deg  above horizon")
    for name, lat, lon, captured in CASES:
        rows = [("capture", captured), ("reference", reference(EPOCH, lat, lon))]
        if args.origin:
            live = query(args.origin, lat, lon)
            print(f"{name}: live TLE epoch={live['tle_epoch']}; compare only with the same TLE")
            rows.append(("live API", tuple(live[k] for k in ("range_km", "alt", "az", "visible"))))
        for source, (distance, alt, az, above) in rows:
            print(f"{name:<10} {source:<9} {distance:11.3f}  {alt:12.6f} {az:12.6f}  {above}")


if __name__ == "__main__":
    main()
