"""New York's fire deaths against ten other big cities', 2000 to 2026: the analysis behind a SparkyData article.

    py src/build_article.py fire-deaths-in-big-cities

Every count is a fire service's (Chicago's, its medical examiner's) count of civilians who died in fires, read by
``nycdata.world_fire`` (card ``world_city_fire_deaths``): New York's from the Fire Department's Bureau of Fire
Investigation, 2000-2025, and its releases for 2026; London's from the Home Office (financial years); Tokyo's and
Yokohama's from their fire services' yearly reports; Seoul's, Busan's and Incheon's from Korea's National Fire
Agency; Hong Kong's, Singapore's and Toronto's from their fire services; Chicago's from the Cook County Medical
Examiner. Definitions differ, so each city is compared with itself: its five years to 2025 (``LAST``) against the
five to 2016 (``MID``, the five years to New York's fewest) and its first five years from 2002 (``FIRST``). The
counts are small, so every change carries a range from the Poisson model widened by the swing each city's own yearly
series shows (``stats.dispersion``), and a change is named only when its range clears zero.

The current year is New York's count to 8 November 2026 as the Department gave it to the Daily News (86, against 44
at the same point of 2025), with its own release of 5 October (71) beside it. Each city with a count for 2026 is
carried to the end of the year at its pace so far, as a projection, never as a count; New York's is also carried on
the shape of 2025 (44 of 63 by 8 November), as the higher reading.

What the cities say and do about fire deaths, batteries above all, comes from their own documents, quoted, never as
a cause. Writes results.json, viz.json, charts.json, data.csv and build.json into
output/articles/fire_deaths_in_big_cities/ and site/public/articles/fire-deaths-in-big-cities/, and copies this script
there as analysis.py. Deterministic: no sampling.
"""

from __future__ import annotations

from datetime import date

import pandas as pd

from article_kit import Article, lines, r, strip
from nycdata import world_fire as F
from sparkylib.stats import change_contrast, count_change, dispersion

SLUG = "fire-deaths-in-big-cities"
SEED = 20261127
FIRST = (2002, 2006)    # the first five years every long series can give (Tokyo's reports start in 2002)
MID = (2012, 2016)      # the five years to 2016, New York's fewest
LAST = (2021, 2025)     # the five latest years
LATE_BREAK = {"hong_kong": (2020, 2024), "yokohama": (2020, 2024)}   # Hong Kong's 2025 is the Wang Fuk Court fire; Yokohama's 2025 is not out
FIRST_OWN = {"seoul": (2007, 2011), "busan": (2007, 2011), "incheon": (2007, 2011), "hong_kong": (2006, 2010),
             "yokohama": (2004, 2008)}        # cities whose series starts after 2002: their first five years
#: London's financial year ending in March of year y+1 is mostly calendar year y: its windows are the calendar ones
#: moved on a year (2021-2025 is 2021/22 to 2025/26).
FY_SHIFT = {"london": 1}
#: Years left out of a city's yearly swing (stats.dispersion), as they are of its windows: Hong Kong's 2025, one fire.
OUT_OF_SWING = {"hong_kong": [2025], "london": [2018]}     # one fire each: Wang Fuk Court; Grenfell Tower (2017/18)
BASES = range(2009, 2013)       # the five-year bases of the low years, 2009-2013 to 2012-2016: the rise's dependence on its base
TWIN_PARKS = 17                 # the Twin Parks fire in the Bronx, January 2022, as the Comptroller's report gives its toll
CHICAGO_BASE = (2015, 2019)   # Chicago's archive starts in 2015: its first five years stand in for MID
TODAY = date(2026, 11, 19)
NY_TO = date(2026, 11, 8)     # the Daily News's count of 86, "this year to date"
#: Reports quoted for their yearly totals, whose terms do not license reuse: their rows stay out of the data file.
QUOTED_ONLY = ("scdf_fire_statistics", "yokohama_fire_nenpo", "toronto_fire_services", "hkfsd_review")
CITIES = list(F.CITIES)
LABEL = {k: v[0] for k, v in F.CITIES.items()}
OTHERS = [k for k in CITIES if k != "new_york"]
RATE_CITIES = ["new_york", "chicago", "tokyo", "toronto", "london", "hong_kong", "singapore"]
WORLD_LINES = ["new_york", "london", "tokyo", "hong_kong", "singapore"]


def five_years(series: pd.Series, span: tuple[int, int]) -> dict:
    """The years of a window the series has, their sum and the yearly mean."""
    s = series.loc[span[0]:span[1]]
    return {"from": span[0], "to": span[1], "years": [int(y) for y in s.index], "n_years": int(len(s)),
            "deaths": int(s.sum()), "per_year": r(float(s.mean()), 2)}


def window_change(now: dict, before: dict, phi: float) -> dict:
    c = count_change(now["deaths"], before["deaths"], exposure_now=now["n_years"], exposure_before=before["n_years"],
                     dispersion=phi, nd=4)
    c["dispersion"] = r(phi, 2)
    # the change again, unrounded, for print: the yearly rates compared (a window can hold four years, not five)
    c["change_pct_exact"] = r(100 * ((now["deaths"] / now["n_years"]) / (before["deaths"] / before["n_years"]) - 1), 4)
    return c


def yearly_chain(series: pd.Series, out=()) -> list[float]:
    """A city's yearly counts on every year from its first to its last, with NaN where a year is missing (London's
    2009/10, Singapore's 2023) or left out as one fire's year (``OUT_OF_SWING``). stats.dispersion pairs neighbours
    and skips a pair with a NaN in it, so the swing is taken only between years that really follow one another."""
    full = series.reindex(range(int(series.index.min()), int(series.index.max()) + 1)).astype(float)
    full.loc[[y for y in out if y in full.index]] = float("nan")
    return full.tolist()


def fy(year: int) -> str:
    """London's financial year by the year it ends: 2026 -> '2025/26'."""
    return f"{year - 1}/{year % 100:02d}"


def main(argv: list[str] | None = None) -> int:
    """Run the analysis and write every file (no options)."""
    A = Article(SLUG, __file__, seed=SEED)
    Q = A.quotes()

    # ---- New York: 2000-2025 on the Bureau of Fire Investigation's counts
    ny = F.deaths("new_york").set_index("year")["deaths"]
    phi_ny = max(1.0, dispersion(yearly_chain(ny)))
    w = {k: five_years(ny, span) for k, span in (("first", FIRST), ("mid", MID), ("last", LAST))}
    low = int(ny.idxmin())
    recent_peak = int(ny.loc[2017:].idxmax())
    A.results["new_york"] = {
        "deaths": {str(y): int(v) for y, v in ny.items()},
        "first": {"year": int(ny.index.min()), "deaths": int(ny.iloc[0])},
        "low": {"year": low, "deaths": int(ny[low])},
        "recent_peak": {"year": recent_peak, "deaths": int(ny[recent_peak])},
        "latest": {"year": int(ny.index.max()), "deaths": int(ny.iloc[-1])},
        "windows": w, "dispersion": r(phi_ny, 2),
        "first_to_mid": window_change(w["mid"], w["first"], phi_ny),
        "mid_to_last": window_change(w["last"], w["mid"], phi_ny),
        "first_to_last": window_change(w["last"], w["first"], phi_ny),
        "since_2000_pct": r(100 * (ny.iloc[-1] / ny.iloc[0] - 1), 2),
    }
    assert low == 2016 and recent_peak == 2023, "the page says 2016 was the fewest and 2023 the most since"
    assert all(v > ny[2016] for y, v in ny.items() if y > 2016), "the page says every year since 2016 has been higher"
    # MID ends at New York's fewest, the base that gives the largest rise: the same rise from every other five-year base
    bases = {}
    for y0 in BASES:
        b = five_years(ny, (y0, y0 + 4))
        ch = window_change(w["last"], b, phi_ny)
        bases[f"{y0}-{y0 + 4}"] = {"deaths": b["deaths"], "change_pct": ch["change_pct_exact"], "lo_pct": ch["lo_pct"],
                                   "hi_pct": ch["hi_pct"], "direction": ch["direction"]}
    others = [v["change_pct"] for k_, v in bases.items() if k_ != f"{MID[0]}-{MID[1]}"]
    A.results["new_york"]["rise_by_base"] = {"bases": bases, "lowest_pct": r(min(others), 2), "highest_other_pct": r(max(others), 2),
                                             "from_mid_pct": bases[f"{MID[0]}-{MID[1]}"]["change_pct"]}
    assert all(v["direction"] == "up" for v in bases.values()), "the page says the rise clears zero from every base"
    assert max(bases, key=lambda k_: bases[k_]["change_pct"]) == f"{MID[0]}-{MID[1]}", "the page says the low base gives the largest rise"
    # one fire inside the latest window: Twin Parks, January 2022
    Q.quote("nyc_comptroller_turn_up_the_heat_2025", "nyc_comptroller_turn_up_the_heat_2025.html", "ultimately killing 17 New Yorkers")
    without_tp = dict(w["last"], deaths=w["last"]["deaths"] - TWIN_PARKS)
    A.results["new_york"]["twin_parks"] = {"deaths": TWIN_PARKS, "last_without": without_tp["deaths"],
                                           "mid_to_last_without": window_change(without_tp, w["mid"], phi_ny)}
    assert A.results["new_york"]["twin_parks"]["mid_to_last_without"]["direction"] == "up", "the page says the rise holds without Twin Parks"
    assert int(ny[2025]) == int(ny.loc[2021:2025].min()), "the page says 2025 was the quietest of the last five years"
    ny_rate = F.fire_rate("new_york").set_index("year")
    A.results["new_york"]["per_million"] = {k_: r(float(ny_rate.loc[v["years"], "deaths"].sum() / ny_rate.loc[v["years"], "pop"].sum() * 1e6), 4)
                                            for k_, v in w.items()}
    assert int(ny[2025]) == int(ny[2020]), "the page says 2025 matched 2020"
    A.claim("new_york.first_to_mid", "down")
    A.claim("new_york.mid_to_last", "up")
    A.recheck("new_york.mid_to_last", yearly_chain(ny))
    A.recheck("new_york.first_to_mid", yearly_chain(ny))

    # ---- this year: the Department's count to 8 November against the same point of 2025, carried to the year's end
    ytd = F.deaths_so_far("new_york")
    oct5, nov8 = ytd[0], ytd[-1]
    same_2025 = 44
    Q.quote(nov8["source_id"], "nydn_firehouse_fire_deaths_2026_11.html", "a steep jump from 44 deaths in the same time period last year")
    days = (NY_TO - date(2026, 1, 1)).days + 1
    pace = nov8["deaths"] * 365 / days
    shape = nov8["deaths"] * int(ny[2025]) / same_2025
    A.results["now"] = {
        "to_oct5": oct5["deaths"], "to_nov8": nov8["deaths"], "same_point_2025": same_2025,
        "vs_2025": count_change(nov8["deaths"], same_2025, dispersion=phi_ny, nd=4) | {
            "dispersion": r(phi_ny, 2), "change_pct_exact": r(100 * (nov8["deaths"] / same_2025 - 1), 4)},
        "projection": {"pace": int(round(pace)), "shape_of_2025": int(round(shape)), "days": days,
                       "method": "the count to 8 November carried at its daily pace to 31 December (the lower reading), "
                                 "and on the share of 2025's deaths that came by 8 November (44 of 63, the higher)"},
    }
    A.claim("now.vs_2025", "up")
    proj = A.results["now"]["projection"]
    above = [int(y) for y, v in ny.items() if v >= proj["pace"]]
    A.results["now"]["projection"]["years_at_or_above_pace"] = above
    assert above == [2000, 2001, 2003, 2005, 2023], f"the page names the years at or above the projection: {above}"
    assert all(v < proj["shape_of_2025"] for y, v in ny.items() if y > 2003) and ny[2003] > proj["shape_of_2025"], \
        "the page says the higher reading would be the deadliest year since 2003"
    A.latest("2026-11-08", "New York's fire deaths in 2026 to 8 November, the Fire Department's count as the Daily News "
             "reported it (86, against 44 at the same point of 2025); the Department's own release of 5 October gave 71")
    A.long_view(2000, int(ny.index.max()), "Civilian fire deaths in New York City, the Bureau of Fire Investigation's "
                "count, 2000-2025",
                why_shorter="The Bureau's annual reports posted by the Department start with 2008's, whose tables reach back "
                            "to 2000; no primary count for the years before 2000 is posted in a form we can read and check")

    # ---- batteries
    bat = F.battery_nyc().set_index("year")["deaths"]
    A.results["battery"] = {
        "deaths": {str(y): int(v) for y, v in bat.items()},
        "peak": {"year": int(bat.loc[:2025].idxmax()), "deaths": int(bat.loc[:2025].max())},
        "share_2023_pct": r(100 * bat[2023] / ny[2023], 2),
        "share_2026_pct": r(100 * bat[2026] / nov8["deaths"], 2),
        "other_2026_to_date": int(nov8["deaths"] - bat[2026]),
        "fires_2026": 401, "fires_2025": 292,
    }
    assert int(bat.loc[:2025].idxmax()) == 2023
    # batteries inside the five-year rise: the Bureau's battery deaths of 2021-2025 taken out of the latest window
    bat5 = int(bat.loc[LAST[0]:LAST[1]].sum())
    without_bat = dict(w["last"], deaths=w["last"]["deaths"] - bat5)
    extra = w["last"]["deaths"] - w["mid"]["deaths"]
    A.results["battery"]["five_years"] = {
        "deaths": bat5, "share_of_window_pct": r(100 * bat5 / w["last"]["deaths"], 2), "extra_deaths": int(extra),
        "share_of_extra_pct": r(100 * bat5 / extra, 2), "last_without": without_bat["deaths"],
        "mid_to_last_without": window_change(without_bat, w["mid"], phi_ny),
        "note": "the Bureau's cause table starts in 2019, so no battery death is on file for 2012-2016: the comparison "
                "assumes there was none, which makes the share an upper reading"}
    assert A.results["battery"]["five_years"]["mid_to_last_without"]["direction"] == "up", "the page says the rise holds without battery deaths"
    # this year: the Department's ten after the Bronx fire, and the Sunset Park fire (six dead, cause open) either way
    Q.quote("nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html", "killing six on Thursday")
    A.results["battery"]["sunset_park_deaths"] = 6
    A.results["battery"]["at_most_2026"] = int(bat[2026]) + 6
    A.results["battery"]["other_at_least_2026"] = int(nov8["deaths"] - bat[2026] - 6)
    assert A.results["battery"]["other_at_least_2026"] > same_2025, "the page says the other fires alone outnumber all of last year's deaths to the same date"

    # ---- the other cities: each against itself
    cities = {}
    for k in CITIES:
        s = F.deaths(k).set_index("year")["deaths"]
        phi = max(1.0, dispersion(yearly_chain(s, OUT_OF_SWING.get(k, []))))
        sh = FY_SHIFT.get(k, 0)
        def span(a: tuple[int, int]) -> tuple[int, int]:
            return (a[0] + sh, a[1] + sh)
        last = five_years(s, span(LATE_BREAK.get(k, LAST)))
        node = {"label": LABEL[k], "area": F.CITIES[k][1], "counted_by": F.CITIES[k][2], "counts": F.CITIES[k][3],
                "first_year": int(s.index.min()), "last_year": int(s.index.max()), "n_years": int(len(s)),
                "dispersion": r(phi, 2), "last": last}
        first_span = span(FIRST_OWN.get(k, FIRST))
        if s.index.min() <= first_span[0]:
            node["first"] = five_years(s, first_span)
            node["first_to_last"] = window_change(last, node["first"], phi)
        mid_span = CHICAGO_BASE if k == "chicago" else span(MID)
        if s.index.min() <= mid_span[0]:
            node["mid"] = five_years(s, mid_span)
            node["mid_to_last"] = window_change(last, node["mid"], phi)
        if k in RATE_CITIES:
            rt = F.fire_rate(k).set_index("year")
            yrs = [y for y in last["years"] if y in rt.index]
            node["rate_per_million"] = r(float(rt.loc[yrs, "deaths"].sum() / rt.loc[yrs, "pop"].sum() * 1e6), 4)
            node["rate_years"] = yrs
        cities[k] = node
    A.results["cities"] = cities

    contrast = {}
    for k in CITIES:
        if k == "new_york" or "mid_to_last" not in cities[k] or k == "chicago":
            continue
        n_, m_ = cities[k]["last"], cities[k]["mid"]
        ct = change_contrast(w["last"]["deaths"], w["mid"]["deaths"], n_["deaths"], m_["deaths"],
                             exposures_a=(w["last"]["n_years"], w["mid"]["n_years"]), exposures_b=(n_["n_years"], m_["n_years"]),
                             dispersion=max(phi_ny, cities[k]["dispersion"]), nd=4)
        contrast[k] = {key: ct[key] for key in ("ratio", "change_pct", "lo_pct", "hi_pct", "direction")} | {
            "dispersion": r(max(phi_ny, cities[k]["dispersion"]), 2)}
    A.results["contrast"] = {"cities": contrast,
                             "new_york_rose_more_than": [k for k, v in contrast.items() if v["direction"] == "up"],
                             "not_told_apart": [k for k, v in contrast.items() if v["direction"] == "unclear"],
                             "note": "New York's change from 2012-2016 to 2021-2025 over each city's own, as one ratio with a "
                                     "90% range; the larger of the two cities' yearly swings widens it"}
    def span_text(node: dict, k: str) -> str:
        a_, b_ = node["years"][0], node["years"][-1]
        if k == "london":
            return f"{a_ - 1}/{a_ % 100:02d} to {b_ - 1}/{b_ % 100:02d}"
        gap = "" if node["n_years"] == b_ - a_ + 1 else f" ({node['n_years']} years)"
        return f"{a_}-{b_}{gap}"
    table = {}
    for k in CITIES:
        c_ = cities[k]
        if "mid_to_last" not in c_:
            continue
        ch = c_["mid_to_last"]
        table[k] = {"label": c_["label"], "before_years": span_text(c_["mid"], k), "after_years": span_text(c_["last"], k),
                    "before": c_["mid"]["deaths"], "after": c_["last"]["deaths"], "change_pct": ch["change_pct_exact"],
                    "lo_pct": ch["lo_pct"], "hi_pct": ch["hi_pct"], "direction": ch["direction"],
                    "contrast": contrast.get(k)}
    A.results["table"] = table
    both = [k for k in CITIES if "mid_to_last" in cities[k] and k != "chicago"]
    rose = [k for k in both if cities[k]["mid_to_last"]["direction"] == "up"]
    fell = [k for k in both if cities[k]["mid_to_last"]["direction"] == "down"]
    level = [k for k in both if k not in rose + fell]
    long_fell = [k for k in CITIES if "first_to_last" in cities[k] and cities[k]["first_to_last"]["direction"] == "down"]
    A.results["order"] = {
        "mid_to_last": sorted(both, key=lambda k: cities[k]["mid_to_last"]["change_pct"]),
        "rose": rose, "fell": fell, "level": level, "n_both": len(both), "n_rose": len(rose), "n_level": len(level),
        "long_fell": long_fell, "n_long_fell": len(long_fell),
        "n_long": len([k for k in CITIES if "first_to_last" in cities[k]]),
        "rate": sorted(RATE_CITIES, key=lambda k: -cities[k]["rate_per_million"]),
    }
    assert set(rose) == {"new_york", "hong_kong"}, f"the page says New York and Hong Kong rose since 2012-2016: {rose}"
    assert fell == ["yokohama"], f"the page says Yokohama fell: {fell}"
    assert set(level) == {"london", "tokyo", "seoul", "busan", "incheon", "singapore"}, level
    told = A.results["contrast"]["new_york_rose_more_than"]
    assert {"tokyo", "seoul", "yokohama"} <= set(told), f"the page says New York's rise is clear of Tokyo's, Seoul's and Yokohama's change: {told}"
    falls = {k: cities[k]["first_to_last"]["change_pct"] for k in long_fell}
    assert max(falls, key=falls.get) == "new_york", f"the page says New York's long fall is the smallest of the clear falls: {falls}"
    rate_order = A.results["order"]["rate"]
    assert rate_order[:2] == ["chicago", "new_york"], f"the page says New York's rate is the highest but Chicago's: {rate_order}"
    A.claim("cities.london.first_to_last", "down")
    A.claim("cities.tokyo.first_to_last", "down")
    A.claim("cities.yokohama.mid_to_last", "down")
    A.results["rate_ratio_london"] = r(cities["new_york"]["rate_per_million"] / cities["london"]["rate_per_million"], 4)
    lr = F.fire_rate("london").set_index("year")
    lmid = float(lr.loc[cities["london"]["mid"]["years"], "deaths"].sum() / lr.loc[cities["london"]["mid"]["years"], "pop"].sum() * 1e6)
    A.results["rate_ratio_london_mid"] = r(A.results["new_york"]["per_million"]["mid"] / lmid, 4)
    A.results["london_per_million_mid"] = r(lmid, 4)
    # Tokyo's residents are the Metropolitan Government's vintage of January 2026; its revision of 29 October 2026 puts
    # 1 January 2026 0.26% lower (nycdata.world_population), which would raise Tokyo's rate by that much
    revised = cities["tokyo"]["rate_per_million"] * 14270748 / 14234309
    A.results["tokyo_population_vintage"] = {"vintage": "January 2026", "revised_lower_pct": r(100 * (1 - 14234309 / 14270748), 2),
                                             "rate_on_revision": r(revised, 4)}
    assert f"{revised:.1f}" == f"{cities['tokyo']['rate_per_million']:.1f}", "the page says the revision does not move Tokyo's printed rate"
    assert A.results["rate_ratio_london_mid"] < A.results["rate_ratio_london"], "the page says the gap with London has widened"
    A.results["rate_ratio_tokyo"] = r(cities["new_york"]["rate_per_million"] / cities["tokyo"]["rate_per_million"], 2)

    # London's own first-to-mid fall, for the sentence that New York fell with London and Tokyo
    for k in ("london", "tokyo"):
        cities[k]["first_to_mid"] = window_change(cities[k]["mid"], cities[k]["first"], max(1.0, cities[k]["dispersion"]))
    A.claim("cities.london.first_to_mid", "down")
    A.claim("cities.tokyo.first_to_mid", "down")
    # each named change rechecked against the swing of the city's own yearly counts (years left out of its swing aside)
    for path, k in (("cities.london.first_to_last", "london"), ("cities.tokyo.first_to_last", "tokyo"),
                    ("cities.yokohama.mid_to_last", "yokohama"),
                    ("cities.london.first_to_mid", "london"), ("cities.tokyo.first_to_mid", "tokyo")):
        A.recheck(path, yearly_chain(F.deaths(k).set_index("year")["deaths"], OUT_OF_SWING.get(k, [])))
    A.recheck("now.vs_2025", yearly_chain(ny))

    # ---- Tokyo's self-harm deaths, London's Grenfell year, Hong Kong's Wang Fuk Court month
    sh = F.tokyo_self_harm().set_index("year")["self_harm"]
    A.results["tokyo_self_harm"] = {"2025": int(sh[2025]), "2002": int(sh[2002]),
                                    "without_2025": int(F.deaths("tokyo").set_index("year").at[2025, "deaths"] - sh[2025])}
    hk_m = F.hong_kong_months()
    nov = hk_m[hk_m["month"] == "2025-11-01"]["deaths"]
    A.results["hong_kong_2025"] = {"year": int(F.deaths("hong_kong").set_index("year").at[2025, "deaths"]),
                                   "november": int(nov.iloc[0])}
    A.results["london_grenfell_year"] = {"fy": fy(2018), "deaths": int(F.deaths("london").set_index("year").at[2018, "deaths"])}

    # ---- carried to the end of the current year (owner, 19 November 2026): each city with a count for 2026 at its pace
    projection = {"new_york": {"to": NY_TO.isoformat(), "so_far": nov8["deaths"], "year": proj["pace"],
                               "high": proj["shape_of_2025"], "method": "daily pace to 8 November; the higher reading on 2025's shape"}}
    for k in OTHERS:
        y = F.deaths_so_far(k)
        if k == "chicago":
            projection[k] = {"so_far": y[-1]["deaths"] if y else None, "to": y[-1]["to"] if y else None,
                             "method": "not carried: the Medical Examiner's archive fills in as causes are settled, so "
                                       "its latest months are short"}
            continue
        if not y:
            projection[k] = {"so_far": None, "method": "no count for 2026 on file; its five-year mean stands"}
            continue
        cur = y[-1]
        if k == "london":
            value, how = cur["deaths"] * 4, ("the first quarter of the financial year 2026/27 (April to June 2026) times four: "
                                             "a projection of the financial year to March 2027, not of calendar 2026")
        else:
            to = date.fromisoformat(cur["to"])
            d = (to - date(2026, 1, 1)).days + 1
            value, how = cur["deaths"] * 365 / d, f"its daily pace over {d} days carried to 31 December"
        projection[k] = {"to": cur["to"], "so_far": cur["deaths"], "year": int(round(value)), "method": how,
                         "vs_last_mean_pct": r(100 * (value / cities[k]["last"]["per_year"] - 1), 1)}
    projection["new_york"]["vs_last_mean_pct"] = r(100 * (pace / (w["last"]["deaths"] / w["last"]["n_years"]) - 1), 4)
    A.results["projection"] = {"cities": projection, "note": "projections, not counts"}
    above_mean = [k for k, v in projection.items() if v.get("vs_last_mean_pct") is not None and v["vs_last_mean_pct"] > 10]
    A.results["projection"]["above_mean_by_10pct"] = above_mean
    assert "new_york" in above_mean

    # ---- what is said and done: every sentence from its saved page
    hist = {key: Q.quote(src, fname, needle) for key, src, fname, needle in HISTORY}
    A.results["history"] = {"quotes": hist, "lfb_ebike_fires": 206, "lfb_deaths_2025": 2, "scdf_amd_fires": 49,
                            "scdf_amd_fall_pct": 26.9, "tfd_elderly_pct": 77.1, "fdny_battery_cut_pct": 67}

    # ---- printed figures
    P = A.printed
    for path in ("new_york.first.deaths", "new_york.low.deaths", "new_york.recent_peak.deaths", "new_york.latest.deaths",
                 "now.to_nov8", "now.same_point_2025", "now.to_oct5", "now.projection.pace", "now.projection.shape_of_2025",
                 "new_york.windows.mid.deaths", "new_york.windows.last.deaths", "new_york.windows.first.deaths",
                 "battery.peak.deaths", "battery.fires_2026", "battery.fires_2025",
                 "tokyo_self_harm.without_2025", "hong_kong_2025.year", "hong_kong_2025.november",
                 "london_grenfell_year.deaths", "history.lfb_ebike_fires"):
        P(path, fmt="int")
    P("battery.deaths.2026", fmt="int")
    P("battery.deaths.2025", fmt="int")
    P("battery.deaths.2024", fmt="int")
    for path in ("new_york.first_to_mid.change_pct", "new_york.mid_to_last.change_pct", "new_york.first_to_last.change_pct"):
        P(path, f"{abs(A.results['new_york'][path.split('.')[1]]['change_pct_exact']):.0f}%")
    for k in ("london", "tokyo"):
        P(f"cities.{k}.first_to_mid.change_pct", f"{abs(cities[k]['first_to_mid']['change_pct_exact']):.0f}%")
        P(f"cities.{k}.first_to_last.change_pct", f"{abs(cities[k]['first_to_last']['change_pct_exact']):.0f}%")
        P(f"cities.{k}.mid_to_last.change_pct", f"{abs(cities[k]['mid_to_last']['change_pct_exact']):.0f}%")
    for k in ("hong_kong", "yokohama"):
        P(f"cities.{k}.mid_to_last.change_pct", f"{abs(cities[k]['mid_to_last']['change_pct_exact']):.0f}%")
    for k in RATE_CITIES:
        P(f"cities.{k}.rate_per_million", f"{cities[k]['rate_per_million']:.1f}")
    P("rate_ratio_london", f"{A.results['rate_ratio_london']:.1f}")
    P("cities.chicago.mid_to_last.change_pct", f"{abs(cities['chicago']['mid_to_last']['change_pct_exact']):.0f}%")
    P("cities.yokohama.first_to_last.change_pct", f"{abs(cities['yokohama']['first_to_last']['change_pct_exact']):.0f}%")
    P("cities.seoul.first_to_last.change_pct", f"{abs(cities['seoul']['first_to_last']['change_pct_exact']):.0f}%")
    P("projection.cities.seoul.year", fmt="int")
    P("projection.cities.seoul.so_far", fmt="int")
    P("cities.seoul.last.per_year", f"{cities['seoul']['last']['per_year']:.0f}")
    P("history.scdf_amd_fires", fmt="int")
    P("history.tfd_elderly_pct", "77%")
    P("history.fdny_battery_cut_pct", "67%")
    A.results["history"]["fdny_ad_campaign_million"] = 1
    P("history.fdny_ad_campaign_million", "$1")
    A.results["new_york"]["since_low_years"] = int(ny.index.max()) - low
    P("now.vs_2025.change_pct", f"{A.results['now']['vs_2025']['change_pct_exact']:.0f}%")
    P("new_york.twin_parks.deaths", fmt="int")
    P("new_york.twin_parks.mid_to_last_without.change_pct", f"{A.results['new_york']['twin_parks']['mid_to_last_without']['change_pct_exact']:.0f}%")
    P("battery.five_years.deaths", fmt="int")
    P("battery.five_years.mid_to_last_without.change_pct", f"{A.results['battery']['five_years']['mid_to_last_without']['change_pct_exact']:.0f}%")
    P("battery.at_most_2026", fmt="int")
    P("battery.other_at_least_2026", fmt="int")
    P("rate_ratio_london_mid", f"{A.results['rate_ratio_london_mid']:.1f}")
    P("projection.cities.new_york.vs_last_mean_pct", f"{A.results['projection']['cities']['new_york']['vs_last_mean_pct']:.0f}%")
    for k, row in table.items():        # every cell of the table in the questions
        P(f"table.{k}.before", fmt="int")
        P(f"table.{k}.after", fmt="int")
        for key in ("change_pct", "lo_pct", "hi_pct"):
            P(f"table.{k}.{key}", f"{abs(row[key]):.0f}%")
        if row["contrast"]:
            for key in ("change_pct", "lo_pct", "hi_pct"):
                P(f"table.{k}.contrast.{key}", f"{1 + row['contrast'][key] / 100:.2f}")
    P("battery.five_years.share_of_window_pct", f"{A.results['battery']['five_years']['share_of_window_pct']:.0f}%")
    P("battery.five_years.share_of_extra_pct", f"{A.results['battery']['five_years']['share_of_extra_pct']:.0f}%")
    P("battery.five_years.extra_deaths", fmt="int")
    rb = A.results["new_york"]["rise_by_base"]
    P("new_york.rise_by_base.lowest_pct", f"{rb['lowest_pct']:.0f}%")
    P("new_york.rise_by_base.highest_other_pct", f"{rb['highest_other_pct']:.0f}%")
    for k_ in ("first", "mid", "last"):
        P(f"new_york.per_million.{k_}", f"{A.results['new_york']['per_million'][k_]:.1f}")

    # ---- charts
    years = [int(y) for y in ny.index]
    A.chart("long_view", lines(
        title="New York's fire deaths fell to 48 in 2016 and rose to 104 in 2023",
        subtitle="Civilians who died in fires in New York City, 2000-2025, and in lithium-ion battery fires from 2019",
        x=[[str(y), str(y)] for y in years],
        series=[["all", "All fire deaths", "All fires"], ["battery", "In lithium-ion battery fires", "Batteries"]],
        cells={"": {"all": {str(y): int(ny[y]) for y in years},
                    "battery": {str(y): (int(bat[y]) if y in bat.index else None) for y in years}}},
        format="num", axis="Deaths in the year", x_axis="Year",
        x_ticks=[str(y) for y in years if y % 5 == 0 or y == years[-1]],
        note="The Fire Department's Bureau of Fire Investigation: civilians who died of a fire, counted in the month they "
             "died, fires set to take one's own life included; each year from the latest annual report that tables it, "
             "2025 from the Department's release of 5 October 2026. Battery deaths are the Bureau's cause table, 2019-2024, "
             "and the Department's count for 2025.",
        provenance="FDNY Bureau of Fire Investigation annual reports 2008-2024; FDNY releases"))

    A.chart("this_year", strip(
        title="By 8 November New York had lost 86 people to fire, against 44 at the same point of 2025",
        subtitle="Fire deaths in New York City, 1 January to 8 November and the whole year, 2025 and 2026 (2026's whole year "
                 "projected)",
        x=[["to_date", "1 January to 8 November"], ["year", "the whole year (2026 projected)"]],
        series=[["y2025", "2025", "2025"], ["y2026", "2026 (the whole year projected at this year's pace)", "2026"]],
        cells={"": {"y2025": {"to_date": same_2025, "year": int(ny[2025])},
                    "y2026": {"to_date": nov8["deaths"], "year": proj["pace"]}}},
        format="num", axis="Deaths", order="series", zero=True,
        note="The counts to 8 November are the Department's, as the Daily News reported them on 8 November 2026. 2026's "
             "whole year is a projection: the count to 8 November carried at its daily pace to 31 December. On the "
             "shape of 2025, when 44 of the year's 63 deaths had come by 8 November, it would be about 123.",
        provenance="FDNY, as reported by the New York Daily News, 8 November 2026; FDNY release of 5 October 2026"))

    ch_order = A.results["order"]["mid_to_last"] + ["chicago"]
    A.chart("then_and_now", strip(
        title="New York's fire deaths rose by a third from 2012-2016 to 2021-2025; Tokyo's, Seoul's and London's show no clear change",
        subtitle="Change in fire deaths from 2012-2016 to each city's latest five years (2021-2025, with the exceptions "
                 "labelled), each city on its own count",
        x=[["change", "2012-2016 to 2021-2025"]],
        series=[[k, LABEL[k] + {"hong_kong": " (to 2024)", "yokohama": " (to 2024)", "chicago": " (from 2015-2019)",
                                "london": " (financial years)", "singapore": " (2023 missing)"}.get(k, ""), LABEL[k]]
                if k != "chicago" else [k, "Chicago (from 2015-2019, Medical Examiner)", "Chicago (base 2015-2019)"]
                for k in ch_order],
        cells={"": {k: {"change": cities[k]["mid_to_last"]["change_pct"]} for k in ch_order}},
        format="chg", axis="Change in deaths a year", order="series",
        note="Each city against itself, as definitions differ. Hong Kong's and Yokohama's latest five years end in 2024 "
             "(Hong Kong's 2025 is dominated by the Wang Fuk Court fire; Yokohama has not published 2025). London's years "
             "end in March. Chicago's count is the Medical Examiner's, from 2015. Toronto's series starts in 2021, too late "
             "for this comparison. The ranges are in the table in the questions.",
        provenance="FDNY; Home Office FIRE0502; Tokyo Fire Department; Yokohama City Fire Bureau; National Fire Agency "
                   "(Korea); Hong Kong Fire Services Department; Singapore Civil Defence Force; Cook County Medical Examiner"))

    rate_years = list(range(2002, 2026))
    series_rate = {}
    for k in WORLD_LINES:
        rt = F.fire_rate(k).set_index("year")
        if k == "london":
            rt = rt.set_axis(rt.index - 1)      # the financial year ending in March of y is drawn at y - 1, where most of it lies
        series_rate[k] = {str(y): (r(float(rt.at[y, "per_million"]), 2) if y in rt.index and not (k == "hong_kong" and y == 2025)
                                   else None) for y in rate_years}
    A.chart("world_rates", lines(
        title="New York has more fire deaths per resident than London, Tokyo or Hong Kong, and the gap has widened",
        subtitle="Fire deaths per million residents, 2002-2025, each city on its own fire service's count",
        x=[[str(y), str(y)] for y in rate_years],
        series=[[k, LABEL[k], LABEL[k]] for k in WORLD_LINES],
        cells={"": series_rate}, format="dec1", axis="Deaths per million residents", x_axis="Year",
        x_ticks=[str(y) for y in rate_years if y % 5 == 0 or y == rate_years[-1]],
        note="Definitions differ, so the levels are a rough guide; the changes are the firmer reading. London's years end "
             "in March (2017/18 includes Grenfell Tower); Tokyo is its fire department's area over Tokyo-to's population; "
             "Hong Kong's 2025 (the Wang Fuk Court fire) is left off the scale and is in the data file. Toronto (2021-2025) "
             "and Chicago (the Medical Examiner's count, from 2015) are in the next chart. Deaths are counted where "
             "the fire was, not by where the victim lived.",
        provenance="FDNY; Home Office FIRE0502 and ONS; Tokyo Fire Department and TMG; Hong Kong FSD and C&SD; SCDF and SingStat"))

    rate_order = A.results["order"]["rate"]
    A.chart("rates_now", strip(
        title="Per resident, New York's fire deaths are about twice London's and above every city but Chicago's count",
        subtitle="Fire deaths a year per million residents, 2021-2025, each city on its own count",
        x=[["rate", "2021-2025"]],
        series=[[k, LABEL[k] + {"chicago": " (Medical Examiner)", "hong_kong": " (2020-2024)", "singapore": " (2023 missing)",
                                "london": " (financial years)"}.get(k, ""),
                 LABEL[k] + (" (Medical Examiner)" if k == "chicago" else "")] for k in rate_order],
        cells={"": {k: {"rate": cities[k]["rate_per_million"]} for k in rate_order}},
        format="dec1", axis="Deaths a year per million residents", order="series", zero=True,
        note="Each city's deaths over the five years divided by its residents summed over the same years. Seoul, Busan, "
             "Incheon and Yokohama have no population on file here and are compared only with themselves.",
        provenance="FDNY; Home Office; Tokyo Fire Department; Toronto Fire Services; Hong Kong FSD; SCDF; Cook County "
                   "Medical Examiner; each city's statistics office for its population"))

    rows = []
    for k in CITIES:
        for _, x in F.deaths(k).iterrows():
            if str(x["source_id"]).startswith(QUOTED_ONLY):
                continue        # a yearly total quoted from a report whose terms do not license reuse: on the page, not in the file
            if k == "tokyo" and str(x["source_id"]).startswith("tfd_kasai_jittai"):
                # the Fire Department's reports may be quoted, not redistributed: the data file carries Tokyo's years from
                # the open yearbook (CC BY; totals equal to the reports', check_tokyo_yearbook) and leaves the rest out
                if not 2020 <= int(x["year"]) <= 2024:
                    continue
                x = x.copy()
                x["source_id"] = "tmg_fire_deaths_by_type_2025"
            rows.append({"city": LABEL[k], "year": int(x["year"]),
                         "period": f"financial year {fy(int(x['year']))}" if k == "london" else "calendar year",
                         "deaths": int(x["deaths"]), "area": F.CITIES[k][1], "counted_by": F.CITIES[k][2],
                         "what_it_counts": F.CITIES[k][3], "kind": "count", "source": x["source_id"]})
        for p in F.deaths_so_far(k):
            lon = k == "london"
            rows.append({"city": LABEL[k], "year": 2027 if lon else 2026,
                         "period": "1 April to 30 June 2026 (financial year 2026/27)" if lon else f"1 January to {p['to']}",
                         "deaths": p["deaths"], "area": F.CITIES[k][1], "counted_by": F.CITIES[k][2],
                         "what_it_counts": F.CITIES[k][3], "kind": "count so far", "source": p["source_id"]})
        pr = projection.get(k, {})
        if pr.get("year") is not None:
            lon = k == "london"
            rows.append({"city": LABEL[k], "year": 2027 if lon else 2026,
                         "period": "financial year 2026/27, to March 2027" if lon else "calendar year 2026",
                         "deaths": pr["year"], "area": F.CITIES[k][1], "counted_by": "SparkyData projection",
                         "what_it_counts": pr["method"], "kind": "projection", "source": "derived"})
    for y, v in bat.items():
        rows.append({"city": "New York", "year": int(y), "period": "calendar year" if y < 2026 else "to 2026-11-08",
                     "deaths": int(v), "area": "New York City", "counted_by": "FDNY",
                     "what_it_counts": "deaths in fires caused by lithium-ion batteries", "kind": "count" if y < 2026 else "count so far",
                     "source": "fdny_bfi_annual_report_2024" if y < 2025 else "nydn_firehouse_fire_deaths_2026_11"})
    out_rows = pd.DataFrame(rows)
    partial = out_rows["period"].str.startswith(("1 January to", "1 April to", "to 2026"))      # a reading of part of a year
    assert not (partial & (out_rows["kind"] == "count")).any(), "a reading of part of a year is exported as a complete count"
    assert not ((out_rows["year"] >= 2026) & out_rows["period"].eq("calendar year") & (out_rows["kind"] == "count")).any(),         "calendar 2026 is exported as a complete count"
    A.write(data=out_rows)
    print(f"{SLUG}: wrote {A.out}")
    return 0


#: What is said and done about fire deaths: (key, source id, saved file, needle). Each is quoted with its date; none
#: is used as a cause.
HISTORY = [
    ("fdny_battery_2024", "fdny_lithium_ion_progress_2025_01", "fdny_lithium_ion_progress_2025_01.html",
     "In 2024, the city had six deaths related to lithium-ion batteries, compared to 18 deaths in 2023, a 67 percent decrease."),
    ("fdny_campaign", "fdny_lithium_ion_progress_2025_01", "fdny_lithium_ion_progress_2025_01.html",
     "Through consistent safety messaging, inspections, community outreach, and a targeted $1 million ad campaign"),
    ("fdny_leading_cause", "fdny_lithium_ion_progress_2025_01", "fdny_lithium_ion_progress_2025_01.html",
     "The leading cause of fire fatalities was electrical fires, including six lithium-ion related deaths."),
    ("twin_parks", "nyc_comptroller_turn_up_the_heat_2025", "nyc_comptroller_turn_up_the_heat_2025.html",
     "the tragic fire at the Twin Parks development in the Bronx in January 2022"),
    ("fdny_headline", "fdny_lithium_ion_progress_2025_01", "fdny_lithium_ion_progress_2025_01.html",
     "announced significant progress in the department's battle against lithium-ion battery fires"),
    ("nydn_86", "nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html",
     "Eighty-six people have died in fires across the city this year to date, a steep jump from 44 deaths in the same time period last year"),
    ("nydn_battery_10", "nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html",
     "raised the lithium-ion battery fire death toll to 10 so far this year"),
    ("nydn_fires_401", "nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html",
     "The number of fires linked to lithium-ion batteries has also jumped this year to 401 as of last week"),
    ("nydn_fires_292", "nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html",
     "In all of 2025, there were 292 blazes, officials said."),
    ("menin", "nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html",
     "The alarming increase in residential fires in NYC — particularly involving lithium-ion batteries — is an issue we must address"),
    ("hearing", "nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html",
     "examine fire safety laws, enforcement practices and public education efforts around lithium-ion battery safety and storage"),
    ("sunset_park", "nydn_firehouse_fire_deaths_2026_11", "nydn_firehouse_fire_deaths_2026_11.html",
     "The deadly Sunset Park fire's cause remains under investigation."),
    ("lfb_record", "lfb_ebike_fires_2025", "lfb_ebike_fires_2025.html",
     "In total, firefighters attended 206 e-bike and e-scooter fires in 2025"),
    ("lfb_deaths", "lfb_ebike_fires_2025", "lfb_ebike_fires_2025.html",
     "In 2025, two people sadly lost their lives, taking the total number of fatalities in London from these types of fires to five since 2023."),
    ("lfb_regulation", "lfb_ebike_fires_2025", "lfb_ebike_fires_2025.html",
     "Record number of e-bike and e-scooter fires across London in 2025, as Brigade calls for regulation to be introduced"),
    ("lfb_online", "lfb_ebike_fires_2025", "lfb_ebike_fires_2025.html",
     "items purchased online, which don't meet UK safety standards, whether bought new or second-hand, are particularly prone to going up in flames"),
    ("scdf_amd", "scdf_fire_statistics_2025", "scdf_fire_statistics_2025.pdf",
     "Fires involving AMDs decreased by 18 calls (-26.9%) to 49 calls in 2025."),
    ("scdf_taskforce", "scdf_fire_statistics_2025", "scdf_fire_statistics_2025.pdf",
     "The Active Mobility Fire Safety Taskforce, co-chaired by LTA and SCDF, will continue its outreach to AMD owners"),
    ("scdf_definition", "scdf_fire_statistics_2025", "scdf_fire_statistics_2025.pdf",
     "SCDF classifies fire fatalities as deaths resultant from the direct effects of burns, smoke inhalation, or both."),
    ("tfd_elderly", "tfd_kasai_jittai_r08", "tfd_kasai_jittai_r08.pdf", "自損行為を除く高齢者の死者は64 人（77.1％）"),
    ("toronto_definition", "toronto_fire_services_annual_report_2025", "toronto_fire_services_annual_report_2025.pdf",
     "Accidental fires exclude both homicide and suicide"),
]


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