#!/usr/bin/env python3
"""
Independent recomputation for the public astronomical-method validation page.

This script deliberately does NOT import any A Star Named code.
It uses:
  - Python zoneinfo (IANA tzdata) for local wall time -> UTC
  - Astropy for the zenith direction (AltAz alt=90 -> ICRS) and nearest-star match

Inputs : scripts/validation/cases.json
Catalog: data/database.json -> celestial_objects (HYG v4.1, J2000.0)
Output : scripts/validation/independent_results.json

Run from the repository root:
    python scripts/validation/independent_check.py
"""
import hashlib
import json
import sys
import warnings
from datetime import datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo

import numpy as np

import astropy
import astropy.units as u
from astropy.coordinates import AltAz, EarthLocation, ICRS, SkyCoord
from astropy.time import Time

warnings.filterwarnings("ignore")

ROOT = Path(__file__).resolve().parents[2]
CASES_PATH = ROOT / "scripts" / "validation" / "cases.json"
DB_PATH = ROOT / "data" / "database.json"
OUT_PATH = ROOT / "scripts" / "validation" / "independent_results.json"


def canonical_star(s: dict) -> list:
    # Fixed-width decimal strings keep the canonical payload byte-identical
    # across Python and JavaScript (avoids float/exponent formatting drift).
    return [
        s["id"],
        s["gaia_source_id"],
        f"{float(s['ra_degrees']):.9f}",
        f"{float(s['dec_degrees']):.9f}",
        f"{float(s['distance_ly']):.6f}",
        f"{float(s['phot_g_mean_mag']):.6f}",
        s["constellation"],
        s["inventory_code"],
        s["data_source"],
        s["epoch"],
    ]


def main() -> int:
    cases = json.loads(CASES_PATH.read_text(encoding="utf-8"))
    db = json.loads(DB_PATH.read_text(encoding="utf-8"))
    stars = db["celestial_objects"]
    if not stars:
        print("empty catalog", file=sys.stderr)
        return 1

    payload = json.dumps(
        [canonical_star(s) for s in sorted(stars, key=lambda x: x["id"])],
        separators=(",", ":"),
        ensure_ascii=False,
    ).encode("utf-8")
    catalog_sha256 = hashlib.sha256(payload).hexdigest()

    catalog = SkyCoord(
        ra=[float(s["ra_degrees"]) for s in stars] * u.deg,
        dec=[float(s["dec_degrees"]) for s in stars] * u.deg,
        frame="icrs",
    )

    out_cases = []
    for c in cases:
        local = datetime.fromisoformat(f"{c['date']}T{c['time']}")
        local = local.replace(tzinfo=ZoneInfo(c["time_zone"]))
        utc = local.astimezone(timezone.utc)
        t = Time(utc, scale="utc")
        loc = EarthLocation(lat=float(c["lat"]) * u.deg, lon=float(c["lon"]) * u.deg)

        # The zenith is the local vertical (alt = 90 deg). Transform that
        # direction into ICRS/J2000, the frame of the HYG catalog.
        zenith = SkyCoord(
            AltAz(alt=90 * u.deg, az=0 * u.deg, obstime=t, location=loc, pressure=0)
        ).transform_to(ICRS())

        # Full-catalog separation scan (no scipy KDTree dependency). On an
        # exact tie, prefer the closer star, matching the product's rule.
        sep = zenith.separation(catalog)
        min_sep = sep.min()
        tied = np.where(sep.deg <= min_sep.deg + 1e-9)[0]
        if len(tied) > 1:
            idx = int(min(tied, key=lambda i: float(stars[int(i)]["distance_ly"])))
        else:
            idx = int(sep.argmin())
        sep2d = sep[idx]
        star = stars[int(idx)]
        out_cases.append(
            {
                "id": c["id"],
                "utc": utc.isoformat(timespec="milliseconds").replace("+00:00", "Z"),
                "utc_ms": int(utc.timestamp() * 1000),
                "zenith_ra_deg": float(zenith.ra.deg),
                "zenith_dec_deg": float(zenith.dec.deg),
                "nearest_star_id": int(star["id"]),
                "nearest_gaia_source_id": star["gaia_source_id"],
                "nearest_inventory_code": star["inventory_code"],
                "nearest_ra_deg": float(star["ra_degrees"]),
                "nearest_dec_deg": float(star["dec_degrees"]),
                "nearest_distance_ly": float(star["distance_ly"]),
                "nearest_mag": float(star["phot_g_mean_mag"]),
                "nearest_constellation": star["constellation"],
                "angular_distance_deg": float(sep2d.deg),
            }
        )

    result = {
        "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"),
        "independent": {
            "library": "astropy",
            "version": astropy.__version__,
            "timezone_source": "Python zoneinfo / IANA tzdata",
        },
        "catalog": {
            "count": len(stars),
            "source": stars[0].get("data_source", "hyg_v41"),
            "epoch": stars[0].get("epoch", "J2000.0"),
            "sha256": catalog_sha256,
        },
        "cases": out_cases,
    }
    OUT_PATH.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print(f"wrote {OUT_PATH} ({len(out_cases)} cases, catalog {len(stars)} stars)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
