#!/usr/bin/env python3
"""Offline analysis of the attached USNO minute-resolution calculation tables."""

import calendar
from datetime import date, datetime, timedelta, timezone
import hashlib
import json
from pathlib import Path
import platform
import re
import sys


BASE = Path(__file__).resolve().parent


def minutes(value):
    if not re.fullmatch(r"\d{4}", value):
        raise ValueError(f"expected HHMM: {value!r}")
    hour, minute = int(value[:2]), int(value[2:])
    if hour > 23 or minute > 59:
        raise ValueError(f"invalid clock reading: {value}")
    return hour * 60 + minute


def clock(value):
    return f"{int(value) // 60:02d}:{int(value) % 60:02d}"


def parse_table(item):
    text, year = item["table_text"], item["year"]
    assert hashlib.sha256(text.encode()).hexdigest() == item["table_sha256"]
    assert f"Rise and Set for the Sun for {year}" in text
    rows = {}
    for line in text.splitlines():
        if not re.match(r"^\d{2}  ", line):
            continue
        day = int(line[:2])
        for month in range(1, 13):
            cell = line[4 + 11 * (month - 1):13 + 11 * (month - 1)]
            if day > calendar.monthrange(year, month)[1]:
                assert not cell.strip()
                continue
            assert re.fullmatch(r"\d{4} \d{4}", cell), (year, month, day, cell)
            rise, setting = map(minutes, cell.split())
            assert rise < setting
            key = date(year, month, day).isoformat()
            assert key not in rows
            rows[key] = {"date": key, "rise": rise, "set": setting,
                         "duration": setting - rise, "midpoint": (rise + setting) / 2}
    assert len(rows) == 365
    return rows


def extrema(rows, key, operation):
    value = operation(r[key] for r in rows)
    return {"minutes": value, "clock": clock(value),
            "dates": [r["date"] for r in rows if r[key] == value]}


def plot_beijing(rows):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    from matplotlib.ticker import FuncFormatter, MaxNLocator

    plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 10,
                         "svg.fonttype": "none", "svg.hashsalt": "gumi-solar-20261027"})
    selected = [r for r in rows if "2026-12-01" <= r["date"] <= "2027-01-15"]
    days = [date.fromisoformat(r["date"]) for r in selected]
    fig, axes = plt.subplots(2, 1, figsize=(9, 6), sharex=True, constrained_layout=True)
    for ax, key, color, operation, title in (
        (axes[0], "rise", "#146b8c", max, "Sunrise: later mornings continue after the solstice"),
        (axes[1], "set", "#b85423", min, "Sunset: evenings turn later before the solstice"),
    ):
        values = [r[key] for r in selected]
        extreme = operation(values)
        tied = [date.fromisoformat(r["date"]) for r in selected if r[key] == extreme]
        ax.plot(days, values, color=color, linewidth=2, marker=".", markersize=4)
        ax.scatter(tied, [extreme] * len(tied), color=color, s=25, zorder=3,
                   label=f"Tied rounded extreme: {clock(extreme)}")
        ax.axvline(date(2026, 12, 22), color="#575757", linestyle="--",
                   linewidth=1.2, label="Solstice date: 12-22")
        ax.set_title(title, loc="left", fontsize=11)
        ax.set_ylabel("Local clock (UTC+8)")
        ax.yaxis.set_major_locator(MaxNLocator(nbins=5, integer=True))
        ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: clock(y)))
        ax.grid(axis="y", color="#dddddd", linewidth=0.7)
        ax.spines[["top", "right"]].set_visible(False)
        ax.legend(loc="lower right", framealpha=0.95, fontsize=9)
        ax.margins(x=0.02, y=0.15)
    axes[1].xaxis.set_major_locator(mdates.DayLocator(interval=7))
    axes[1].xaxis.set_major_formatter(mdates.DateFormatter("%m-%d"))
    axes[1].set_xlabel("Local date: December 2026 to January 2027")
    fig.suptitle("Beijing representative point: 39.90 N, 116.40 E\nUSNO calculated times, rounded to whole minutes", fontsize=12)
    svg_path = BASE / "solar-winter-beijing.svg"
    fig.savefig(svg_path, metadata={"Date": None})
    svg_path.write_text("\n".join(line.rstrip() for line in svg_path.read_text().splitlines()) + "\n")
    fig.savefig("/tmp/gumi-solar-winter-beijing-20261027.png", dpi=160)
    plt.close(fig)
    return matplotlib.__version__


def main():
    snapshot = json.loads((BASE / "solar-winter-usno-snapshot.json").read_text())
    all_rows, annual_counts = {}, []
    for item in snapshot["annual_tables"]:
        place = item["place"]["id"]
        rows = parse_table(item)
        assert not (set(all_rows.get(place, {})) & set(rows))
        all_rows.setdefault(place, {}).update(rows)
        annual_counts.append({"place": place, "year": item["year"], "rows": len(rows)})

    start, end = date(2026, 11, 1), date(2027, 2, 28)
    expected = [(start + timedelta(days=i)).isoformat() for i in range((end - start).days + 1)]
    places = {}
    for place, mapping in all_rows.items():
        winter = [mapping[d] for d in expected]
        point = next(x["place"] for x in snapshot["annual_tables"] if x["place"]["id"] == place)
        places[place] = {
            "representative_point": point,
            "mean_solar_noon_baseline_minutes": 720 + 60 * point["tz"] - 4 * point["longitude"],
            "window_rows": len(winter),
            "earliest_set": extrema(winter, "set", min),
            "latest_rise": extrema(winter, "rise", max),
            "minimum_difference_of_rounded_times": extrema(winter, "duration", min),
            "selected_days": [mapping[d] for d in ("2026-12-10", "2026-12-22", "2027-01-10")],
            "daily_rows": winter,
        }

    noon_checks = []
    for entry in snapshot["beijing_day_checks"]:
        data = entry["response"]["properties"]["data"]
        key = date(data["year"], data["month"], data["day"]).isoformat()
        events = {x["phen"]: x["time"] for x in data["sundata"]}
        row = all_rows["beijing"][key]
        assert events["Rise"] == clock(row["rise"])
        assert events["Set"] == clock(row["set"])
        assert events["Upper Transit"] == clock(row["midpoint"])
        noon_checks.append({"date": key, "upper_transit": events["Upper Transit"],
                            "rounded_midpoint_minutes": row["midpoint"],
                            "end_civil_twilight": events["End Civil Twilight"]})

    a, b = (all_rows["beijing"][d] for d in ("2026-12-10", "2026-12-22"))
    delta = {key: b[key] - a[key] for key in ("rise", "set", "duration", "midpoint")}
    assert delta["rise"] == delta["midpoint"] - delta["duration"] / 2
    assert delta["set"] == delta["midpoint"] + delta["duration"] / 2
    assert delta == {"rise": 8, "set": 4, "duration": -4, "midpoint": 6.0}

    season = next(x for x in snapshot["seasons"]["response"]["data"]
                  if x["phenom"] == "Solstice" and x["month"] == 12)
    utc = datetime.fromisoformat(f'{season["year"]}-{season["month"]:02d}-{season["day"]:02d}T{season["time"]}:00+00:00')
    local_solstice = {name: utc.astimezone(timezone(timedelta(hours=offset))).isoformat()
                      for name, offset in (("beijing", 8), ("tokyo", 9))}
    assert local_solstice["beijing"].startswith("2026-12-22T04:50")
    assert local_solstice["tokyo"].startswith("2026-12-22T05:50")
    for info in places.values():
        assert info["window_rows"] == 120
        assert max(info["earliest_set"]["dates"]) < "2026-12-22"
        assert min(info["latest_rise"]["dates"]) > "2026-12-22"

    report = {"analysis_date": "2026-10-27", "source_retrieved_at_utc": snapshot["retrieved_at_utc"],
              "environment": {"python": platform.python_version(), "macos": platform.mac_ver()[0],
                              "machine": platform.machine()},
              "kind": "analysis of official predictions, not field observations or an independent ephemeris",
              "annual_parse_counts": annual_counts, "window": [start.isoformat(), end.isoformat()],
              "solstice_utc": utc.isoformat(), "solstice_local": local_solstice,
              "places": places, "beijing_day_API_checks": noon_checks,
              "beijing_Dec10_to_Dec22_changes_minutes": delta,
              "checks": ["Four table hashes and 365 valid dates per table",
                         "Blank cells for invalid month dates retained during fixed-width parsing",
                         "120 consecutive winter dates per place across the year boundary",
                         "Two one-day API rise/set/transit comparisons",
                         "Exact midpoint/duration decomposition for the selected Beijing pair",
                         "UTC solstice conversion to both local dates",
                         "Rounded earliest sunset before and latest sunrise after the solstice date"],
              "limits": ["Times rounded to one minute; ties are retained, not ranked by hidden seconds.",
                         "Rounded set minus rounded rise is not a high-precision day length.",
                         "Midpoint defined from endpoints; not generally exact upper transit.",
                         "Fixed UTC offsets; no daylight saving adjustment.",
                         "Representative coordinates, no terrain, observer height or actual weather."]}
    if "--plot" in sys.argv:
        print(f"Plot made with Matplotlib {plot_beijing(places['beijing']['daily_rows'])}", file=sys.stderr)
    json.dump(report, sys.stdout, ensure_ascii=False, indent=2)
    print()


if __name__ == "__main__":
    main()
