"""How long New Yorkers live against ten other big cities' residents, and how far each city has come since about
1990: the analysis behind a SparkyData article.

    py src/build_article.py living-longer-in-five-cities

Life expectancy at birth from each city's own office (card ``world_city_life_expectancy``): New York's Health
Department, ONS for London, INSEE for Paris (the city, département 75), the Japanese Mortality Database for Tokyo,
Statistics Canada for the City of Toronto and the island of Montreal, C&SD for Hong Kong, SingStat for Singapore's
residents, INE for the Comunidad de Madrid, the Chicago Health Atlas (CDPH) for Chicago and the county health
department's reports for Los Angeles County. ONS, INSEE and C&SD publish men and women only, so the eleven are compared
men with men and women with women; both sexes appear where an office publishes it.

Each city is compared from its earliest period around 1990 to its latest: New York 1989-1991 (its only table before
2000) to 2023, the latest year by sex; London 1991-93 to 2022-24; Paris, Tokyo, Hong Kong, Singapore and Madrid the mean
of 1989-1991 to their latest single year; Toronto and Montreal 1996-98, their earliest, to 2022-24; Chicago 1990 (the
health department's historical table) to 2024 (its annual series, another life-table method: the two give 77.8 and 78.0
for 2010); Los Angeles County 1996 to 2019, the last year its department prints by sex. The pandemic is read from single
years, 2019 against 2020, in the eight cities that publish them. Life expectancy is a published figure without a published
margin here, so the page compares changes of years, never tenths, and calls the order of the eleven observed. The current
reading is this year's deaths so far against the same stretch of 2025 in the five cities whose offices publish months: a
count, not a life expectancy. What each city does about it is quoted from its own plan (RESPONSES), never inferred.

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

from __future__ import annotations

import pandas as pd

from decimal import ROUND_HALF_UP, Decimal

from article_kit import Article, lines, r, strip
from nycdata import world_health as H
from sparkylib.stats import count_change


def rh(v: float, nd: int = 1) -> float:
    """Round half up at ``nd`` decimals (an office's 75.85 prints as 75.9, not Python's 75.8)."""
    q = Decimal(1).scaleb(-nd)
    return float(Decimal(str(v)).quantize(q, rounding=ROUND_HALF_UP))

SLUG = "living-longer-in-five-cities"
SEED = 20261104
CITIES = [("new_york", "New York"), ("london", "London"), ("paris", "Paris"), ("toronto", "Toronto"), ("tokyo", "Tokyo"),
          ("montreal", "Montreal (island)"), ("chicago", "Chicago"), ("los_angeles", "Los Angeles County"),
          ("hong_kong", "Hong Kong"), ("singapore", "Singapore"), ("madrid", "Madrid region")]
FIVE = ("new_york", "london", "paris", "toronto", "tokyo")           # the cities with 2026 deaths so far
SINGLE = ("new_york", "london", "paris", "tokyo", "hong_kong", "singapore", "madrid", "chicago")   # single years for 2019-2020
SEXES = ("male", "female")
#: the break each ranked gain crosses, as its chart label names it
BREAK_LABEL = {"chicago": ", across two methods", "hong_kong": ", across a change of population basis",
               "toronto": ", across two boundary vintages", "montreal": ", across two boundary vintages"}
DOCS = {"nyc_2024": ("doh_pr_life_expectancy_2024_provisional", "doh_pr_life_expectancy_2024_provisional.html",
                     "provisional 2024 life expectancy rose to 83.2 years"),
        "nyc_final_2024": ("doh_pr_vital_statistics_2023", "doh_pr_vital_statistics_2023.html", "Final 2024 data will be released in 2026")}
#: What each city says it does about longevity, quoted from its own documents: (source id, saved file, needle, what).
RESPONSES = {
    "new_york": [("doh_healthynyc_impact_report_2025", "doh_healthynyc_impact_report_2025.pdf", "exceed 83 years by 2030",
                  "target: life expectancy above 83 years by 2030 (HealthyNYC, in local law since 2024)"),
                 ("doh_healthynyc_impact_report_2025", "doh_healthynyc_impact_report_2025.pdf", "we have reached 83.2 years",
                  "the department's own reading: 83.2 in 2024, provisional, ahead of schedule"),
                 ("doh_healthynyc_impact_report_2025", "doh_healthynyc_impact_report_2025.pdf", "93% decrease",
                  "the department's own explanation: a 93% fall in COVID-19 deaths between 2021 and 2024")],
    "london": [("gla_health_inequalities_implementation_plan_2025_2028", "gla_health_inequalities_implementation_plan_2025_2028.pdf",
                "key indicator within the Health Inequalities Strategy", "measure: healthy life expectancy, a gap between boroughs"),
               ("dhsc_10_year_health_plan_summary_2025", "dhsc_10_year_health_plan_summary_2025.html",
                "halve the gap in healthy life expectancy", "national target: halve the regional gap in healthy life expectancy")],
    "paris": [("hcsp_contribution_sns_2023_2033", "hcsp_contribution_sns_2023_2033.pdf", "objectif à 15 ans",
               "objective: raise healthy life expectancy over fifteen years, no number"),
              ("an_cion_soc_cr58_sns_2026", "an_cion_soc_cr58_sns_2026.html", "aucun décret n'a été pris",
               "status: the 2023-2033 strategy was never adopted by decree")],
    "tokyo": [("tmg_health_promotion_plan21_third_ch5", "tmg_health_promotion_plan21_third_ch5.pdf", "83.01",
               "target: healthy life expectancy at 65 to rise faster than remaining life expectancy at 65, by 2032"),
              ("tmg_health_promotion_plan21_third_ch5", "tmg_health_promotion_plan21_third_ch5.pdf", "東京保健所長会方式",
               "the indicator's method: the Tokyo Public Health Directors' Council's healthy life expectancy at 65")],
    "toronto": [("tph_strategic_plan_2024_2028", "tph_strategic_plan_2024_2028.pdf", "protects and improves health at a population level",
                 "the plan's mission, with no longevity target in it"),
                ("tph_mortality_trends_report_2025", "tph_mortality_trends_report_2025.pdf", "reduce preventable deaths and health inequities",
                 "measure: mortality surveillance to target preventable deaths; no target")],
    "montreal": [("msss_pgps_fiche_cibles_2025", "msss_pgps_fiche_cibles_2025.pdf", "mortalité prématurée",
                  "target (Quebec): the premature-mortality gap between the most and least advantaged cut by 10% by 2025")],
    "chicago": [("cdph_healthy_chicago_2025_page", "cdph_healthy_chicago_2025_page.html", "eliminating the life expectancy gap",
                 "target: eliminate the life-expectancy gap between Black and non-Black Chicagoans"),
                ("chicago_mayor_pr_life_expectancy_2022", "chicago_mayor_pr_life_expectancy_2022.html", "up from 8.8 years in 2017",
                 "the gap: ten years in 2020, 8.8 in 2017")],
    "los_angeles": [("lacdph_cheip_2024_2029_revised_2026", "lacdph_cheip_2024_2029_revised_2026.pdf", "Infant Mortality Rates",
                     "measure: the infant-mortality gap halved in five years; no life-expectancy target")],
    "hong_kong": [("hk_dh_ncd_strategy_towards_2025", "hk_dh_ncd_strategy_towards_2025.pdf", "25% relative reduction",
                   "target: a 25% relative cut by 2025 in the risk of premature death from four chronic diseases"),
                  ("hk_dh_ncd_strategy_towards_2025", "hk_dh_ncd_strategy_towards_2025.pdf", "between ages of 30 and 70",
                   "the indicator: the unconditional probability of dying between 30 and 70 from the four diseases"),
                  ("hk_pr_primary_healthcare_blueprint_2022", "hk_pr_primary_healthcare_blueprint_2022.htm", "from treatment to disease prevention",
                   "lever: primary care shifted from treatment to prevention")],
    "singapore": [("moh_speech_masagos_healthier_sg_debate_2022", "moh_speech_masagos_healthier_sg_debate_2022.html", "health-adjusted life expectancy is 75 years",
                   "measure: 85 years of life, 75 in health"),
                  ("moh_pq_life_expectancy_gap_2026", "moh_pq_life_expectancy_gap_2026.html", "10.6 years in 2014 to 11.2 years in 2023",
                   "the gap widened; targets deferred")],
    "madrid": [("madrid_salud_estrategia_ciudad_saludable_2021_2024", "madrid_salud_estrategia_ciudad_saludable_2021_2024.pdf",
                "esperanza de vida activa y saludable", "aim: extend active and healthy life expectancy, no number"),
               ("cm_informe_estado_salud_2025", "cm_informe_estado_salud_2025.pdf", "82,98", "the region's reading: 82.98 men, 87.65 women in 2023")],
}


def value(e: pd.DataFrame, first: int, sex: str, last: int | None = None) -> float:
    """The figure for the period starting in ``first`` (and ending in ``last`` when given), or the mean of the single
    years ``first`` to ``last`` when the office publishes single years."""
    d = e[e["sex"] == sex]
    exact = d[(d["first"] == first) & (d["last"] == (last if last is not None else d["last"]))]
    if last is None:
        exact = d[d["first"] == first]
    if len(exact) == 1:
        return float(exact["e0"].iloc[0])
    years = d[(d["first"] == d["last"]) & d["first"].between(first, last)]
    assert len(years) == last - first + 1, (first, last, sex)
    return float(years["e0"].mean())


def main(argv: list[str] | None = None) -> int:
    """Run the analysis and write every file (no options)."""
    A = Article(SLUG, __file__, seed=SEED)
    E = {k: H.life_expectancy(k) for k, _ in CITIES}
    chi = E["chicago"]
    chi_hist, chi_annual = chi[chi["source"].str.startswith("CDPH historical")], chi[chi["source"].str.startswith("Chicago Health Atlas")]
    labels = dict(CITIES)

    # ---- around 1990 to the latest, by sex: (start label, start, end label, end)
    spans = {"new_york": ("1989-1991", lambda s: value(E["new_york"], 1989, s, 1991), "2023", lambda s: value(E["new_york"], 2023, s)),
             "london": ("1991-1993", lambda s: value(E["london"], 1991, s, 1993), "2022-2024", lambda s: value(E["london"], 2022, s, 2024)),
             "paris": ("1989-1991", lambda s: value(E["paris"], 1989, s, 1991), "2025", lambda s: value(E["paris"], 2025, s)),
             "toronto": ("1996-1998", lambda s: value(E["toronto"], 1996, s, 1998), "2022-2024", lambda s: value(E["toronto"], 2022, s, 2024)),
             "tokyo": ("1989-1991", lambda s: value(E["tokyo"], 1989, s, 1991), "2024", lambda s: value(E["tokyo"], 2024, s)),
             "montreal": ("1996-1998", lambda s: value(E["montreal"], 1996, s, 1998), "2022-2024", lambda s: value(E["montreal"], 2022, s, 2024)),
             "hong_kong": ("1989-1991", lambda s: value(E["hong_kong"], 1989, s, 1991), "2025", lambda s: value(E["hong_kong"], 2025, s)),
             "singapore": ("1989-1991", lambda s: value(E["singapore"], 1989, s, 1991), "2025", lambda s: value(E["singapore"], 2025, s)),
             "madrid": ("1989-1991", lambda s: value(E["madrid"], 1989, s, 1991), "2024", lambda s: value(E["madrid"], 2024, s)),
             "chicago": ("1990", lambda s: value(chi_hist, 1990, s), "2024", lambda s: value(chi_annual, 2024, s))}
    gains = {}
    for k, (l0, f0, l1, f1) in spans.items():
        gains[k] = {"from": l0, "to": l1}
        for s in SEXES:
            a, b = f0(s), f1(s)
            gains[k][s] = {"start": rh(a), "end": rh(b), "gain": rh(b - a)}
    # each break, named beside the gain it touches (owner, 5 November 2026: published figures are ranked as an observed order)
    gains["hong_kong"]["crosses_basis"] = "C&SD's figures rest on the extended de facto population to 1995 and the resident population from 1996"
    gains["chicago"]["crosses_basis"] = "two life-table methods: the health department's historical table for 1990 and its annual series for 2024, 1.3 years apart for men in 2010 and 1.1 for women"
    for k in ("toronto", "montreal"):
        gains[k]["crosses_basis"] = "Statistics Canada's 1996-98 and 2000-02 figures are on the boundaries of their time, the later ones on 2023 boundaries: continuity not tested"
    A.results["gains"] = gains
    # Los Angeles County: levels only, each on its own basis (1996-2000 on 1990-based populations, 2001-2005 on Census-2000 ones,
    # 2010 and 2019 from another report), never a gain across them
    la = {s: {str(y): rh(value(E["los_angeles"], y, s)) for y in (1996, 2000, 2001, 2005, 2010, 2019)} for s in SEXES}
    la["basis"] = "1996-2000 on 1990-based population estimates; 2001-2005 on Census-2000 estimates; 2010 and 2019 from the 2010-2019 report"
    A.results["los_angeles_levels"] = la
    order = {}
    for s in SEXES:
        levels = {k: gains[k][s]["end"] for k in gains}
        levels["los_angeles"] = la[s]["2019"]
        levels["chicago"] = rh(value(chi_annual, 2024, s))
        ny = levels["new_york"]
        ranked = list(gains)                                            # every city with a start and an end, breaks named
        comparable = [k for k in gains if "crosses_basis" not in gains[k]]  # one basis, method and boundary throughout: the sensitivity
        by_gain = sorted(ranked, key=lambda k: -gains[k][s]["gain"])
        order[s] = {"by_gain": by_gain, "new_york_gain_rank": by_gain.index("new_york") + 1,
                    "ranked": ranked, "comparable": comparable, "gains_above_new_york": [k for k in ranked if gains[k][s]["gain"] > gains["new_york"][s]["gain"]],
                    "gains_above_new_york_within_basis": [k for k in gains if "crosses_basis" not in gains[k] and gains[k][s]["gain"] > gains["new_york"][s]["gain"]],
                    "levels": levels, "strictly_above_new_york": sorted((k for k in levels if levels[k] > ny), key=lambda k: levels[k]),
                    "level_with_new_york": [k for k in levels if k != "new_york" and levels[k] == ny],
                    "strictly_below_new_york": sorted((k for k in levels if levels[k] < ny), key=lambda k: levels[k])}
        order[s]["cities_above_new_york"] = len(order[s]["strictly_above_new_york"])
    A.results["order"] = order
    assert order["male"]["new_york_gain_rank"] == 1 and order["male"]["strictly_below_new_york"] == ["chicago", "los_angeles"], order["male"]
    assert order["male"]["level_with_new_york"] == [] and order["female"]["level_with_new_york"] == ["los_angeles"], order
    # Los Angeles County's men sit a tenth below New York's 2023 figure, on a 2019 estimate: a difference these figures cannot assess
    A.results["new_york_minus_los_angeles_male"] = rh(order["male"]["levels"]["new_york"] - order["male"]["levels"]["los_angeles"])
    assert abs(A.results["new_york_minus_los_angeles_male"]) <= 0.1
    assert order["female"]["strictly_below_new_york"] == ["chicago", "london"], order["female"]
    assert len(order["male"]["ranked"]) == 10 and len(order["male"]["comparable"]) == 6, order["male"]
    assert sorted(order["female"]["gains_above_new_york"]) == ["hong_kong", "singapore"] and order["female"]["gains_above_new_york_within_basis"] == ["singapore"], order["female"]
    A.results["new_york_lead_male"] = rh(gains["new_york"]["male"]["gain"] - max(gains[k]["male"]["gain"] for k in order["male"]["ranked"] if k != "new_york"))
    A.results["new_york_lead_male_within_one_basis"] = rh(gains["new_york"]["male"]["gain"] - max(gains[k]["male"]["gain"] for k in order["male"]["comparable"] if k != "new_york"))
    A.results["new_york_female_gain_rank"] = order["female"]["new_york_gain_rank"]
    assert order["female"]["new_york_gain_rank"] == 3
    # Chicago's two methods: the overlap at 2010 by sex, and the gain within each method; the gain across them is as published
    cm = {}
    for s in ("both", *SEXES):
        h, a_ = value(chi_hist, 2010, s), value(chi_annual, 2010, s)
        cm[s] = {"historical_2010": rh(h, 2), "annual_2010": rh(a_, 2), "annual_minus_historical": rh(a_ - h)}
    for s in SEXES:
        cm[s]["gain_1990_2010_historical"] = rh(value(chi_hist, 2010, s) - value(chi_hist, 1990, s))
        cm[s]["gain_2010_2024_annual"] = rh(value(chi_annual, 2024, s) - value(chi_annual, 2010, s))
        cm[s]["gain_across_as_published"] = rh(value(chi_annual, 2024, s) - value(chi_hist, 1990, s))   # two methods: ranked as published, the break named
        cm[s]["gain_across_less_offset"] = rh(value(chi_annual, 2024, s) - value(chi_hist, 1990, s) - (value(chi_annual, 2010, s) - value(chi_hist, 2010, s)))
        cm[s]["end_2024"] = rh(value(chi_annual, 2024, s)); cm[s]["start_1990"] = rh(value(chi_hist, 1990, s))
    for s in SEXES:
        cm[s]["chicago_2010_2023_annual"] = rh(value(chi_annual, 2023, s) - value(chi_annual, 2010, s))
        cm[s]["new_york_2010_2023"] = rh(value(E["new_york"], 2023, s) - value(E["new_york"], 2010, s))
    for s in SEXES:                                                  # a sensitivity: the 2010 method gap taken out, not a harmonised series
        others = {k: gains[k][s]["gain"] for k in gains if k != "chicago"}
        cm[s]["rank_less_offset"] = 1 + sum(v > cm[s]["gain_across_less_offset"] for v in others.values())
        cm[s]["rank_as_published"] = 1 + sum(v > gains["chicago"][s]["gain"] for v in others.values())
    assert cm["male"]["rank_as_published"] == 2 and cm["male"]["rank_less_offset"] == 5, cm["male"]
    A.results["chicago_methods"] = cm
    A.results["new_york_minus_chicago_male_now"] = rh(gains["new_york"]["male"]["end"] - value(chi_annual, 2024, "male"))
    # the published 95% intervals, where an office publishes them, on the latest figures (New York's office publishes none)
    iv = {}
    for k in ("london", "toronto", "montreal"):
        e = E[k]
        for s in SEXES:
            row = e[(e["sex"] == s) & (e["first"] == 2022)].iloc[0]
            iv.setdefault(k, {})[s] = {"end": rh(row["e0"]), "lo": rh(row["lo"]), "hi": rh(row["hi"])}
    A.results["intervals"] = iv
    # a common endpoint, 2023, for the offices with single years (New York's latest year by sex): does the order change?
    ce = {}
    for s in SEXES:
        ce[s] = {k: rh(value(E[k], 2023, s) - value(E[k], 1989, s, 1991)) for k in ("new_york", "paris", "tokyo", "singapore", "madrid")}
        ce[s]["new_york"] = gains["new_york"][s]["gain"]
        ce[s]["london_2022_2024"] = gains["london"][s]["gain"]
        ce[s]["above_new_york"] = [k for k, v in ce[s].items() if k not in ("new_york", "above_new_york") and v > ce[s]["new_york"]]
    A.results["common_endpoint_2023"] = ce
    A.results["intervals_note"] = ("ONS, Statistics Canada and Chicago's historical table publish 95% intervals (in the data file); the Health Department, "
                                   "INSEE, the Japanese Mortality Database, C&SD, SingStat, INE and the Chicago Health Atlas's city rows carry none, so no "
                                   "contrast with New York can be given a range")
    # Hong Kong on its resident-population basis only (from 1996): the gain since then, a sensitivity to the 1996 change
    A.results["hong_kong_since_1996"] = {s: {"1996": rh(value(E["hong_kong"], 1996, s)), "2025": rh(value(E["hong_kong"], 2025, s)),
                                             "gain": rh(value(E["hong_kong"], 2025, s) - value(E["hong_kong"], 1996, s))} for s in SEXES}
    # Tokyo: the database against the ministry's five-yearly tables, signed, the latest overlaps
    mh = H.mhlw_tokyo().set_index(["first", "sex"])["e0"]; jm = E["tokyo"].set_index(["first", "sex"])["e0"]
    A.results["tokyo_database_minus_ministry"] = {f"{y}_{s}": rh(jm[(y, s)] - mh[(y, s)], 2) for y in (2010, 2015, 2020) for s in SEXES}

    # both sexes, where an office publishes it
    both = {"new_york": {"1989_1991": value(E["new_york"], 1989, "both", 1991), "2019": value(E["new_york"], 2019, "both"),
                         "2020": value(E["new_york"], 2020, "both"), "2023": value(E["new_york"], 2023, "both"),
                         "2024": value(E["new_york"], 2024, "both")},
            "tokyo": {"2024": value(E["tokyo"], 2024, "both")},
            "toronto": {"2022_2024": value(E["toronto"], 2022, "both", 2024)},
            "montreal": {"2022_2024": value(E["montreal"], 2022, "both", 2024)},
            "singapore": {"2025": value(E["singapore"], 2025, "both")},
            "madrid": {"2024": value(E["madrid"], 2024, "both")},
            "chicago": {"2024": value(chi_annual, 2024, "both")},
            "los_angeles": {"2019": value(E["los_angeles"], 2019, "both")}}
    A.results["both"] = {k: {p: r(v, 1) for p, v in d.items()} for k, d in both.items()}
    A.results["both"]["new_york"]["gain_since_1990"] = r(both["new_york"]["2024"] - both["new_york"]["1989_1991"], 1)
    A.results["both"]["new_york"]["drop_2020"] = r(both["new_york"]["2019"] - both["new_york"]["2020"], 1)

    # ---- the pandemic, single years: 2019 against 2020, eight cities
    lon1 = H.london_single_years()
    A.results["london_single_2024"] = {s: rh(value(lon1, 2024, s)) for s in SEXES}
    for s in SEXES:
        A.printed(f"london_single_2024.{s}", f"{A.results['london_single_2024'][s]:.1f}")
    single = {k: (lon1 if k == "london" else chi_annual if k == "chicago" else E[k]) for k in SINGLE}
    pandemic = {}
    for k, e in single.items():
        pandemic[k] = {}
        for s in SEXES:
            a, b = value(e, 2019, s), value(e, 2020, s)
            pandemic[k][s] = {"2019": r(a, 1), "2020": r(b, 1), "change": r(b - a, 1)}
    A.results["pandemic"] = pandemic
    assert all(pandemic["new_york"][s]["change"] < min(pandemic[k][s]["change"] for k in pandemic if k != "new_york") for s in SEXES)
    A.results["pandemic_order_male"] = sorted(pandemic, key=lambda k: pandemic[k]["male"]["change"])
    A.results["pandemic_rose_male"] = [k for k in pandemic if pandemic[k]["male"]["change"] > 0]
    A.results["new_york_male_2023_vs_2019"] = {"2019": rh(value(E["new_york"], 2019, "male")), "2023": rh(value(E["new_york"], 2023, "male"))}
    A.results["recovered"] = {"new_york_2019": r(both["new_york"]["2019"], 1), "new_york_2023": r(both["new_york"]["2023"], 1)}

    # ---- this year's deaths so far (the five offices that publish months)
    now = {}
    for k in FIVE:
        d = H.deaths_2026(k)
        cc = count_change(d["2026"], d["2025"])
        now[k] = {**d, **cc, "change_pct": r(100 * (d["2026"] / d["2025"] - 1), 1),
                  "model": "a plain count model (90% range)"}
    A.results["deaths_2026"] = now
    A.results["deaths_2026_clear"] = [k for k in now if now[k]["direction"] in ("up", "down")]
    named = []
    for k in ("new_york", "london"):              # the two offices with a short-period series to recheck against
        again = A.recheck(f"deaths_2026.{k}", H.deaths_series(k))
        now[k]["rechecked"] = again["direction"]
        now[k]["rechecked_lo_pct"], now[k]["rechecked_hi_pct"], now[k]["dispersion"] = again["lo_pct"], again["hi_pct"], again["dispersion"]
        now[k]["model"] += "; rechecked against the series' own swing (New York's months since January 2024, London's weeks since January 2025), a sensitivity that does not capture every form of serial dependence, reporting delay or revision"
        if again["direction"] in ("up", "down") and now[k]["direction"] == again["direction"]:
            A.claim(f"deaths_2026.{k}", again["direction"]); named.append(k)
    for k in ("paris", "tokyo", "toronto"):
        now[k]["rechecked"] = "no short-period series assembled here" if k != "toronto" else "a first release against a revised year: no direction read"
        now[k]["model"] += "; no short-period series assembled here for the recheck, so no direction is named" if k != "toronto" else "; a first release against a revised year, no direction read"
    A.results["deaths_2026_named"] = named

    # ---- the documents
    Q = A.quotes()
    A.results["quotes"] = {}
    for key, (src, fname, needle) in DOCS.items():
        q = Q.quote(src, fname, needle)
        A.results["quotes"][key] = {"quote": q["quote"], "source": q["source"]}
    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"]})
    A.results["responses"] = out
    A.results["response_documents"] = sorted({d[0] for docs in RESPONSES.values() for d in docs})
    A.results["response_documents_n"] = len(A.results["response_documents"])
    # what each document's target is, by the measure it names (read from the quotes; a classification, not a count of plans)
    A.results["targets_by_measure"] = {
        "life_expectancy_at_birth_threshold": ["new_york"],
        "gap_in_healthy_life_expectancy": ["london"],
        "healthy_life_expectancy_at_65_direction": ["tokyo"],
        "premature_mortality_probability_30_to_70": ["hong_kong"],
        "gap_in_premature_mortality_by_socioeconomic_advantage": ["montreal"],
        "gap_in_life_expectancy_by_race": ["chicago"],
        "gap_in_infant_mortality_by_race": ["los_angeles"],
        "aim_without_a_number": ["paris", "singapore", "madrid"],
        "no_longevity_target_in_the_document": ["toronto"]}
    figs = {}
    for key, city, token, needle in (("ny_target", "new_york", "83", "83 years by 2030"), ("ny_reached", "new_york", "83.2", None),
                                     ("chicago_gap_2017", "chicago", "8.8", None), ("hk_cut", "hong_kong", "25%", None),
                                     ("sg_le", "singapore", "85", "85 years"), ("sg_hale", "singapore", "75", "75 years"),
                                     ("sg_gap_2014", "singapore", "10.6", None), ("sg_gap_2023", "singapore", "11.2", None),
                                     ("madrid_men_2023", "madrid", "82.98", "82,98"), ("madrid_women_2023", "madrid", "87.65", "87,65"),
                                     ("tokyo_hle_men", "tokyo", "83.01", None), ("tokyo_hle_women", "tokyo", "86.19", None), ("ny_covid_fall", "new_york", "93%", None),
                                     ("montreal_cut", "montreal", "10%", "10 %"), ("la_imr_cut", "los_angeles", "50%", None), ("hk_ages", "hong_kong", "30", None), ("hk_ages_70", "hong_kong", "70", None)):
        assert any((needle or token) in d["quote"] for d in out[city]), (key, token)
        figs[key] = token
        A.printed(f"responses_figures.{key}", token)
    A.results["responses_figures"] = figs

    A.results["method"] = {
        "spans": {k: f"{v[0]} to {v[2]}" for k, v in spans.items()},
        "single_years": "Paris, Tokyo, Hong Kong, Singapore and Madrid publish single years: their 1989-1991 is the mean of the three",
        "chicago": "two life-table methods, the historical table (1990, 2000, 2010) and the annual series (2010-2024), whose 2010 values differ "
                   "by 0.2 years for both sexes, 1.3 for men and 1.1 for women: the gain across them (1990 to 2024) is in the observed ranking with the break named, and the gain within each table and the gain with the 2010 gap taken out (rank_less_offset) are sensitivities",
        "los_angeles": "the county, not the city; levels only, each on its own basis, no gain across the 2001 break; the latest figures by sex we could read are the 2019 report's (the county's later dashboard is a Power BI embed with no file)",
        "chicago_methods": "the 2010 overlap by sex (annual minus historical: men 1.3, women 1.1) and the gain within each method are in chicago_methods",
        "ties": "a city is above New York only when its published figure is strictly higher at the published precision; ties are listed",
        "deaths_2026": "count_change on the two totals; New York's and London's rechecked against their monthly and weekly series (no direction survives), Paris's and Tokyo's without a short-period series assembled here, Toronto's a first release: no direction is named for any",
        "both_sexes": "published by New York, Tokyo, Toronto, Montreal, Singapore, Madrid and Chicago; London, Paris and Hong Kong by sex only",
        "order": "an observed order of published point figures, no interval for New York's, so no contrast with New York can be assessed; a tenth's difference is reported as a tenth",
        "ranked": "every city with a published start around 1990 and a latest figure is ranked as published (owner, 5 November 2026): ten; the break each gain crosses is named beside it (Hong Kong's 1996 population basis, Toronto's and Montreal's two boundary vintages, Chicago's two methods); Los Angeles County has levels only, its 2001 population-basis break moving its figure by more than a year",
        "comparable": "the sensitivity: the six cities whose series runs on one population basis, one method and one set of boundaries throughout",
        "now": "deaths so far in 2026 against the same stretch of 2025 in the five cities whose offices publish months: not a life expectancy"}
    A.latest("2026-09", "Deaths so far in 2026 against the same stretch of 2025: New York and Paris to September, London to week 43, "
             "Tokyo to August, Toronto to March", why_older="No city has published a 2026 life expectancy; New York's latest is "
             "2024, provisional")
    A.long_view(1990, 2025, "Life expectancy at birth by sex from about 1990 (New York 1989-1991, London 1991-93, Paris, Tokyo, Hong "
                "Kong, Singapore and Madrid every year, Chicago 1990, Toronto, Montreal and Los Angeles County from 1996) to each city's latest year")
    A.reproduce("London, men's life expectancy 2022-24 (ONS bulletin)", published=80.5, published_moe90=None,
                reproduced=gains["london"]["male"]["end"], kind="rate", tolerance=0.05)
    A.reproduce("Paris, women's life expectancy 2025 (INSEE)", published=87.1, published_moe90=None,
                reproduced=gains["paris"]["female"]["end"], kind="rate", tolerance=0.05)
    A.reproduce("New York, life expectancy 2023 (DOHMH)", published=82.6, published_moe90=None,
                reproduced=A.results["both"]["new_york"]["2023"], kind="rate", tolerance=0.05)
    A.reproduce("Hong Kong, men's life expectancy 2025 (C&SD's table)", published=83.1, published_moe90=None,
                reproduced=gains["hong_kong"]["male"]["end"], kind="rate", tolerance=0.05)
    # the Comunidad de Madrid's health report prints 82.98 for men in 2023 from its own life table; INE's table gives 82.92:
    # two offices' tables, kept apart on the page, not a reproduction
    A.results["madrid_2023_two_tables"] = {"region_report_male": 82.98, "ine_male": r(value(E["madrid"], 2023, "male"), 2)}
    A.printed("madrid_2023_two_tables.ine_male", f"{A.results['madrid_2023_two_tables']['ine_male']:.2f}")
    A.results["reproduction_source"] = ("ONS's bulletin of 10 December 2025; INSEE's key figures of 5 February 2026; DOHMH's release of "
                                        "30 December 2025; C&SD's table 115-01011")
    A.results["reproduction_note"] = "Each published figure against the same figure read from the office's file."

    # ---- what the prose prints
    for k in gains:
        for s in SEXES:
            for f in ("start", "end", "gain"):
                A.printed(f"gains.{k}.{s}.{f}", f"{gains[k][s][f]:.1f}")
    for s in SEXES:
        for y in ("1996", "2000", "2001", "2005", "2010", "2019"):
            A.printed(f"los_angeles_levels.{s}.{y}", f"{la[s][y]:.1f}")
        for f in ("annual_minus_historical", "gain_1990_2010_historical", "gain_2010_2024_annual", "gain_across_as_published", "gain_across_less_offset", "end_2024", "chicago_2010_2023_annual", "new_york_2010_2023"):
            A.printed(f"chicago_methods.{s}.{f}", f"{cm[s][f]:.1f}")
        A.printed(f"hong_kong_since_1996.{s}.gain", f"{A.results['hong_kong_since_1996'][s]['gain']:.1f}")
        for k in iv:
            A.printed(f"intervals.{k}.{s}.lo", f"{iv[k][s]['lo']:.1f}"); A.printed(f"intervals.{k}.{s}.hi", f"{iv[k][s]['hi']:.1f}")
    for k_, v_ in A.results["tokyo_database_minus_ministry"].items():
        A.printed(f"tokyo_database_minus_ministry.{k_}", f"{v_:+.2f}")
    A.printed("new_york_male_2023_vs_2019.2019", f"{A.results['new_york_male_2023_vs_2019']['2019']:.1f}")
    for k in now:
        A.printed(f"deaths_2026.{k}.lo_pct", f"{now[k]['lo_pct']:+.1f}%")
        A.printed(f"deaths_2026.{k}.hi_pct", f"{now[k]['hi_pct']:+.1f}%")
        if "rechecked_lo_pct" in now[k]:
            A.printed(f"deaths_2026.{k}.rechecked_lo_pct", f"{now[k]['rechecked_lo_pct']:+.1f}%"); A.printed(f"deaths_2026.{k}.rechecked_hi_pct", f"{now[k]['rechecked_hi_pct']:+.1f}%")
    for k in pandemic:
        for s in SEXES:
            for f in ("2019", "2020"):
                A.printed(f"pandemic.{k}.{s}.{f}", f"{pandemic[k][s][f]:.1f}")
            A.printed(f"pandemic.{k}.{s}.change", f"{abs(pandemic[k][s]['change']):.1f}")
    for k, d in A.results["both"].items():
        for p, v in d.items():
            A.printed(f"both.{k}.{p}", f"{v:.1f}")
    A.printed("new_york_lead_male", f"{A.results['new_york_lead_male']:.1f}")
    A.printed("new_york_lead_male_within_one_basis", f"{A.results['new_york_lead_male_within_one_basis']:.1f}")
    for s in SEXES:
        for k in ("paris", "tokyo", "singapore", "madrid"):
            A.printed(f"common_endpoint_2023.{s}.{k}", f"{ce[s][k]:.1f}")
    A.printed("new_york_minus_chicago_male_now", f"{A.results['new_york_minus_chicago_male_now']:.1f}")
    A.printed("order.male.cities_above_new_york", str(order["male"]["cities_above_new_york"]))
    A.printed("order.female.cities_above_new_york", str(order["female"]["cities_above_new_york"]))
    A.printed("response_documents_n", str(A.results["response_documents_n"]))
    for k in now:
        A.printed(f"deaths_2026.{k}.2026", f"{now[k]['2026']:,}")
        A.printed(f"deaths_2026.{k}.2025", f"{now[k]['2025']:,}")
        A.printed(f"deaths_2026.{k}.change_pct", f"{abs(now[k]['change_pct']):.1f}%")

    # ---- charts
    for s, word in (("male", "Men"), ("female", "Women")):
        A.chart(f"{s}_gains", strip(
            title=("Men's life expectancy rose more in New York than in nine other big cities since about 1990, and New York's men still trail eight of them"
                   if s == "male" else "Women's life expectancy rose most in Hong Kong and Singapore, then New York, whose women still trail seven cities"),
            subtitle=f"{word}'s life expectancy at birth, around 1990 and the latest year, in years; hover a dot for the row's exact years and the break it crosses where there is one",
            x=[["start", "Around 1990"], ["end", "Latest"]],
            series=[[k, f"{labels[k]} ({gains[k]['from']} to {gains[k]['to']}{BREAK_LABEL.get(k, '')})", labels[k]] for k, _ in CITIES if k in gains],
            cells={"": {k: {"start": gains[k][s]["start"], "end": gains[k][s]["end"]} for k, _ in CITIES if k in gains}},
            format="dec1", axis="Life expectancy at birth, years", zero=False,
            note="Each office's own measure: New York, the Health Department (1989-1991 and 2023); London, ONS (three-year periods); "
                 "Paris, INSEE (1989-1991 averaged, 2025 provisional); Toronto and the island of Montreal, Statistics Canada (three-year "
                 "periods, from 1996-98); Tokyo, the Japanese Mortality Database (1989-1991 averaged, 2024); Hong Kong, C&SD (2025); "
                 "Singapore residents, SingStat (2025, preliminary); the Madrid region, INE (2024); Chicago, its health department's "
                 "historical table for 1990 and its annual series for 2024, two methods; Hong Kong's 1989-1991 is on an earlier population basis "
                 "than its 2025, and Toronto's and Montreal's 1996-98 on earlier boundaries than their 2022-24: each drawn as published, the "
                 "break named. Los Angeles County has no pair from about 1990 to its latest figure on one basis and is in the table.",
            provenance="NYC Health Department; ONS; INSEE; Statistics Canada; Japanese Mortality Database (IPSS); C&SD; SingStat; INE; CDPH; LA County DPH"))

    years = list(range(1989, 2026))
    def series_for(k, s, lo=1989, hi=2025):
        src = chi_annual if k == "chicago" else chi_hist if k == "chicago_historical" else E[k]
        e = src[src["sex"] == s]
        out = {}
        for _, row in e.iterrows():
            mid = (int(row["first"]) + int(row["last"])) // 2
            if lo <= mid <= hi:
                out[str(mid)] = r(row["e0"], 2)
        return out
    long_series = [[k, labels[k], labels[k]] for k, _ in CITIES if k not in ("chicago", "los_angeles", "hong_kong", "toronto", "montreal")]
    long_series += [["toronto_a", "Toronto (1996-98 and 2000-02, boundaries of the time)", "Toronto, earlier boundaries", "Toronto"], ["toronto_b", "Toronto (from 2006-08, 2023 boundaries)", "Toronto", "Toronto"],
                    ["montreal_a", "Montreal (1996-98 and 2000-02, boundaries of the time)", "Montreal, earlier boundaries", "Montreal"], ["montreal_b", "Montreal (from 2006-08, 2023 boundaries)", "Montreal", "Montreal"]]
    long_series += [["hong_kong_a", "Hong Kong (to 1995, extended de facto population)", "Hong Kong to 1995", "Hong Kong"], ["hong_kong_b", "Hong Kong (from 1996, resident population)", "Hong Kong", "Hong Kong"]]
    long_series += [["chicago", "Chicago (annual series, from 2010)", "Chicago", "Chicago"], ["chicago_historical", "Chicago (historical table: 1990, 2000, 2010)", "Chicago, decades", "Chicago"],
                    ["los_angeles_a", "Los Angeles County (1996-2000, one basis)", "LA County to 2000", "Los Angeles County"], ["los_angeles_b", "Los Angeles County (2001-2005, another basis)", "LA County 2001-05", "Los Angeles County"],
                    ["los_angeles_c", "Los Angeles County (2010 and 2019, its report)", "LA County 2010, 2019", "Los Angeles County"]]
    long_cells = {k: series_for(k, "male") for k, _ in CITIES if k not in ("chicago", "los_angeles", "hong_kong", "toronto", "montreal")}
    long_cells.update({"toronto_a": series_for("toronto", "male", 1989, 2003), "toronto_b": series_for("toronto", "male", 2006, 2025),
                       "montreal_a": series_for("montreal", "male", 1989, 2003), "montreal_b": series_for("montreal", "male", 2006, 2025)})
    long_cells.update({"hong_kong_a": series_for("hong_kong", "male", 1989, 1995), "hong_kong_b": series_for("hong_kong", "male", 1996, 2025)})
    long_cells.update({"chicago": series_for("chicago", "male"), "chicago_historical": series_for("chicago_historical", "male"),
                       "los_angeles_a": series_for("los_angeles", "male", 1996, 2000), "los_angeles_b": series_for("los_angeles", "male", 2001, 2005),
                       "los_angeles_c": series_for("los_angeles", "male", 2010, 2019)})
    A.chart("men_long_view", lines(
        title="New York's men have gained on the other cities since 1990; Chicago's are the lowest in every year its office prints",
        subtitle="Men's life expectancy at birth, years (three-year periods drawn at their middle year; a series breaks where an office changed its method or its population basis)",
        x=[[str(t), str(t)] for t in years],
        series=long_series,
        cells={"": long_cells},
        format="dec1", axis="Men's life expectancy at birth, years", zero=False,
        x_ticks=[str(t) for t in years if t % 5 == 0], connect=True, labels="legend",
        note="New York prints no single years before 2000: its first point is 1989-1991, joined to 2000, the one join across a gap. London, "
             "Toronto and Montreal are three-year periods drawn at their middle year; Chicago's historical table (1990, 2000, 2010) and its "
             "annual series from 2010 are separate series, two methods; Los Angeles County is three separate series (1996-2000 and 2001-2005 "
             "on two population bases, then its report's 2010 and 2019); Hong Kong breaks at 1996, where its office changed its population basis; Toronto and Montreal "
             "break between 2000-02 and 2006-08, where Statistics Canada's boundaries change (continuity untested); Paris, Tokyo, Singapore and Madrid are single "
             "years. Every series is joined across its own missing years (New York 1989-1991 to 2000; the three-year periods; Chicago's and Los Angeles County's "
             "benchmark points), never across a break.",
        provenance="NYC Health Department; ONS; INSEE; Statistics Canada; Japanese Mortality Database (IPSS); C&SD; SingStat; INE; CDPH; LA County DPH"))

    A.chart("pandemic", strip(
        title="In 2020 New York lost more years of life expectancy than any of the seven other cities with single years",
        subtitle="Men's life expectancy at birth, 2019 and 2020, single years",
        x=[["2019", "2019"], ["2020", "2020"]],
        series=[[k, labels[k], labels[k]] for k in pandemic],
        cells={"": {k: {"2019": pandemic[k]["male"]["2019"], "2020": pandemic[k]["male"]["2020"]} for k in pandemic}},
        format="dec1", axis="Men's life expectancy at birth, years", zero=False,
        note="Single years: London's from ONS's series in development; Chicago's from the Health Atlas. Toronto, Montreal and Los Angeles "
             "County publish no single years for 2019 and 2020.",
        provenance="NYC Health Department; ONS; INSEE; Japanese Mortality Database (IPSS); C&SD; SingStat; INE; CDPH"))

    rows_out = []
    for k, label in CITIES + [("london_single", "London")]:
        frame = lon1 if k == "london_single" else E[k]
        for _, row in frame.iterrows():
            rows_out.append({"city": label, "first": int(row["first"]), "last": int(row["last"]), "sex": row["sex"],
                             "life_expectancy": float(row["e0"]), "lo95": row.get("lo"), "hi95": row.get("hi"), "source": row["source"]})
    A.write(data=pd.DataFrame(rows_out))
    print(f"{SLUG}: wrote {A.out}")
    return 0


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