"""How New York's summers have warmed against eleven other big cities': the analysis behind a SparkyData article.

    py src/build_article.py summer-heat-in-twelve-cities

Each city's summers (June to August) at the station its weather service keeps for it (card
``world_city_summers``): New York at Central Park, its official record, and at LaGuardia and JFK airports; London at
Heathrow, from the Met Office's own monthly means; Paris at Montsouris; Toronto at its downtown station; Tokyo at
JMA's station 47662, put on the Kitanomaru Park site's basis before its December 2014 move with JMA's own
corrections; Berlin at Tempelhof; Vienna at Hohe Warte (GeoSphere Austria); Seoul at KMA's station 108; Hong Kong at the Observatory;
Singapore at Changi; Los Angeles at LAX; Chicago at O'Hare. A summer's mean daily maximum (the afternoon high) and
mean daily minimum (the night's low) are the means of its three monthly means.

The comparison is each station against itself: the last ten summers (2017-2026) against 1991-2000, with a 90% range
from the summers' own spread (``sparkylib.stats.mean_difference``), named only when it clears zero on the unrounded
range. Whether one city warmed more than another is tested on each year's difference between the two stations, so a
summer that was hot in both cancels: every other city against both New York airports, Central Park against the
airports, the five largest afternoon changes against one another, and Chicago's nights against the next three. The
long view runs from 1960, when every station's record is complete, as each summer's departure from the station's
own 1961-1990 average. The current reading is the 2026 summer, complete in every file. Two sensitivities are
computed: the decade windows moved a year, and Toronto's older station put on its newer one's basis.

Temperatures are kept in degrees Celsius, as every weather service publishes them, and printed in Fahrenheit first
for the site's readers (a change times 1.8; a level times 1.8 plus 32). How each city responds to heat comes from its
own published plan or warning rule, quoted (``A.quotes``), never from the temperature files.

Writes results.json, viz.json, charts.json, data.csv and build.json into
output/articles/summer_heat_in_twelve_cities/ and site/public/articles/summer-heat-in-twelve-cities/, and copies this
script there as analysis.py. Deterministic: no sampling, and SEED is kept for any resampling.
"""

from __future__ import annotations

import math
from itertools import combinations

import pandas as pd

from article_kit import Article, lines, r, strip
from nycdata import world_weather as W
from sparkylib.stats import autocorrelation, mean_difference, mean_difference_ar1

SLUG = "summer-heat-in-twelve-cities"
SEED = 20261104
BEFORE = (1991, 2000)            # the first ten summers of the record every station has
AFTER = (2017, 2026)             # the last ten summers
SHIFTED = [((1991, 2000), (2016, 2025)), ((1992, 2001), (2017, 2026))]   # the sensitivity to the windows' ends
LONG_FROM = 1960                 # every station's summers are complete from here
BASE = (1961, 1990)              # the long view's reference period (WMO's old standard normals)
NOW = 2026
#: the rows the page compares, New York first at its three stations, then the eleven other cities
ROWS = [("laguardia", "New York, LaGuardia"), ("jfk", "New York, JFK"), ("central_park", "New York, Central Park"),
        ("heathrow", "London, Heathrow"), ("montsouris", "Paris, Montsouris"), ("berlin", "Berlin, Tempelhof"),
        ("vienna", "Vienna, Hohe Warte"), ("toronto_city", "Toronto, downtown"), ("chicago", "Chicago, O'Hare"),
        ("los_angeles", "Los Angeles, LAX"), ("tokyo", "Tokyo"), ("seoul", "Seoul"), ("hong_kong", "Hong Kong Observatory"),
        ("singapore", "Singapore, Changi")]
NEW_YORK = ("laguardia", "jfk")  # the two stations New York's comparisons use (Central Park shown beside them)
OTHERS = tuple(k for k, _ in ROWS if k not in NEW_YORK + ("central_park",))
CITY_OF = {k: W.SITES[k][0] for k, _ in ROWS}
LONG_LINES = [("laguardia", "New York (LaGuardia)", "New York"), ("heathrow", "London (Heathrow)", "London"),
              ("montsouris", "Paris (Montsouris)", "Paris"), ("vienna", "Vienna (Hohe Warte)", "Vienna"),
              ("tokyo", "Tokyo", "Tokyo"), ("hong_kong", "Hong Kong", "Hong Kong")]
RELOCATION = ("jma_tokyo_relocation_notice_2014", "jma_tokyo_relocation_20141202.html")
CORRECTION_DOC = ("jma_temperature_correction_method", "jma_temperature_correction.html")
SUMMER_DAYS = 92


def f_level(c: float) -> float:
    return c * 1.8 + 32


def f_change(c: float) -> float:
    return c * 1.8


def add_f(d: dict, levels: bool = True) -> dict:
    """Fahrenheit copies of a mean_difference node's change, range and the two period means (the node's values are
    kept to 0.0001 C, so the Fahrenheit copies are exact at a tenth; decisions use the node's direction). The period
    means of a contrast node are differences, not temperatures: ``levels=False`` converts them as changes."""
    d["change_f"] = r(f_change(d["change"]), 1) + 0.0            # + 0.0 turns a -0.0 into 0.0
    d["lo_f"], d["hi_f"] = r(f_change(d["lo"]), 1) + 0.0, r(f_change(d["hi"]), 1) + 0.0
    if "before" in d:
        conv = f_level if levels else f_change
        d["before_f"], d["after_f"] = r(conv(d["before"]), 1) + 0.0, r(conv(d["after"]), 1) + 0.0
    return d


def md(before, after) -> dict:
    """mean_difference kept to four decimals (0.0001 C), so ranks and conversions do not turn on rounding."""
    return mean_difference(before, after, nd=4)


def up(d: dict) -> bool:
    return d["direction"] == "up"


def main(argv: list[str] | None = None) -> int:
    """Run the analysis and write every file (no options)."""
    A = Article(SLUG, __file__, seed=SEED)
    S = {k: W.summers(k).set_index("year") for k, _ in ROWS}
    span = lambda s, a: s.loc[a[0]:a[1]]

    def contrast(a: str, b: str, col: str, before=BEFORE, after=AFTER) -> dict:
        """The change in station a's yearly lead over station b, with its range (a minus b, each year)."""
        diff = (S[a][col] - S[b][col]).dropna()
        d = add_f(md(span(diff, before), span(diff, after)), levels=False)
        d["lag1_autocorrelation"] = r(autocorrelation(span(diff, (before[0], after[1]))), 2)
        return d

    # ---- each station's change, 1991-2000 to the last ten summers
    change = {}
    for k, label in ROWS:
        s = S[k]
        node = {"label": label, "city": CITY_OF[k], "station": W.SITES[k][1]}
        for col, name in (("tx", "days"), ("tn", "nights")):
            d = add_f(md(span(s, BEFORE)[col], span(s, AFTER)[col]))
            assert d["n_before"] == d["n_after"] == 10, (k, col)
            d["lag1_autocorrelation"] = r(autocorrelation(span(s, (BEFORE[0], AFTER[1]))[col]), 2)
            node[name] = d
        change[k] = node
    A.results["change"] = change
    for k in change:
        for name in ("days", "nights"):
            if change[k][name]["direction"] in ("up", "down"):   # the unrounded range clears zero
                A.claim(f"change.{k}.{name}", change[k][name]["direction"])

    # the order of the cities' changes (New York at LaGuardia), largest first: the observed order, not a tested one
    ny_days = max(change[ny]["days"]["change"] for ny in NEW_YORK)
    order_days = sorted(OTHERS + ("laguardia",), key=lambda k: -change[k]["days"]["change"])
    order_nights = sorted(OTHERS + ("laguardia",), key=lambda k: -change[k]["nights"]["change"])
    A.results["order"] = {"days": order_days, "nights": order_nights,
                          "days_rank_of_new_york": order_days.index("laguardia") + 1,
                          "nights_rank_of_new_york": order_nights.index("laguardia") + 1,
                          "warmed_more_than_new_york_days": [k for k in OTHERS if change[k]["days"]["change"] > ny_days],
                          "warmed_less_than_new_york_days": [k for k in OTHERS if change[k]["days"]["change"] < min(change[ny]["days"]["change"] for ny in NEW_YORK)],
                          "no_warming_days": [k for k in OTHERS if not up(change[k]["days"])]}

    # ---- did the other cities warm more than New York? each year's difference between the two stations
    gap = {}
    for o in OTHERS + ("central_park",):
        gap[o] = {}
        for ny in NEW_YORK:
            for col, name in (("tx", "days"), ("tn", "nights")):
                gap[o][f"{ny}_{name}"] = contrast(o, ny, col)
    A.results["gap"] = gap
    for o in gap:
        for key, d in gap[o].items():
            if d["direction"] in ("up", "down"):
                A.claim(f"gap.{o}.{key}", d["direction"])
    A.results["afternoons_more_than_new_york"] = [o for o in OTHERS if all(up(gap[o][f"{ny}_days"]) for ny in NEW_YORK)]
    A.results["afternoons_less_than_new_york"] = [o for o in OTHERS if all(gap[o][f"{ny}_days"]["direction"] == "down" for ny in NEW_YORK)]
    A.results["nights_more_than_new_york"] = [o for o in OTHERS if all(up(gap[o][f"{ny}_nights"]) for ny in NEW_YORK)]
    A.results["times_new_york"] = {o: r(change[o]["days"]["change"] / ny_days, 1) for o in OTHERS if change[o]["days"]["change"] > 0}
    # Central Park against the airports: does the park's smaller change differ from theirs by more than the swing?
    A.results["central_park_less_than_airports_days"] = all(gap["central_park"][f"{ny}_days"]["direction"] == "down" for ny in NEW_YORK)

    # ---- the leaders against one another: the five largest afternoon changes, and Chicago's nights against the next three
    top5 = order_days[:5]
    pairs = {"days_top5": {}, "nights_chicago": {}}
    for a, b in combinations(top5, 2):
        pairs["days_top5"][f"{a}_vs_{b}"] = contrast(a, b, "tx")
    for b in [k for k in order_nights if k != "chicago"][:3]:
        pairs["nights_chicago"][f"chicago_vs_{b}"] = contrast("chicago", b, "tn")
    diff = (S["chicago"]["tn"] - S["chicago"]["tx"]).dropna()          # Chicago's nights against its own afternoons
    pairs["chicago_nights_minus_days"] = add_f(md(span(diff, BEFORE), span(diff, AFTER)), levels=False)
    pairs["days_top5_members"] = top5
    pairs["days_top5_separated"] = [k for k, d in pairs["days_top5"].items() if d["direction"] in ("up", "down")]
    pairs["days_top5_pairs"] = len(pairs["days_top5"])
    pairs["nights_chicago_clears"] = [k.split("_vs_")[1] for k, d in pairs["nights_chicago"].items() if up(d)]
    pairs["nights_chicago_compared"] = [k.split("_vs_")[1] for k in pairs["nights_chicago"]]
    A.results["pairs"] = pairs
    for group in ("days_top5", "nights_chicago"):
        for key, d in pairs[group].items():
            if d["direction"] in ("up", "down"):
                A.claim(f"pairs.{group}.{key}", d["direction"])
    if pairs["chicago_nights_minus_days"]["direction"] in ("up", "down"):
        A.claim("pairs.chicago_nights_minus_days", pairs["chicago_nights_minus_days"]["direction"])

    # ---- sensitivities: the windows moved a year; Toronto's older station on its newer one's basis
    shifted = []
    for before, after in SHIFTED:
        more = [o for o in OTHERS if all(up(contrast(o, ny, "tx", before, after)) for ny in NEW_YORK)]
        shifted.append({"before": f"{before[0]}-{before[1]}", "after": f"{after[0]}-{after[1]}",
                        "afternoons_more_than_new_york": more,
                        "vienna_berlin_paris_hold": all(k in more for k in ("vienna", "berlin", "montsouris"))})
    # serial dependence: the lag-one autocorrelation of the yearly series the leads rest on, 1991-2026
    lead_series = {f"{o}_minus_{ny}": gap[o][f"{ny}_days"]["lag1_autocorrelation"]
                   for o in ("vienna", "berlin", "montsouris") for ny in NEW_YORK}
    lead_series.update({f"central_park_minus_{ny}": gap["central_park"][f"{ny}_days"]["lag1_autocorrelation"] for ny in NEW_YORK})
    # serial dependence, allowed for: the same contrasts with the range widened for the residuals' lag-one
    # autocorrelation (sparkylib.stats.mean_difference_ar1), the station pairing kept
    def ar1_of(diff):
        d = add_f(mean_difference_ar1(span(diff, BEFORE), span(diff, AFTER)), levels=False)
        return {k: d[k] for k in ("change", "lo", "hi", "rho", "inflation", "direction", "change_f", "lo_f", "hi_f")}

    def ar1(a, b, col="tx"):
        return ar1_of((S[a][col] - S[b][col]).dropna())
    dep = {f"{o}_minus_{ny}": ar1(o, ny) for o in ("vienna", "berlin", "montsouris", "heathrow") for ny in NEW_YORK}
    dep.update({f"central_park_minus_{ny}": ar1("central_park", ny) for ny in NEW_YORK})
    dep["chicago_nights_minus_days"] = ar1_of((S["chicago"]["tn"] - S["chicago"]["tx"]).dropna())
    dep["leads_hold"] = all(up(dep[f"{o}_minus_{ny}"]) for o in ("vienna", "berlin", "montsouris") for ny in NEW_YORK)
    dep["central_park_holds"] = all(dep[f"central_park_minus_{ny}"]["direction"] == "down" for ny in NEW_YORK)
    dep["london_over_laguardia_holds"] = up(dep["heathrow_minus_laguardia"])
    dep["chicago_nights_hold"] = up(dep["chicago_nights_minus_days"])
    dep["rho_max"] = max(v["rho"] for k, v in dep.items() if isinstance(v, dict))
    dep["n"] = sum(isinstance(v, dict) for v in dep.values())
    # is the warming contrast smaller at night? each year's (Heathrow minus LaGuardia by day) minus (the same by night)
    day_night = ((S["heathrow"]["tx"] - S["laguardia"]["tx"]) - (S["heathrow"]["tn"] - S["laguardia"]["tn"])).dropna()
    A.results["day_night_contrast"] = {"heathrow_vs_laguardia": add_f(md(span(day_night, BEFORE), span(day_night, AFTER)), levels=False),
                                       "what": "the change in Heathrow's lead over LaGuardia by day minus the same by night, on each year's difference"}
    if A.results["day_night_contrast"]["heathrow_vs_laguardia"]["direction"] in ("up", "down"):
        A.claim("day_night_contrast.heathrow_vs_laguardia", A.results["day_night_contrast"]["heathrow_vs_laguardia"]["direction"])
    A.results["sensitivity"] = {"windows": shifted, "dependence": dep,
                               "autocorrelation": {"leads": lead_series, "leads_min": min(lead_series.values()),
                                                   "leads_max": max(lead_series.values()),
                                                   "stations_days": {k: change[k]["days"]["lag1_autocorrelation"] for k, _ in ROWS},
                                                   "stations_nights": {k: change[k]["nights"]["lag1_autocorrelation"] for k, _ in ROWS}}}
    off = W.toronto_offsets()
    tor = {}
    for col, name in (("tx", "days"), ("tn", "nights")):
        s = S["toronto_city"][col]
        old = s.loc[:W.TORONTO_JOIN.year - 1] + off[col]         # every summer before 2003 is the older station's
        tor[name] = add_f(md(span(old, BEFORE), span(s, AFTER)))
    A.results["sensitivity"]["toronto"] = {"offset_tx_c": r(off["tx"], 2), "offset_tn_c": r(off["tn"], 2),
                                           "offset_tn_f": r(f_change(off["tn"]), 1), "overlap_summer_days": off["days"],
                                           "join": W.TORONTO_JOIN.date().isoformat(), "days": tor["days"], "nights": tor["nights"]}

    # ---- the current summer
    now = {}
    for k, label in ROWS:
        s = S[k]
        recent = span(s, (BEFORE[0], NOW))
        row = {"tx": r(s.loc[NOW, "tx"], 2), "tn": r(s.loc[NOW, "tn"], 2),
               "tx_f": r(f_level(s.loc[NOW, "tx"]), 1), "tn_f": r(f_level(s.loc[NOW, "tn"]), 1),
               "rank_tx_since_1991": int((recent["tx"] > s.loc[NOW, "tx"]).sum() + 1),
               "rank_tn_since_1991": int((recent["tn"] > s.loc[NOW, "tn"]).sum() + 1),
               "summers_since_1991": int(len(recent)),
               "hottest_tx_since_1991": int(recent["tx"].idxmax()), "hottest_tx_f": r(f_level(recent["tx"].max()), 1)}
        if "hot_days" in s:
            row["hot_days"] = int(s.loc[NOW, "hot_days"])
            row["warm_nights"] = int(s.loc[NOW, "warm_nights"])
        now[k] = row
    A.results["y2026"] = now
    A.results["record_2026"] = sorted(k for k, _ in ROWS if now[k]["rank_tx_since_1991"] == 1)

    # ---- hot days and warm nights where the service publishes daily values (not Tokyo or Heathrow, read monthly):
    # counts of observed days, with the coverage they rest on
    counts = {}
    for k, _ in ROWS:
        if "hot_days" not in S[k]:
            continue
        recent = span(S[k], (BEFORE[0], NOW))
        counts[k] = {name: {"before": r(span(S[k], BEFORE)[name].mean(), 1), "after": r(span(S[k], AFTER)[name].mean(), 1)}
                     for name in ("hot_days", "warm_nights")}
        counts[k]["coverage"] = {"tx_days_min": int(recent["tx_days"].min()), "tn_days_min": int(recent["tn_days"].min()),
                                 "both_days_min": int(recent["both_days"].min()),
                                 "days_min": int(min(recent["tx_days"].min(), recent["tn_days"].min())),
                                 "summers_short_tx": int((recent["tx_days"] < SUMMER_DAYS).sum()),
                                 "summers_short_tn": int((recent["tn_days"] < SUMMER_DAYS).sum()),
                                 "complete": bool((recent[["tx_days", "tn_days"]] == SUMMER_DAYS).all().all())}
    A.results["counts"] = counts
    A.results["counts_complete_stations"] = sorted(k for k in counts if counts[k]["coverage"]["complete"])
    A.results["counts_absent"] = [k for k, _ in ROWS if k not in counts]
    A.results["thresholds"] = {"hot_day_c": W.HOT_DAY_C, "hot_day_f": r(f_level(W.HOT_DAY_C), 0),
                               "warm_night_c": W.WARM_NIGHT_C, "warm_night_f": r(f_level(W.WARM_NIGHT_C), 0),
                               "summer_days": SUMMER_DAYS}

    # ---- Tokyo's move: the change as observed and on one site's basis
    raw = W.summers("tokyo", adjusted=False).set_index("year")
    A.results["tokyo_move"] = {
        "date": W.MOVE.date().isoformat(),
        "days_as_observed": md(span(raw, BEFORE)["tx"], span(raw, AFTER)["tx"])["change"],
        "nights_as_observed": md(span(raw, BEFORE)["tn"], span(raw, AFTER)["tn"])["change"],
        "summer_correction_tn": r(sum(W.TOKYO_CORRECTION[m][0] for m in W.SUMMER) / 3, 2),
        "summer_correction_tx": r(sum(W.TOKYO_CORRECTION[m][1] for m in W.SUMMER) / 3, 2)}
    T = A.results["tokyo_move"]
    for k in ("days_as_observed", "nights_as_observed"):
        T[k + "_f"] = r(f_change(T[k]), 1)
    T["summer_correction_tn_f"] = r(f_change(-T["summer_correction_tn"]), 1)

    # ---- the long view: each summer's departure from the station's own 1961-1990 average
    long = {}
    for k, _ in ROWS:
        s = S[k].loc[LONG_FROM:NOW]
        if k in ("seoul", "singapore"):               # read from 1991 only (their services' pages and files, registered by year)
            continue
        assert set(range(LONG_FROM, NOW + 1)) <= set(s.index), (k, sorted(set(range(LONG_FROM, NOW + 1)) - set(s.index)))
        base = s.loc[BASE[0]:BASE[1]]
        long[k] = {"tx": (s["tx"] - base["tx"].mean()), "tn": (s["tn"] - base["tn"].mean())}
    A.results["long"] = {
        k: {"tx_last10_f": r(f_change(long[k]["tx"].loc[AFTER[0]:AFTER[1]].mean()), 1),
            "tn_last10_f": r(f_change(long[k]["tn"].loc[AFTER[0]:AFTER[1]].mean()), 1),
            "warmest_tx_year": int(long[k]["tx"].idxmax())} for k, _ in ROWS if k in long}
    A.results["long"]["first_year"] = LONG_FROM
    A.results["long"]["not_from_1960"] = ["seoul", "singapore"]

    # ---- levels: the hottest and coolest summers of the twelve cities, the last ten summers (New York at LaGuardia)
    levels = {k: {"tx_f": change[k]["days"]["after_f"], "tn_f": change[k]["nights"]["after_f"],
                  "tx": change[k]["days"]["after"], "tn": change[k]["nights"]["after"]} for k in OTHERS + ("laguardia",)}
    by_tx = sorted(levels, key=lambda k: -levels[k]["tx"])      # ordered on the unrounded Celsius means
    A.results["levels"] = {"last10": levels, "hottest_days_order": by_tx,
                           "hottest_days": by_tx[0], "warmest_nights": max(levels, key=lambda k: levels[k]["tn_f"]),
                           "laguardia_minus_heathrow_f": r(f_change(span(S["laguardia"], AFTER)["tx"].mean()
                                                                    - span(S["heathrow"], AFTER)["tx"].mean()), 1),
                           "hotter_than_laguardia": [k for k in by_tx if levels[k]["tx_f"] > levels["laguardia"]["tx_f"]],
                           "days_rank_of_new_york": by_tx.index("laguardia") + 1,
                           "nights_rank_of_new_york": sorted(levels, key=lambda k: -levels[k]["tn"]).index("laguardia") + 1}

    # ---- the documents
    Q = A.quotes()
    q_move = Q.quote(RELOCATION[0], RELOCATION[1], "「東京」の観測地点を千代田区大手町から北の丸公園へ移転し")
    q_counts = Q.quote(CORRECTION_DOC[0], CORRECTION_DOC[1], "猛暑日などの階級別日数等については確立しておりません")
    A.results["quotes"] = {"tokyo_move": {"quote": q_move["quote"], "source": q_move["source"]},
                           "tokyo_counts": {"quote": q_counts["quote"], "source": q_counts["source"]}}
    responses(A, Q)

    A.results["method"] = {
        "summer": "June, July and August; the mean of the three monthly means of the daily maximum and minimum",
        "usable_month": "a daily file's month counts with at least 80% of its days with both readings (JMA's rule); Tokyo's "
                        "months are JMA's monthly means as published, a month JMA marks ']' (too few days) left out; "
                        "Heathrow's are the Met Office's monthly means as published, a month marked '---' left out and a "
                        "month marked '*' (estimated by the Met Office) kept and counted (none in a summer since 1960); "
                        "every station has every summer 1991-2026",
        "change": "the mean of 2017-2026 minus the mean of 1991-2000, Welch's 90% range from the summers' own spread "
                  "(sparkylib.stats.mean_difference); summers treated as independent draws around each period's level; "
                  "each range is its own, not simultaneous across the comparisons",
        "gap": "each year's difference between the two stations, its 2017-2026 mean minus its 1991-2000 mean, with the same range",
        "decision": "a change or a lead is named only when its unrounded range clears zero (the node's direction); "
                    "estimates are kept to 0.0001 C through conversion and ranking",
        "dependence": "the ranges assume independent summers; sensitivity.autocorrelation gives the lag-one "
                      "autocorrelation of every yearly series they rest on, and sensitivity.dependence recomputes the "
                      "three leads and the Central Park contrasts with the range widened for the residuals' lag-one "
                      "autocorrelation (sparkylib.stats.mean_difference_ar1), the within-year pairing kept",
        "station_histories": "Tokyo's move and Toronto's join are the two station changes handled; no other station's "
                             "observing history was checked, and the ranges carry no allowance for an undocumented change",
        "counts": "hot days and warm nights are counts of observed days over the summer's 92, never scaled; "
                  "the coverage each station's counts rest on is in counts.<station>.coverage",
        "means_universe": "a daily file's monthly means use the days with both readings (both_days in data.csv); "
                          "the counts use each reading's own days",
        "quality": "a NOAA value with a quality flag, a Météo-France value with quality code 2, an HKO value not marked "
                   "complete and a JMA month marked ']' are left out; a JMA month marked ')' (a few days missing) is kept; "
                   "nothing is imputed",
        "heathrow": "the Met Office's own monthly means (Open Government Licence); the ECA&D daily series is the check only",
        "tokyo": "months before 2 December 2014 put on the Kitanomaru Park site's basis with JMA's monthly corrections, "
                 "taken as fixed offsets",
        "toronto": "two climate numbers joined at 1 July 2003 without adjustment; sensitivity.toronto puts the older on "
                   "the newer one's basis with the summer overlap offsets",
        "units": "computed in degrees Celsius; printed in Fahrenheit (a change times 1.8)",
        "responses": "each city's own published plan or warning rule, quoted; no response is set beside a temperature as a cause"}
    A.latest(f"{NOW}-08", "Each weather service's daily or monthly temperatures, the June to August 2026 summer complete")
    A.long_view(LONG_FROM, NOW, "Summer mean daily maximum and minimum at each city's station, 1960-2026, as departures "
                "from the station's 1961-1990 average; the comparison of decades from 1991")
    mo = W.met_office_heathrow()
    A.results["heathrow_estimated_summer_months_since_1960"] = int(mo[(mo["year"] >= LONG_FROM) & mo["month"].isin(W.SUMMER) & mo["estimated"]].shape[0])
    eca = W.summers_of_daily(W.heathrow_daily_series()).set_index("year")
    A.reproduce(f"Heathrow, mean daily high in summer {NOW}, degrees C (the daily series GHCN-Daily carries from ECA&D)",
                published=r(eca.loc[NOW, "tx"], 2), published_moe90=None, reproduced=r(S["heathrow"].loc[NOW, "tx"], 2),
                kind="rate", tolerance=0.25)
    A.reproduce("Heathrow, change in the summer mean daily high, 1991-2000 to 2017-2026, degrees C (the daily series "
                "GHCN-Daily carries from ECA&D)",
                published=r(span(eca, AFTER)["tx"].mean() - span(eca, BEFORE)["tx"].mean(), 2),
                published_moe90=None, reproduced=change["heathrow"]["days"]["change"], kind="rate", tolerance=0.05)
    A.results["reproduction_source"] = ("Heathrow's daily series as GHCN-Daily carries it from ECA&D, an independent copy "
                                        "of the Met Office's readings")
    A.results["reproduction_note"] = ("The daily series assigns some daily highs to a neighbouring month, so single "
                                      "months differ from the Met Office's monthly means by up to 0.7 C; whole summers "
                                      "agree within 0.25 C and the change between the decades within 0.05 C.")

    # ---- what the prose prints (every printed figure appears on the page: the FAQ's tables carry the full sets)
    for k, _ in ROWS:
        for name in ("days", "nights"):
            d = change[k][name]
            for f in ("change_f", "lo_f", "hi_f", "before_f", "after_f"):
                A.printed(f"change.{k}.{name}.{f}", f"{d[f]:.1f}°F")
        A.printed(f"y2026.{k}.tx_f", f"{now[k]['tx_f']:.1f}°F")
        A.printed(f"y2026.{k}.tn_f", f"{now[k]['tn_f']:.1f}°F")
        A.printed(f"y2026.{k}.rank_tx_since_1991", str(now[k]["rank_tx_since_1991"]))
    for k in ("vienna", "laguardia"):
        A.printed(f"change.{k}.days.change", f"{change[k]['days']['change']:.1f}°C")
        A.printed(f"long.{k}.tx_last10_f", f"{A.results['long'][k]['tx_last10_f']:.1f}°F")
    A.printed("long.montsouris.tx_last10_f", f"{A.results['long']['montsouris']['tx_last10_f']:.1f}°F")
    for k in counts:
        for name in ("hot_days", "warm_nights"):
            for when in ("before", "after"):
                # half up, not Python's half to even: a mean of ten whole counts can be an exact half (JFK's 28.5)
                A.printed(f"counts.{k}.{name}.{when}", f"{math.floor(counts[k][name][when] + 0.5):.0f}")
        if not counts[k]["coverage"]["complete"]:                 # the page names each station short of a day
            A.printed(f"counts.{k}.coverage.days_min", str(counts[k]["coverage"]["days_min"]))
    A.printed("thresholds.summer_days", str(SUMMER_DAYS))
    for o in gap:
        for key, d in gap[o].items():
            for f in ("change_f", "lo_f", "hi_f"):
                A.printed(f"gap.{o}.{key}.{f}", f"{d[f]:.1f}°F")
    for group in ("days_top5", "nights_chicago"):
        for key, d in pairs[group].items():
            for f in ("change_f", "lo_f", "hi_f"):
                A.printed(f"pairs.{group}.{key}.{f}", f"{d[f]:.1f}°F")
    A.printed("pairs.days_top5_pairs", str(pairs["days_top5_pairs"]))
    A.printed("pairs.days_top5_separated_n", str(len(pairs["days_top5_separated"])))
    A.results["pairs"]["days_top5_separated_n"] = len(pairs["days_top5_separated"])
    for name in ("days", "nights"):
        for f in ("change_f", "lo_f", "hi_f"):
            A.printed(f"sensitivity.toronto.{name}.{f}", f"{tor[name][f]:.1f}°F")
    A.printed("sensitivity.toronto.offset_tn_f", f"{A.results['sensitivity']['toronto']['offset_tn_f']:.1f}°F")
    for key in ("leads_min", "leads_max"):
        A.printed(f"sensitivity.autocorrelation.{key}", f"{A.results['sensitivity']['autocorrelation'][key]:.2f}")
    for key in ("central_park_minus_laguardia", "central_park_minus_jfk", "montsouris_minus_laguardia", "heathrow_minus_laguardia"):
        for f in ("lo_f", "hi_f"):
            A.printed(f"sensitivity.dependence.{key}.{f}", f"{dep[key][f]:.1f}°F")
    A.printed("sensitivity.dependence.rho_max", f"{dep['rho_max']:.2f}")
    A.printed("sensitivity.dependence.n", str(dep["n"]))
    for f in ("change_f", "lo_f", "hi_f"):
        A.printed(f"day_night_contrast.heathrow_vs_laguardia.{f}", f"{A.results['day_night_contrast']['heathrow_vs_laguardia'][f]:.1f}°F")
    for f in ("change_f", "lo_f", "hi_f"):
        A.printed(f"pairs.chicago_nights_minus_days.{f}", f"{pairs['chicago_nights_minus_days'][f]:.1f}°F")
    A.printed("tokyo_move.nights_as_observed_f", f"{T['nights_as_observed_f']:.1f}°F")
    A.printed("tokyo_move.summer_correction_tn_f", f"{T['summer_correction_tn_f']:.1f}°F")
    A.printed("thresholds.hot_day_f", f"{A.results['thresholds']['hot_day_f']:.0f}°F")
    A.printed("thresholds.warm_night_f", f"{A.results['thresholds']['warm_night_f']:.0f}°F")
    A.printed("levels.laguardia_minus_heathrow_f", f"{A.results['levels']['laguardia_minus_heathrow_f']:.1f}°F")
    for key in ("days_rank_of_new_york", "nights_rank_of_new_york"):
        A.printed(f"order.{key}", str(A.results["order"][key]))
        A.printed(f"levels.{key}", str(A.results["levels"][key]))
    kinds = {c: {d[3].split(":")[0] for d in docs} for c, docs in RESPONSES.items()}
    A.results["cities_with_warning_quote"] = sorted(c for c, k in kinds.items() if k & {"warning", "alert", "advisory"})
    A.results["cities_without_warning_quote"] = sorted(c for c, k in kinds.items() if not k & {"warning", "alert", "advisory"})
    A.results["cities_with_cool_place_quote"] = sorted(c for c, docs in RESPONSES.items()
                                                     if any(k in " ".join(d[3] for d in docs) for k in ("cool", "shelter")))
    for key in ("cities_with_warning_quote", "cities_with_cool_place_quote"):
        A.results[key + "_n"] = len(A.results[key])
        A.printed(key + "_n", str(len(A.results[key])))
    A.results["y2025_tokyo_tx_f"] = r(f_level(S["tokyo"].loc[2025, "tx"]), 1)
    # the documents' own counts the page repeats in words beside their quotes, read from the quotes
    figures = {"paris_cool_places": ("paris", "Près de 1 400 lieux frais", r"1 400", 1400),
               "seoul_shelters": ("seoul", "무더위쉼터 총 4,078개소", r"4,078", 4078)}
    A.results["responses_figures"] = {}
    for key, (city, needle, token, value) in figures.items():
        assert any(needle in d["quote"] for d in A.results["responses"][city]), (key, needle)
        A.results["responses_figures"][key] = value
        A.printed(f"responses_figures.{key}", f"{value:,}")

    # ---- charts
    def decades(col: str) -> dict:
        return {"": {k: {"1991-2000": r(f_level(change[k][col]["before"]), 1),
                         "2017-2026": r(f_level(change[k][col]["after"]), 1)} for k, _ in ROWS}}

    A.chart("afternoons", strip(
        title="The largest observed afternoon warming is at Vienna's, Berlin's and Paris's stations; at LAX and Changi the change could be nothing",
        subtitle="Mean daily high in June to August, 1991-2000 against the last ten summers, degrees Fahrenheit",
        x=[["1991-2000", "1991 to 2000"], ["2017-2026", "2017 to 2026"]],
        series=[[k, label, label] for k, label in ROWS], cells=decades("days"), format="dec1",
        axis="Mean daily high, °F", zero=False,
        note="Each city at its weather service's station: New York at LaGuardia, JFK and Central Park (NOAA); London at "
             "Heathrow (the Met Office's monthly means); Paris at Montsouris (Météo-France); Berlin at Tempelhof (DWD); "
             "Vienna at Hohe Warte (GeoSphere Austria); Toronto downtown (Environment Canada); Chicago at O'Hare and Los Angeles at LAX "
             "(NOAA); Tokyo at JMA's station, its summers before its 2014 move adjusted with JMA's own corrections; Seoul "
             "(KMA); Hong Kong (the Observatory); Singapore at Changi (MSS), where June to August is not a summer. Each "
             "change carries a 90% range (the FAQ lists them); the order is the observed one.",
        provenance="NOAA GHCN-Daily; Met Office; Météo-France; DWD (its own open data); GeoSphere Austria; ECCC; JMA; KMA; HKO; MSS"))

    A.chart("nights", strip(
        title="The largest observed night warming is at Chicago's station, then Vienna's and Tokyo's; the three are not separated",
        subtitle="Mean daily low in June to August, 1991-2000 against the last ten summers, degrees Fahrenheit",
        x=[["1991-2000", "1991 to 2000"], ["2017-2026", "2017 to 2026"]],
        series=[[k, label, label] for k, label in ROWS], cells=decades("nights"), format="dec1",
        axis="Mean daily low, °F", zero=False,
        note="The same stations as the afternoon chart. Tokyo's 2014 move lowered its summer nights by more than a "
             "degree; its earlier summers are put on the new site's basis. Toronto's two station numbers are joined "
             "without adjustment. Each change carries a 90% range (the FAQ lists them); the order is the observed one.",
        provenance="NOAA GHCN-Daily; Met Office; Météo-France; DWD (its own open data); GeoSphere Austria; ECCC; JMA; KMA; HKO; MSS"))

    years = list(range(LONG_FROM, NOW + 1))
    A.chart("long_view", lines(
        title="Since about 1990, summer afternoons in Vienna, Paris, London and Tokyo have pulled away from their old averages",
        subtitle="Each summer's mean daily high against the station's own 1961-1990 average, degrees Fahrenheit (Heathrow's 2026 provisional)",
        x=[[str(t), str(t)] for t in years],
        series=[list(x) for x in LONG_LINES],
        cells={"": {k: {str(t): r(f_change(long[k]["tx"][t]), 2) for t in years} for k, _, _ in LONG_LINES}},
        format="dec1", axis="Above or below the 1961-1990 average, °F",
        x_ticks=[str(t) for t in years if t % 10 == 0 or t == NOW],
        note="Zero is each station's own 1961-1990 summer average, so the lines show change, not which city is hotter. "
             "Six of the twelve cities are drawn, for legibility: New York (at LaGuardia), London, Paris and Vienna, Tokyo "
             "and Hong Kong; Berlin, Toronto, Chicago and Los Angeles are in the data file, and Seoul and Singapore have "
             "no 1960 record here.",
        provenance="NOAA GHCN-Daily; Met Office; Météo-France; GeoSphere Austria; JMA; Hong Kong Observatory"))

    ny_years = list(range(BEFORE[0], NOW + 1))
    A.chart("new_york_stations", lines(
        title="Central Park's afternoons have warmed less than New York's airports'",
        subtitle="Mean daily high in June to August at New York's three long-running stations, degrees Fahrenheit",
        x=[[str(t), str(t)] for t in ny_years],
        series=[["central_park", "Central Park", "Central Park"], ["laguardia", "LaGuardia Airport", "LaGuardia"],
                ["jfk", "JFK Airport", "JFK"]],
        cells={"": {k: {str(t): r(f_level(S[k].loc[t, "tx"]), 1) for t in ny_years} for k in ("central_park", "laguardia", "jfk")}},
        format="dec1", axis="Mean daily high, °F", zero=False,
        x_ticks=[str(t) for t in ny_years if t % 5 == 0 or t in (BEFORE[0], NOW)],
        note="Central Park is the city's official record. The park's change is tested against each airport's on the "
             "yearly differences (the FAQ has the ranges). The records do not say why its afternoons have warmed less.",
        provenance="NOAA GHCN-Daily"))

    rows_out = []
    for k, label in ROWS:
        for t, row in S[k].iterrows():
            out = {"station": label, "city": CITY_OF[k], "summer": int(t), "mean_daily_high_c": r(row["tx"], 2),
                   "mean_daily_low_c": r(row["tn"], 2), "mean_daily_high_f": r(f_level(row["tx"]), 2),
                   "mean_daily_low_f": r(f_level(row["tn"]), 2)}
            if "hot_days" in row:
                out["days_30c_or_more"] = int(row["hot_days"]) if pd.notna(row["hot_days"]) else None
                out["nights_20c_or_more"] = int(row["warm_nights"]) if pd.notna(row["warm_nights"]) else None
                out["days_with_a_maximum"] = int(row["tx_days"]) if pd.notna(row["tx_days"]) else None
                out["days_with_a_minimum"] = int(row["tn_days"]) if pd.notna(row["tn_days"]) else None
                out["days_with_both"] = int(row["both_days"]) if pd.notna(row["both_days"]) else None
            rows_out.append(out)
    A.write(data=pd.DataFrame(rows_out))
    print(f"{SLUG}: wrote {A.out}")
    return 0


#: How each city answers the heat, from its own documents: city -> [(source id, saved file, needle, what it establishes)].
#: Every sentence the page prints about a response rests on one of these quotes (found in the saved copy at the build).
#: The word before the colon in "what" is its kind: warning, alert or advisory (a rule that triggers), plan, or a place.
RESPONSES = {
    "new_york": [("nws_okx_extreme_heat_criteria", "nws_okx_extreme_heat_criteria.html",
                  "Issued when the heat index is forecast to reach 95 to 99F for at least 2 consecutive days or 100 to 104 F for any length of time",
                  "warning: the National Weather Service's heat advisory for the city, on the heat index"),
                 ("nycem_extreme_heat_plan_page", "nycem_extreme_heat_plan_page.html",
                  "During heat emergencies, the City will open cooling centers throughout the five boroughs", "cooling centers")],
    "london": [("ukhsa_adverse_weather_health_plan_2026", "ukhsa_adverse_weather_health_plan_2026_2027.pdf",
                "first released in April 2023, brought together and built on the Heatwave Plan for England, first published in 2004",
                "alert: England's heat-health alerts, under a plan since 2004"),
               ("ukhsa_adverse_weather_health_plan_2026", "ukhsa_adverse_weather_health_plan_2026_2027.pdf",
                "impact-based alerting system", "alerts on expected impact, not a fixed degree"),
               ("gla_cool_spaces_press_2022", "gla_cool_spaces_press_2022_06_17.html",
                "the Mayor has established a network of free to access", "cool spaces")],
    "paris": [("meteofrance_vigilance_canicule_explainer", "meteofrance_vigilance_canicule_explainer.html",
               "une période de chaleur intense pendant au moins 3 jours et 3 nuits consécutifs", "warning: orange vigilance, three days and nights"),
              ("paris_plan_canicule_page", "paris_plan_canicule_page.html",
               "Le niveau 3 « alerte canicule » est déclenché automatiquement par le préfet d'Île-de-France, dès le passage en vigilance météorologique orange",
               "plan: level 3 follows the orange vigilance automatically"),
              ("paris_plan_canicule_page", "paris_plan_canicule_page.html",
               "Près de 1 400 lieux frais permettent de se rafraîchir pendant la journée ou la nuit à Paris", "cool places")],
    "berlin": [("dwd_hitzewarnung_system", "dwd_hitzewarnung_system.html", "Dieser Schwellenwert liegt bei etwa 32°C",
                "warning: felt temperature about 32 C"),
               ("berlin_hitzeaktionsplan_press_2025", "berlin_hitzeaktionsplan_press_2025_11_25.html",
                "Zentraler Bestandteil des Hitzeaktionsplans sind 72 Maßnahmen", "plan: 72 measures")],
    "vienna": [("wien_hitzewarndienst_landessanitaetsdirektion", "wien_hitzewarndienst_landessanitaetsdirektion.html",
                "die durchschnittliche gefühlte Tagesmaximaltemperatur an mindestens drei aufeinanderfolgenden Tagen über 35 Grad Celsius",
                "warning: an average felt daily maximum above 35 C over at least three consecutive days"),
               ("wien_hitzewarndienst_landessanitaetsdirektion", "wien_hitzewarndienst_landessanitaetsdirektion.html",
                "kühlt es während der Nacht nicht unter 20 Grad Celsius ab", "and nights not below 20 C"),
               ("wien_hitzeaktionsplan_massnahmen", "wien_hitzeaktionsplan_massnahmen.html",
                "Coole Zonen: Schaffung von kühlen, konsumfreien Innenräumen für die öffentliche Nutzung",
                "cool place: the Coole Zonen, cool indoor rooms open to the public"),
               ("wien_hitzeaktionsplan_massnahmen", "wien_hitzeaktionsplan_massnahmen.html",
                "bei Hitzewarnung während oder präventiv vor einer prognostizierten Hitzewelle gesetzt",
                "plan: the acute measures start at a heat warning or before a forecast heat wave")],
    "toronto": [("toronto_heat_relief_strategy_page", "toronto_heat_relief_strategy_page.html",
                 "daytime maximum temperatures of 31°C or warmer, together with nighttime minimum temperatures of 20°C or warmer",
                 "warning: 31 C by day and 20 C by night, two days"),
                ("toronto_heat_relief_strategy_page", "toronto_heat_relief_strategy_page.html",
                 "humidex values expected to reach 40 or higher", "or a humidex of 40, two days"),
                ("toronto_heat_relief_page", "toronto_heat_relief_page.html",
                 "Find one of 500+ Cooling Spaces Near You", "cool place: more than 500 cooling spaces on the City's map")],
    "chicago": [("noaa_july_1995_heat_wave_assessment", "noaa_july_1995_heat_wave_assessment.pdf",
                 "465 heat-related deaths recorded during the period from July 11-27, 1995", "the 1995 heat wave")],
    "los_angeles": [("la_emd_heat_cooling_centers_page", "la_emd_heat_cooling_centers_page.html",
                     "LA City opens dedicated cooling centers", "cooling centers"),
                    ("la_emd_heat_cooling_centers_page", "la_emd_heat_cooling_centers_page.html", "Cool Spots LA", "cool spots"),
                    ("la_emd_heat_cooling_centers_page", "la_emd_heat_cooling_centers_page.html", "parks and library branches", "at parks and libraries")],
    "tokyo": [("moe_japan_heatstroke_alert", "moe_japan_heatstroke_alert_about.html",
               "日最高暑さ指数（WBGT）が33（予測値）に達する場合に発表", "warning: WBGT 33"),
              ("moe_japan_special_heatstroke_alert", "moe_japan_special_heatstroke_alert_about.html",
               "翌日の日最高暑さ指数（WBGT）が35（予測値）に達する場合等に発表", "a special alert at WBGT 35, forecast for the following day"),
              ("moe_japan_special_heatstroke_alert", "moe_japan_special_heatstroke_alert_about.html",
               "全ての暑さ指数情報提供地点", "at all of the prefecture's reporting points"),
              ("moe_japan_special_heatstroke_alert", "moe_japan_special_heatstroke_alert_about.html",
               "市町村が事前に指定を行っているクーリングシェルター（指定暑熱避難施設）", "cooling shelters designated by municipalities, opened on the alert")],
    "seoul": [("kma_heat_warning_reform_press_2026", "kma_heat_warning_reform_press_2026_05_12.html",
               "일최고체감온도가 33 ℃ 또는 35 ℃ 이상이 이틀 이상 지속될 것으로 예상될 때", "warning: felt temperature 33 and 35 C, two days"),
              ("kma_heat_warning_reform_press_2026", "kma_heat_warning_reform_press_2026_05_12.html", "'08년 도입된 폭염특보", "warnings since 2008"),
              ("seoul_heat_plan_mediahub_2026", "seoul_heat_plan_mediahub_2026_05_28.html", "무더위쉼터 총 4,078개소", "4,078 cooling shelters"),
              ("seoul_heat_plan_mediahub_2026", "seoul_heat_plan_mediahub_2026_05_28.html", "204곳에 확대 시공", "cool roofs at 204 sites")],
    "hong_kong": [("hko_extremely_hot_weather_alerts", "hko_extremely_hot_weather_alerts.html",
                   "the Observatory issues the Very Hot Weather Warning (VHWW)",
                   "warning: the Very Hot Weather Warning, issued for very hot weather with no degree in the sentence"),
                  ("hko_extremely_hot_weather_alerts", "hko_extremely_hot_weather_alerts.html", "35 degrees or above",
                   "special alert: the extremely hot weather special alert when the temperature generally reaches 35 C"),
                  ("hk_had_emergency_services_shelters", "hk_had_emergency_services_shelters.html",
                   "temporary heat shelters during oppressively hot weather", "cool place: temporary heat shelters in oppressively hot weather"),
                  ("hk_labour_heat_stress_at_work_warning", "hk_labour_heat_stress_at_work_warning.pdf",
                   "Heat Stress at Work Warning (HSWW) based on the Hong Kong Heat Index", "work: a heat-stress warning for workplaces"),
                  ("hk_labour_heat_stress_at_work_warning", "hk_labour_heat_stress_at_work_warning.pdf",
                   "working outdoors or in indoor environments without air", "for work outdoors or indoors without air conditioning"),
                  ("hk_labour_heat_stress_at_work_warning", "hk_labour_heat_stress_at_work_warning.pdf",
                   "measured temperatures over many places in Hong Kong and the issuance of",
                   "issued on the index, measured temperatures across Hong Kong and the Observatory's alert")],
    "singapore": [("mse_nea_heat_stress_advisory_launch_2023", "mse_nea_heat_stress_advisory_launch_2023_07_24.html",
                   "have launched a Heat Stress Advisory for the public", "advisory: a heat-stress advisory, 2023"),
                  ("mse_nea_heat_stress_advisory_launch_2023", "mse_nea_heat_stress_advisory_launch_2023_07_24.html",
                   "is based on the Wet Bulb Globe Temperature (WBGT)", "on the wet-bulb globe temperature")],
}
FRAMING = ("wmo_who_heatwaves_and_health_2015", "wmo_who_heatwaves_and_health_2015.pdf",
           "the structure of HHWSs varies significantly among cities, regions and countries")


def responses(A: Article, Q) -> None:
    """How each city responds to heat, from its own published documents: results['responses'] holds, per city, the
    quotes the page's sentences rest on (each found in the saved copy, or the build stops)."""
    out = {}
    for city, docs in RESPONSES.items():
        out[city] = []
        for src, fname, needle, what in docs:
            q = Q.quote(src, fname, needle)
            out[city].append({"what": what, "source": src, "page": q.get("page"), "quote": q["quote"]})
    q = Q.quote(*FRAMING)
    out["framing"] = [{"what": "WMO and WHO on heat-health warning systems", "source": FRAMING[0], "page": q.get("page"), "quote": q["quote"]}]
    A.results["responses"] = out


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