#!/usr/bin/env python3
"""
LifeAstroAPI Accuracy Lab.

Fixed test vectors, the API's raw JSON for each of them, the NASA JPL Horizons
answers for the same moments and places, and the comparison, written to one
folder you can open, diff or rerun.

  birth     28 birth charts, two in each of 14 metro cities, 1952-2022, several
            under daylight saving or a historic UTC offset. The seven grahas
            from /v1/chart/planets and the lagna and MC from /v1/chart/ascendant,
            against JPL geocentric apparent longitudes and a lagna computed from
            JPL's local apparent sidereal time.
  panchang  The 1st and 15th of every month of 2027 in the same 14 cities, from
            /v1/panchang/basic: sunrise, sunset, moonrise and moonset against the
            moment JPL puts the upper limb on the refracted horizon, every tithi,
            karana, nakshatra and yoga end-time against the moment JPL's Sun and
            Moon reach that boundary, and the tithi, nakshatra and yoga at
            sunrise.

Python 3.9+, standard library only (on Windows also: pip install tzdata).
Credits: birth 560, panchang 6,720 for all 14 cities; --cities picks some,
e.g. one city costs 40 (birth) and 480 (panchang). /v1/meta/ayanamsas and
/v1/meta/version are free.

  export LIFEASTRO_API_KEY=your_key
  python3 accuracy_lab.py --only birth
  python3 accuracy_lab.py --only panchang --cities Delhi,London

Writes to --out: vectors.json, api_responses.jsonl, jpl_responses.jsonl,
birth_grahas.csv, birth_lagna.csv, panchang_riseset.csv, panchang_elements.csv,
panchang_at_sunrise.csv and summary.json. Rerunning with the same --out reuses
the responses already saved there, so an interrupted run costs nothing twice.

To recheck the published comparison without a key or a network, run it on the
unzipped download: python3 accuracy_lab.py --out .
"""
import argparse
import csv
import datetime as dt
import json
import math
import os
import statistics
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

try:
    from zoneinfo import ZoneInfo
except ImportError:  # Python < 3.9
    sys.exit("Python 3.9 or newer is needed (zoneinfo).")

HORIZONS = "https://ssd.jpl.nasa.gov/api/horizons.api"
JPL_ID = {"Sun": "10", "Moon": "301", "Mercury": "199", "Venus": "299", "Mars": "499",
          "Jupiter": "5", "Saturn": "6"}
GRAHAS = list(JPL_ID)
NAK = 360.0 / 27.0
PADA = NAK / 4.0
SIDEREAL_RATE = 15.04106864  # arcsec of sidereal time per second of UT

# name: (latitude, longitude, IANA time zone)
CITIES = {
    "Delhi": (28.6139, 77.2090, "Asia/Kolkata"),
    "Mumbai": (19.0760, 72.8777, "Asia/Kolkata"),
    "Kolkata": (22.5726, 88.3639, "Asia/Kolkata"),
    "Chennai": (13.0827, 80.2707, "Asia/Kolkata"),
    "Bengaluru": (12.9716, 77.5946, "Asia/Kolkata"),
    "Hyderabad": (17.3850, 78.4867, "Asia/Kolkata"),
    "Ahmedabad": (23.0225, 72.5714, "Asia/Kolkata"),
    "Pune": (18.5204, 73.8567, "Asia/Kolkata"),
    "Dubai": (25.2048, 55.2708, "Asia/Dubai"),
    "Singapore": (1.3521, 103.8198, "Asia/Singapore"),
    "London": (51.5074, -0.1278, "Europe/London"),
    "New York": (40.7128, -74.0060, "America/New_York"),
    "Toronto": (43.6532, -79.3832, "America/Toronto"),
    "Sydney": (-33.8688, 151.2093, "Australia/Sydney"),
}

# id, city, local date, local time, note
VECTORS = [
    ("V01", "Delhi", "1952-08-15", "06:05", ""),
    ("V02", "Delhi", "2001-12-02", "23:40", "near local midnight"),
    ("V03", "Mumbai", "1990-01-15", "10:30", "the sample birth used across the docs"),
    ("V04", "Mumbai", "1975-06-25", "04:15", "before sunrise"),
    ("V05", "Kolkata", "1961-03-03", "13:20", ""),
    ("V06", "Kolkata", "2010-10-10", "19:45", ""),
    ("V07", "Chennai", "1968-11-21", "02:50", ""),
    ("V08", "Chennai", "2018-04-14", "08:00", ""),
    ("V09", "Bengaluru", "1984-07-30", "17:25", ""),
    ("V10", "Bengaluru", "2022-01-26", "11:11", ""),
    ("V11", "Hyderabad", "1956-05-09", "21:30", ""),
    ("V12", "Hyderabad", "2005-09-18", "05:55", ""),
    ("V13", "Ahmedabad", "1979-02-27", "15:05", ""),
    ("V14", "Ahmedabad", "2014-08-06", "00:35", "just after local midnight"),
    ("V15", "Pune", "1971-10-19", "09:40", ""),
    ("V16", "Pune", "1998-03-22", "22:10", ""),
    ("V17", "Dubai", "1987-12-24", "07:30", ""),
    ("V18", "Dubai", "2016-05-01", "14:50", ""),
    ("V19", "Singapore", "1965-08-09", "10:00", "historic offset UTC+07:30"),
    ("V20", "Singapore", "2008-02-29", "18:20", "leap day"),
    ("V21", "London", "1969-12-20", "21:56", "winter under British Standard Time (UTC+1 all year, 1968-71)"),
    ("V22", "London", "2003-01-07", "03:15", "winter, UTC+0"),
    ("V23", "New York", "1977-07-13", "21:27", "daylight saving"),
    ("V24", "New York", "2012-11-06", "07:45", "two days after daylight saving ended"),
    ("V25", "Toronto", "1983-04-24", "16:00", "daylight saving"),
    ("V26", "Toronto", "2020-12-31", "23:59", "last minute of the year"),
    ("V27", "Sydney", "1973-10-20", "12:00", "southern hemisphere"),
    ("V28", "Sydney", "2000-09-15", "20:00", "daylight saving started early that year"),
]
PANCHANG_DATES = [f"2027-{m:02d}-{d:02d}" for m in range(1, 13) for d in (1, 15)]


# ── helpers ──────────────────────────────────────────────────────────────────
def jd_of(t):
    return 2440587.5 + t.timestamp() / 86400.0


def wrap180(x):
    return (x + 180.0) % 360.0 - 180.0


def stats(values):
    v = sorted(abs(x) for x in values)
    if not v:
        return {"n": 0}
    return {"n": len(v), "median": round(statistics.median(v), 3),
            "p95": round(v[min(len(v) - 1, int(0.95 * len(v)))], 3), "max": round(v[-1], 3)}


def write_csv(out, name, rows):
    if not rows:
        return
    with open(os.path.join(out, name), "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
        w.writeheader()
        w.writerows(rows)


def jsonl_load(path):
    out = {}
    if os.path.exists(path):
        with open(path) as f:
            for line in f:
                if line.strip():
                    rec = json.loads(line)
                    out[rec["key"]] = rec
    return out


class Api:
    """GET with the key in a header; every response is kept in api_responses.jsonl."""

    def __init__(self, base, key, delay, out):
        self.base, self.key, self.delay = base.rstrip("/"), key, delay
        self.path = os.path.join(out, "api_responses.jsonl")
        self.cache = jsonl_load(self.path)
        self.used = set()

    def get(self, path, fresh=False, **params):
        params = {k: str(v) for k, v in params.items()}
        key = f"{path}?{urllib.parse.urlencode(sorted(params.items()))}"
        self.used.add(key)
        if key in self.cache and not fresh:
            return self.cache[key]["response"]
        if not self.key:
            sys.exit("Set LIFEASTRO_API_KEY or pass --key (free key: https://lifeastroapi.com/signup/)")
        url = f"{self.base}{path}?{urllib.parse.urlencode(params)}"
        req = urllib.request.Request(url, headers={"Authorization": f"Bearer {self.key}"})
        for _ in range(6):
            try:
                with urllib.request.urlopen(req, timeout=60) as r:
                    body = json.loads(r.read())
                break
            except urllib.error.HTTPError as e:
                if e.code == 429:
                    time.sleep(int(e.headers.get("Retry-After", "20")))
                    continue
                sys.exit(f"{path}: HTTP {e.code} {e.read()[:300]!r}")
        else:
            sys.exit(f"{path}: still rate limited")
        rec = {"key": key, "path": path, "params": params, "response": body}
        with open(self.path, "a") as f:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
        self.cache[key] = rec
        time.sleep(self.delay)
        return body


class Jpl:
    """NASA JPL Horizons; every raw answer is kept in jpl_responses.jsonl."""

    def __init__(self, out):
        self.path = os.path.join(out, "jpl_responses.jsonl")
        self.cache = jsonl_load(self.path)
        self.used = set()

    def query(self, params):
        q = {"format": "json", "OBJ_DATA": "'NO'", "MAKE_EPHEM": "'YES'", "EPHEM_TYPE": "'OBSERVER'",
             "ANG_FORMAT": "'DEG'", "EXTRA_PREC": "'YES'", "CSV_FORMAT": "'YES'"}
        q.update({k: f"'{v}'" for k, v in params.items()})
        key = urllib.parse.urlencode(sorted(q.items()))
        self.used.add(key)
        if key in self.cache:
            res = self.cache[key]["result"]
        else:
            for attempt in range(5):
                try:
                    with urllib.request.urlopen(f"{HORIZONS}?{key}", timeout=180) as r:
                        res = json.loads(r.read())["result"]
                    break
                except (urllib.error.URLError, TimeoutError):
                    time.sleep(5 * (attempt + 1))
            else:
                sys.exit("JPL Horizons did not answer")
            rec = {"key": key, "url": f"{HORIZONS}?{key}", "result": res}
            with open(self.path, "a") as f:
                f.write(json.dumps(rec) + "\n")
            self.cache[key] = rec
            time.sleep(0.5)
        if "$$SOE" not in res:
            sys.exit("JPL Horizons error:\n" + res[-2000:])
        body = res[res.index("$$SOE") + 5:res.index("$$EOE")]
        return [[c.strip() for c in line.split(",")] for line in body.strip().splitlines()]


def true_obliquity(jd_ut):
    """IAU 2006 mean obliquity plus the four largest nutation terms (good to ~0.1")."""
    t = (jd_ut + 69.0 / 86400.0 - 2451545.0) / 36525.0
    eps0 = (84381.406 - 46.836769 * t - 0.0001831 * t * t + 0.00200340 * t ** 3) / 3600.0
    r = math.radians
    sun_l, moon_l = r(280.4665 + 36000.7698 * t), r(218.3165 + 481267.8813 * t)
    node = r(125.04452 - 1934.136261 * t)
    deps = 9.20 * math.cos(node) + 0.57 * math.cos(2 * sun_l) + 0.10 * math.cos(2 * moon_l) - 0.09 * math.cos(2 * node)
    return eps0 + deps / 3600.0


def asc_mc(last_deg, lat, eps):
    th, phi, e = math.radians(last_deg), math.radians(lat), math.radians(eps)
    asc = math.degrees(math.atan2(math.cos(th), -(math.sin(th) * math.cos(e) + math.tan(phi) * math.sin(e)))) % 360
    mc = math.degrees(math.atan2(math.sin(th), math.cos(th) * math.cos(e))) % 360
    return asc, mc


def sign_nak_pada(sid):
    sid %= 360.0
    return int(sid // 30), int(sid // NAK), int((sid % NAK) // PADA) + 1


# ── birth charts ─────────────────────────────────────────────────────────────
def run_birth(api, jpl, out, cities):
    vecs = []
    for vid, city, date, hm, note in VECTORS:
        if city not in cities:
            continue
        lat, lon, tz = CITIES[city]
        local = dt.datetime.strptime(f"{date} {hm}", "%Y-%m-%d %H:%M").replace(tzinfo=ZoneInfo(tz))
        utc = local.astimezone(dt.timezone.utc)
        q = dict(date=date, time=hm, tz=tz, lat=lat, lon=lon)
        vecs.append({"id": vid, "city": city, "note": note, "query": q, "utc": utc,
                     "utc_offset": local.strftime("%z"), "jd_ut": jd_of(utc),
                     "planets": api.get("/v1/chart/planets", **q), "asc": api.get("/v1/chart/ascendant", **q)})
    if not vecs:
        return None
    tlist = " ".join(f"{v['jd_ut']:.9f}" for v in vecs)
    ref = {}
    for body, cid in JPL_ID.items():
        # Horizons answers in time order, so match each row to its vector by JD
        rows = jpl.query({"COMMAND": cid, "CENTER": "500@399", "TLIST": tlist, "TLIST_TYPE": "JD",
                          "TIME_TYPE": "UT", "QUANTITIES": "31", "CAL_FORMAT": "JD"})
        for v in vecs:
            r = min(rows, key=lambda r: abs(float(r[0]) - v["jd_ut"]))
            if abs(float(r[0]) - v["jd_ut"]) > 1e-6:
                sys.exit(f"JPL has no row for {v['id']}")
            ref[(v["id"], body)] = float(r[3])

    grahas, lagna = [], []
    for v in vecs:
        p, a = v["planets"], v["asc"]
        ayan = p["ayanamsa_value"]
        base = {"vector": v["id"], "city": v["city"], "local_time": f"{v['query']['date']} {v['query']['time']}",
                "utc_offset": v["utc_offset"], "utc": v["utc"].strftime("%Y-%m-%d %H:%M")}
        for pl in p["planets"]:
            if pl["name"] not in GRAHAS:
                continue
            mine = (pl["sidereal_lon"] + ayan) % 360
            jl = ref[(v["id"], pl["name"])]
            jsnp = sign_nak_pada(jl - ayan)
            asnp = (pl["sign_index"], pl["nakshatra_idx"], pl["pada"])
            grahas.append({**base, "graha": pl["name"], "api_sidereal_deg": f"{pl['sidereal_lon']:.7f}",
                           "api_ayanamsa_deg": f"{ayan:.7f}", "api_tropical_deg": f"{mine:.7f}",
                           "jpl_tropical_deg": f"{jl:.7f}", "diff_arcsec": f"{wrap180(mine - jl) * 3600:.3f}",
                           "api_sign_nakshatra_pada": "%d/%d/%d" % asnp, "jpl_sign_nakshatra_pada": "%d/%d/%d" % jsnp,
                           "same": str(asnp == jsnp).lower()})
        lat = v["query"]["lat"]
        rows = jpl.query({"COMMAND": "10", "CENTER": "coord@399", "COORD_TYPE": "GEODETIC",
                          "SITE_COORD": f"{v['query']['lon']},{lat},0", "TLIST": f"{v['jd_ut']:.9f}",
                          "TLIST_TYPE": "JD", "TIME_TYPE": "UT", "QUANTITIES": "7"})
        last_h = float(rows[0][3])
        eps = true_obliquity(v["jd_ut"])
        j_asc, j_mc = asc_mc(last_h * 15.0, lat, eps)
        # how far the lagna moves per second of birth time here, to express the difference as time
        rate = wrap180(asc_mc(last_h * 15.0 + SIDEREAL_RATE / 3600.0, lat, eps)[0] - j_asc) * 3600.0
        asc = a["ascendant"]
        ayan_a = a["ayanamsa_value"]
        m_asc = (asc["sidereal_lon"] + ayan_a) % 360
        m_mc = (asc["mc"] + ayan_a) % 360
        d_asc = wrap180(m_asc - j_asc) * 3600.0
        jsnp = sign_nak_pada(j_asc - ayan_a)
        asnp = (asc["sign_index"], asc["nakshatra_idx"], asc["pada"])
        lagna.append({**base, "jpl_local_apparent_sidereal_time_h": f"{last_h:.10f}", "true_obliquity_deg": f"{eps:.7f}",
                      "api_lagna_tropical_deg": f"{m_asc:.7f}", "jpl_lagna_tropical_deg": f"{j_asc:.7f}",
                      "lagna_diff_arcsec": f"{d_asc:.3f}", "lagna_diff_as_birth_time_s": f"{d_asc / rate:.3f}",
                      "api_mc_tropical_deg": f"{m_mc:.7f}", "jpl_mc_tropical_deg": f"{j_mc:.7f}",
                      "mc_diff_arcsec": f"{wrap180(m_mc - j_mc) * 3600:.3f}",
                      "api_sign_nakshatra_pada": "%d/%d/%d" % asnp, "jpl_sign_nakshatra_pada": "%d/%d/%d" % jsnp,
                      "same": str(asnp == jsnp).lower()})
    write_csv(out, "birth_grahas.csv", grahas)
    write_csv(out, "birth_lagna.csv", lagna)
    return {
        "vectors": len(vecs),
        "cities": len({v["city"] for v in vecs}),
        "grahas": {"all": stats([float(r["diff_arcsec"]) for r in grahas]),
                   "by_graha": {g: stats([float(r["diff_arcsec"]) for r in grahas if r["graha"] == g]) for g in GRAHAS},
                   "same_sign_nakshatra_pada": sum(r["same"] == "true" for r in grahas), "compared": len(grahas)},
        "lagna": {"arcsec": stats([float(r["lagna_diff_arcsec"]) for r in lagna]),
                  "as_birth_time_s": stats([float(r["lagna_diff_as_birth_time_s"]) for r in lagna]),
                  "mc_arcsec": stats([float(r["mc_diff_arcsec"]) for r in lagna]),
                  "same_sign_nakshatra_pada": sum(r["same"] == "true" for r in lagna), "compared": len(lagna)},
        "unit": "arcsec unless named",
    }


# ── panchang ─────────────────────────────────────────────────────────────────
class Series:
    """Hourly JPL longitudes, unwrapped, with 4-point Lagrange interpolation."""

    def __init__(self, rows):
        self.t0 = float(rows[0][0])
        self.h = float(rows[1][0]) - self.t0
        vals, off, prev = [], 0.0, None
        for r in rows:
            x = float(r[3])
            if prev is not None and x + off < prev - 180:
                off += 360.0
            prev = x + off
            vals.append(prev)
        self.v = vals

    def __call__(self, jd):
        x = (jd - self.t0) / self.h
        i = min(max(int(math.floor(x)) - 1, 0), len(self.v) - 4)
        u = x - i
        p = self.v[i:i + 4]
        return (p[0] * -(u - 1) * (u - 2) * (u - 3) / 6 + p[1] * u * (u - 2) * (u - 3) / 2
                - p[2] * u * (u - 1) * (u - 3) / 2 + p[3] * u * (u - 1) * (u - 2) / 6)


def limb_crossing(jpl, body, lat, lon, jd0, rising):
    """JD when the upper limb meets the refracted horizon, from JPL elevations."""
    rows = jpl.query({"COMMAND": JPL_ID[body], "CENTER": "coord@399", "COORD_TYPE": "GEODETIC",
                      "SITE_COORD": f"{lon},{lat},0", "START_TIME": f"JD{jd0 - 0.005:.6f}",
                      "STOP_TIME": f"JD{jd0 + 0.005:.6f}", "STEP_SIZE": "48", "APPARENT": "REFRACTED",
                      "QUANTITIES": "4,13", "CAL_FORMAT": "JD"})
    pts = [(float(r[0]), float(r[4]) + float(r[5]) / 7200.0) for r in rows]  # elevation + semi-diameter
    for (t1, f1), (t2, f2) in zip(pts, pts[1:]):
        if (rising and f1 < 0 <= f2) or (not rising and f1 >= 0 > f2):
            return t1 + (t2 - t1) * f1 / (f1 - f2)
    return None


def crossing(fn, target, jd_guess):
    """The moment within ±6 h of jd_guess at which angle fn(jd) reaches target (it only increases)."""
    lo, hi = jd_guess - 0.25, jd_guess + 0.25
    flo, fhi = wrap180(fn(lo) - target), wrap180(fn(hi) - target)
    if not (flo < 0 <= fhi):
        return None
    for _ in range(60):
        mid = (lo + hi) / 2
        if wrap180(fn(mid) - target) < 0:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


def run_panchang(api, jpl, out, cities):
    series = {}
    for body in ("Sun", "Moon"):
        rows = jpl.query({"COMMAND": JPL_ID[body], "CENTER": "500@399", "START_TIME": "2026-12-30 00:00",
                          "STOP_TIME": "2028-01-03 00:00", "STEP_SIZE": "1 h", "TIME_TYPE": "UT",
                          "QUANTITIES": "31", "CAL_FORMAT": "JD"})
        series[body] = Series(rows)
    sun, moon = series["Sun"], series["Moon"]

    # Lahiri ayanamsa (a convention, not a measurement) from the free endpoint, one value a day
    ayan = {}
    for d in sorted({(dt.date.fromisoformat(x) + dt.timedelta(days=k)).isoformat()
                     for x in PANCHANG_DATES for k in (-1, 0, 1, 2)}):
        r = api.get("/v1/meta/ayanamsas", date=d, time="00:00", tz="UTC")
        val = next(a["value_deg"] for a in r["ayanamsas"] if a["name"] == "lahiri")
        ayan[jd_of(dt.datetime.fromisoformat(d).replace(tzinfo=dt.timezone.utc))] = val
    ay_pts = sorted(ayan.items())

    def ayanamsa(jd):
        for (t1, a1), (t2, a2) in zip(ay_pts, ay_pts[1:]):
            if t1 <= jd <= t2:
                return a1 + (a2 - a1) * (jd - t1) / (t2 - t1)
        raise SystemExit(f"no ayanamsa sample around JD {jd}")

    angle = {
        "tithi": (lambda t: (moon(t) - sun(t)) % 360, 12.0),
        "karana": (lambda t: (moon(t) - sun(t)) % 360, 6.0),
        "nakshatra": (lambda t: (moon(t) - ayanamsa(t)) % 360, NAK),
        "yoga": (lambda t: (moon(t) + sun(t) - 2 * ayanamsa(t)) % 360, NAK),
    }

    riseset, elements, at_sunrise = [], [], []
    for city in cities:
        lat, lon, tz = CITIES[city]
        for d in PANCHANG_DATES:
            b = api.get("/v1/panchang/basic", date=d, tz=tz, lat=lat, lon=lon)
            base = {"city": city, "date": d}
            jpl_sunrise = None
            for event, body, rising in (("sunrise", "Sun", True), ("sunset", "Sun", False),
                                        ("moonrise", "Moon", True), ("moonset", "Moon", False)):
                jd = b.get(f"{event}_jd")
                if jd is None or (body == "Moon" and not b.get(f"has_{event}", True)):
                    continue
                ref = limb_crossing(jpl, body, lat, lon, jd, rising)
                if event == "sunrise":
                    jpl_sunrise = ref
                riseset.append({**base, "event": event, "api_local": b.get(f"{event}_local", ""),
                                "api_jd": f"{jd:.6f}", "jpl_limb_jd": f"{ref:.6f}" if ref else "",
                                "diff_seconds": f"{(jd - ref) * 86400:.1f}" if ref else "not within ±7 min"})
            items = [("tithi", b["tithi"]), ("nakshatra", b["nakshatra"]), ("yoga", b["yoga"])]
            items += [("karana", k) for k in b["karana"]]
            for el, it in items:
                fn, step = angle[el]
                target = ((it["index"] + 1) * step) % 360
                ref = crossing(fn, target, it["end_jd"])
                elements.append({**base, "element": el, "index": it["index"], "name": it["name"],
                                 "api_end_local": it["end_local"], "api_end_jd": f"{it['end_jd']:.6f}",
                                 "boundary_deg": f"{target:.6f}", "jpl_end_jd": f"{ref:.6f}" if ref else "",
                                 "diff_seconds": f"{(it['end_jd'] - ref) * 86400:.1f}" if ref else "no crossing within ±6 h"})
            if jpl_sunrise:
                for el, it in items[:3]:
                    fn, step = angle[el]
                    jidx = int(fn(jpl_sunrise) // step) % round(360 / step)
                    at_sunrise.append({**base, "element": el, "jpl_sunrise_jd": f"{jpl_sunrise:.6f}",
                                       "api_index": it["index"], "api_name": it["name"], "jpl_index": jidx,
                                       "same": str(jidx == it["index"]).lower()})
    write_csv(out, "panchang_riseset.csv", riseset)
    write_csv(out, "panchang_elements.csv", elements)
    write_csv(out, "panchang_at_sunrise.csv", at_sunrise)

    res = {"cities": len(cities), "days": len(cities) * len(PANCHANG_DATES), "riseset": {}, "end_times": {},
           "at_sunrise": {}}
    for e in ("sunrise", "sunset", "moonrise", "moonset"):
        sel = [r for r in riseset if r["event"] == e]
        res["riseset"][e] = stats([float(r["diff_seconds"]) for r in sel if r["jpl_limb_jd"]])
        res["riseset"][e]["outside_window"] = sum(1 for r in sel if not r["jpl_limb_jd"])
    for el in ("tithi", "karana", "nakshatra", "yoga"):
        # the same end-time shows up in every city that has it on that date: count each moment once
        seen = {}
        for r in elements:
            if r["element"] == el and r["jpl_end_jd"]:
                seen[(r["index"], r["api_end_jd"][:9])] = float(r["diff_seconds"])
        res["end_times"][el] = stats(list(seen.values()))
        res["end_times"][el]["missing"] = sum(1 for r in elements if r["element"] == el and not r["jpl_end_jd"])
    for el in ("tithi", "nakshatra", "yoga"):
        sel = [r for r in at_sunrise if r["element"] == el]
        res["at_sunrise"][el] = {"same": sum(r["same"] == "true" for r in sel), "compared": len(sel)}
    res["unit"] = "seconds"
    return res


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--api", default=os.environ.get("LIFEASTRO_API_URL", "https://api.lifeastroapi.com"))
    ap.add_argument("--key", default=os.environ.get("LIFEASTRO_API_KEY"))
    ap.add_argument("--only", choices=["birth", "panchang"])
    ap.add_argument("--cities", help="comma-separated, default all 14: " + ", ".join(CITIES))
    ap.add_argument("--out", default="accuracy-lab")
    ap.add_argument("--delay", type=float, default=0.7, help="seconds between API calls")
    a = ap.parse_args()
    cities = list(CITIES)
    if a.cities:
        cities = [c.strip() for c in a.cities.split(",") if c.strip()]
        bad = [c for c in cities if c not in CITIES]
        if bad:
            sys.exit(f"unknown city {bad}; choose from {', '.join(CITIES)}")
    os.makedirs(a.out, exist_ok=True)
    api, jpl = Api(a.api, a.key, a.delay, a.out), Jpl(a.out)

    with open(os.path.join(a.out, "vectors.json"), "w") as f:
        json.dump({"cities": {c: dict(zip(("lat", "lon", "tz"), CITIES[c])) for c in cities},
                   "birth": [dict(zip(("id", "city", "date", "time", "note"), v)) for v in VECTORS if v[1] in cities],
                   "panchang_dates": PANCHANG_DATES}, f, indent=2)

    path = os.path.join(a.out, "summary.json")
    summary = {}
    if a.only and os.path.exists(path):  # parts run separately add up
        with open(path) as f:
            summary = json.load(f)
    # without a key everything comes from the saved responses: the comparison is recomputed offline
    summary.update({"generated_at": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
                    "api": a.api if a.key else summary.get("api", "saved responses"),
                    "api_version": api.get("/v1/meta/version", fresh=bool(a.key))})
    for name, fn in (("birth", run_birth), ("panchang", run_panchang)):
        if a.only in (None, name):
            print(f"running {name} …", file=sys.stderr)
            summary[name] = fn(api, jpl, a.out, cities)
    with open(path, "w") as f:
        json.dump(summary, f, indent=2)
    if a.only is None and a.cities is None:
        # a complete run: keep exactly the responses behind this summary, in the order first saved
        for src in (api, jpl):
            keep = [src.cache[k] for k in src.cache if k in src.used]
            with open(src.path, "w") as f:
                for rec in keep:
                    f.write(json.dumps(rec, ensure_ascii=False) + "\n")
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()
