"""Check the scores yourself: rebuilds scores.csv and the rankings from the site's downloads, with nothing but Python 3.

    python3 check.py                      # in a folder with forecasts.csv, weather.csv and scores.csv from the Data page
    python3 check.py --month 2026-10      # also print a month's rankings (or --week 2026-10-12, --season 2026-fall, --year 2026)

It picks each forecaster's 9 a.m. forecast for every day from forecasts.csv, scores it against weather.csv, and
compares the result with scores.csv row by row. The rules are the ones on the How it works page:

- The forecast out at 9 a.m.: the latest version put out by then. "Put out" is the station's own published time where
  there is one, if it's no more than 24 hours before the site first read it; else when the site first read it. A
  version last seen more than 24 hours before 9 a.m. doesn't count (the source had stopped).
- High against the day's official high; low against the scored low (weather.csv, scored_low_f). A chance of rain of 50%
  or more calls for rain; without a chance, the forecast's rain call.
- The consensus: for each number, the median of the members' forecasts (halves round up), with at least 3 behind it;
  it calls for rain when more than half of at least 3 calls do.
- Rankings: TV weather teams, 1 day out, the average miss of the high and low on the days every ranked team had a
  forecast out; a team needs forecasts on 80% of the period's scored days.
"""
import argparse
import csv
import datetime as dt
import math
import sys
from collections import defaultdict
from pathlib import Path

CUTOFF = dt.time(9)
BACKDATE = dt.timedelta(hours=24)
LEADS = range(1, 8)
MIN_MEMBERS = 3
TAKE_PART = 0.8
MIN_DAYS = {"week": 5, "month": 20, "season": 60, "year": 250}
TEAMS = "TV weather teams"


def read(path):
    with open(path, newline="", encoding="utf-8-sig") as f:
        return list(csv.DictReader(f))


def num(x):
    if x in ("", None):
        return None
    try:
        return int(x)
    except ValueError:
        return float(x)


def when(s):
    return dt.datetime.fromisoformat(s) if s else None


def published(v):
    seen, issued = v["first_seen"], v["published"]
    return issued if issued and seen - BACKDATE <= issued < seen else seen


def versions(forecast_rows):
    """{source: [version]}, each version {"id", "first_seen", "last_seen", "published", "member", "days": {date: row}}."""
    out = {}
    for r in forecast_rows:
        v = out.setdefault(r["source"], {}).setdefault(int(r["version"]), {
            "id": int(r["version"]), "first_seen": when(r["first_seen"]), "last_seen": when(r["last_seen"]),
            "published": when(r["published"]), "member": r.get("in_consensus") == "1", "kind": r["kind"],
            "name": r["forecaster"], "days": {}})
        v["days"][r["for_date"]] = {"high": num(r["high_f"]), "low": num(r["low_f"]), "pop": num(r["rain_chance_pct"]),
                                    "rain": num(r["rain_forecast"])}
    return {s: sorted(vs.values(), key=lambda v: (v["first_seen"], v["id"])) for s, vs in out.items()}


def version_at(vs, day, tz):
    cutoff = dt.datetime.combine(day, CUTOFF, tz)
    before = [v for v in vs if v["first_seen"] <= cutoff]
    cands = before[-1:] + [v for v in vs if cutoff < v["first_seen"] <= cutoff + BACKDATE and v["published"]]
    cands = [v for v in cands if published(v) <= cutoff]
    if not cands:
        return None
    v = max(cands, key=lambda v: (published(v), v["first_seen"], v["id"]))
    return None if v["last_seen"] < cutoff - BACKDATE else v


def median(xs):
    xs = sorted(xs)
    if not xs:
        return None
    n = len(xs)
    m = xs[n // 2] if n % 2 else (xs[n // 2 - 1] + xs[n // 2]) / 2
    return math.floor(m + 0.5)


def rain_call(f):
    return int(f["pop"] >= 50) if f["pop"] is not None else f["rain"]


def consensus(fcs):
    out = {}
    for k in ("high", "low", "pop"):
        xs = [f[k] for f in fcs if f[k] is not None]
        out[k] = median(xs) if len(xs) >= MIN_MEMBERS else None
    calls = [c for f in fcs if (c := rain_call(f)) is not None]
    out["call"] = int(2 * sum(calls) > len(calls)) if len(calls) >= MIN_MEMBERS else None
    return out


def scores(forecast_rows, weather_rows):
    """The scores, as scores.csv has them: [{column: value}]."""
    obs = {r["date"]: r for r in weather_rows}
    vs = versions(forecast_rows)
    if not vs or not obs:
        return []
    tz = next(v["first_seen"].tzinfo for x in vs.values() for v in x)
    start = min(v["first_seen"] for x in vs.values() for v in x).date()
    last = dt.date.fromisoformat(max(obs))
    out, together = [], defaultdict(list)

    def row(source, name, kind, day, lead, target, f, call, version):
        o = obs[target]
        oh, ol, rained = num(o["high_f"]), num(o["scored_low_f"]), num(o["rained"])
        miss = lambda a, b: None if a is None or b is None else a - b  # noqa: E731
        return {"forecast_made": day, "days_ahead": lead, "for_date": target, "source": source, "forecaster": name, "kind": kind,
                "high_forecast": f["high"], "high_actual": oh, "high_miss": miss(f["high"], oh), "low_forecast": f["low"],
                "low_actual": ol, "low_miss": miss(f["low"], ol), "low_measured_as": o["scored_low_measured_as"],
                "rain_chance_pct": f["pop"], "called_rain": call, "rained": rained, "version": version}

    for source, sv in vs.items():
        day = start
        while day <= last:
            v = version_at(sv, day, tz)
            if v:
                for lead in range(0, max(LEADS) + 1):
                    target = (day + dt.timedelta(days=lead)).isoformat()
                    f = v["days"].get(target)
                    if target not in obs or not f:
                        continue
                    if lead in LEADS:
                        out.append(row(source, v["name"], v["kind"], day.isoformat(), lead, target, f, rain_call(f), v["id"]))
                    if v["member"]:
                        together[(day.isoformat(), lead, target)].append(f)
            day += dt.timedelta(days=1)
    for (day, lead, target), fcs in sorted(together.items()):
        c = consensus(fcs)
        if lead in LEADS and (c["high"] is not None or c["low"] is not None):
            out.append(row("consensus", "Consensus forecast", "Consensus", day, lead, target, c, c["call"], None))
    return out


KEY = ("forecast_made", "days_ahead", "for_date", "source")
COMPARED = ("high_forecast", "high_actual", "low_forecast", "low_actual", "rain_chance_pct", "called_rain", "rained", "version")


def compare(mine, theirs):
    """The differences between rebuilt scores and scores.csv: [text]."""
    norm = lambda r: {k: ("" if r[k] is None else str(r[k])) for k in KEY + COMPARED}  # noqa: E731
    a = {tuple(norm(r)[k] for k in KEY): norm(r) for r in mine}
    b = {tuple(r[k] for k in KEY): {k: r[k] for k in KEY + COMPARED} for r in theirs}
    out = [f"only rebuilt: {' '.join(k)}" for k in a.keys() - b.keys()]
    out += [f"only in scores.csv: {' '.join(k)}" for k in b.keys() - a.keys()]
    for k in a.keys() & b.keys():
        bad = [c for c in COMPARED if a[k][c] != b[k][c]]
        if bad:
            out.append(f"{' '.join(k)}: " + ", ".join(f"{c} {a[k][c] or '-'} vs {b[k][c] or '-'}" for c in bad))
    return sorted(out)


def period(kind, key):
    """'month', '2026-10' -> (start, end)."""
    if kind == "week":
        start = dt.date.fromisoformat(key)
        start -= dt.timedelta(days=start.weekday())
        return start, start + dt.timedelta(days=6)
    if kind == "month":
        start = dt.date.fromisoformat(key + "-01")
        return start, (start + dt.timedelta(days=32)).replace(day=1) - dt.timedelta(days=1)
    if kind == "season":
        year, name = key.split("-")
        first = {"winter": 12, "spring": 3, "summer": 6, "fall": 9}[name]
        start = dt.date(int(year), first, 1)
        end = dt.date(int(year) + (first == 12), (first + 2) % 12 or 12, 1)
        return start, (end + dt.timedelta(days=32)).replace(day=1) - dt.timedelta(days=1)
    return dt.date(int(key), 1, 1), dt.date(int(key), 12, 31)


def standings(score_rows, start, end):
    """The TV teams ranked over a period, as the Rankings page does: (days compared, [(place, source, average miss)])."""
    m = defaultdict(dict)
    kind = {}
    for r in score_rows:
        if str(r["days_ahead"]) != "1" or any(r[k] in (None, "") for k in ("high_forecast", "low_forecast", "high_actual", "low_actual")):
            continue
        d = dt.date.fromisoformat(r["for_date"])
        if start <= d <= end:
            m[r["source"]][d] = (abs(num(r["high_forecast"]) - num(r["high_actual"])), abs(num(r["low_forecast"]) - num(r["low_actual"])))
            kind[r["source"]] = r["kind"]
    scored = {d for by in m.values() for d in by}
    teams = [s for s in m if kind[s] == TEAMS]
    eligible = [t for t in teams if len(m[t]) >= TAKE_PART * len(scored)]
    common = set.intersection(*(set(m[t]) for t in eligible)) if eligible else set()
    if not common:
        return 0, []
    lines = []
    for t in eligible:
        got = [m[t][d] for d in common]
        lines.append((t, (sum(h for h, _ in got) + sum(lo for _, lo in got)) / (2 * len(got))))
    return len(common), sorted(((1 + sum(round(o, 2) < round(x, 2) for _, o in lines), t, x) for t, x in lines), key=lambda r: (r[0], r[1]))


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--dir", default=".", help="the folder with the CSV files (default: here)")
    for k in ("week", "month", "season", "year"):
        ap.add_argument(f"--{k}", help=f"print a {k}'s rankings")
    a = ap.parse_args(argv)
    d = Path(a.dir)
    mine = scores(read(d / "forecasts.csv"), read(d / "weather.csv"))
    diffs = compare(mine, read(d / "scores.csv"))
    print(f"scores.csv: {len(mine)} rows rebuilt from forecasts.csv and weather.csv; "
          + ("all match." if not diffs else f"{len(diffs)} differ:"))
    for x in diffs[:50]:
        print("  " + x)
    for k in ("week", "month", "season", "year"):
        if getattr(a, k):
            start, end = period(k, getattr(a, k))
            n, ranked = standings(mine, start, end)
            last = max((r["for_date"] for r in mine), default="")
            print(f"\n{k} {getattr(a, k)} ({start} to {end}): TV weather teams compared on {n} days"
                  + (" (so far)" if end.isoformat() > last else "" if n >= MIN_DAYS[k] else f" (fewer than {MIN_DAYS[k]}: not final)"))
            for place, s, x in ranked:
                print(f"  {place}. {s}  {x:.2f}°")
    return 1 if diffs else 0


if __name__ == "__main__":
    sys.exit(main())
