"""Grocery prices in New York against other big cities', 1990 to 2026: the analysis behind a SparkyData article.

    py src/build_article.py grocery-prices-in-big-cities

The consumer price index of each city's own statistics office for the group closest to food bought to eat at home,
with the same area's all-items index (card ``world_city_food_prices``, loader ``nycdata.world_prices``): the Bureau of
Labor Statistics' food at home for New York, Chicago, Los Angeles and the U.S. city average; Statistics Canada's food
purchased from stores (Ontario's and Quebec's, beside Toronto's and Montreal's all items); the Statistics Bureau of
Japan's food for Tokyo's wards and Osaka (meals out included); Hong Kong's, Singapore's, the Comunidad de Madrid's and
Berlin's food; Sydney's and Melbourne's food and non-alcoholic beverages (meals out included); and, because neither office
publishes a city index, the United Kingdom's and France's food for London and Paris.

An index measures how far prices moved, never their level: the cities are compared by the change in their own index,
2019 to 2025 and 2005 to 2025, as calendar-year averages of the months published (the Bureau did not collect October
2025, so 2025's U.S. averages are of eleven months). The current year is each city's latest month against the same
month a year before. The indexes are sample surveys of prices. The Bureau of Labor Statistics publishes sampling errors for its
indexes; they are not on file here and are not used. Instead one fixed rule decides when a difference is called
(``apart``): the two changes, as printed in whole percents, differ by more than two points. So the order of
cities is an observed order of published figures, and a numerically higher reading is called higher only when
it clears the rule.

What New York's plan for city-owned grocery stores promises is quoted from the Mayor's release and set against the Census
Bureau's measure of grocery stores' gross margin, the share of each sales dollar left after the cost of the goods.

Writes results.json, viz.json, charts.json, data.csv and build.json into output/articles/grocery_prices_in_big_cities/
and site/public/articles/grocery-prices-in-big-cities/, and copies this script there as analysis.py. Deterministic.
"""

from __future__ import annotations

import pandas as pd

from article_kit import Article, lines, r, strip
from nycdata import world_prices as P
from sparkylib.dates import MONTH_ABBR

SLUG = "grocery-prices-in-big-cities"
SEED = 20261125
FROM, TO = 2019, 2025       # the last year before the pandemic, and the last full year
LONG_FROM = 2005            # twenty years before the last full year
FIRST = 1990
CLOSE = 2                   # two changes are called different only when their printed whole percents differ by more than two
#: The city indexes that are groceries alone (food at home, or food without meals out); the other four include meals out.
GROCERY_ONLY = ["new_york", "chicago", "los_angeles", "hong_kong", "singapore", "madrid", "berlin"]
MAYOR_LATEST = "2026-06"    # June 2026, released in July: the month the Mayor's "since 2019" could reach
#: (key, label): New York first, then the cities with their own index, then the provinces and countries.
CITIES = [("new_york", "New York"), ("chicago", "Chicago"), ("los_angeles", "Los Angeles"), ("tokyo", "Tokyo"),
          ("osaka", "Osaka"), ("hong_kong", "Hong Kong"), ("singapore", "Singapore"), ("madrid", "Madrid region"),
          ("berlin", "Berlin"), ("sydney", "Sydney"), ("melbourne", "Melbourne"),
          ("toronto", "Toronto (Ontario's food)"), ("montreal", "Montreal (Quebec's food)"),
          ("london", "London (the UK's)"), ("paris", "Paris (France's)"), ("us", "United States")]
LABEL = dict(CITIES)
OWN_INDEX = ["chicago", "los_angeles", "tokyo", "osaka", "hong_kong", "singapore", "madrid", "berlin", "sydney", "melbourne"]
WIDER = ["toronto", "montreal", "london", "paris"]


def change(a: pd.DataFrame, y0: int, y1: int, col: str = "food") -> float | None:
    if y0 not in a.index or y1 not in a.index or pd.isna(a.at[y0, col]) or pd.isna(a.at[y1, col]):
        return None
    return 100 * (float(a.at[y1, col]) / float(a.at[y0, col]) - 1)


def apart(x: float, y: float) -> bool:
    """The rule for calling a difference, stated on the page: the two changes, as printed in whole percents, differ by
    more than two points. The offices' sampling errors are not used (the Bureau of Labor Statistics publishes them for
    its indexes; they are not on file here), so this is a fixed rule, not a margin."""
    return abs(round(x) - round(y)) > CLOSE


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()

    # ---- every city: food and all items, 2019 to 2025 and 2005 to 2025, and the latest month
    world, annuals = {}, {}
    for k, label in CITIES:
        a = P.annual(k).set_index("year")
        annuals[k] = a
        latest = P.latest_change(k)
        world[k] = {"label": label, "covers": P.CITIES[k][0], "area": P.CITIES[k][1], "publisher": P.CITIES[k][2],
                    "food_2019_2025_pct": r(change(a, FROM, TO), 4),
                    "all_2019_2025_pct": r(change(a, FROM, TO, "all_items"), 4) if change(a, FROM, TO, "all_items") is not None else None,
                    "food_2005_2025_pct": r(change(a, LONG_FROM, TO), 4) if change(a, LONG_FROM, TO) is not None else None,
                    "months_2025": int(a.at[TO, "months"]),
                    "latest": {"period": latest["period"], "food_pct": r(latest["food_pct"], 4),
                               "all_items_pct": r(latest["all_items_pct"], 4) if latest["all_items_pct"] is not None else None}}
        f, al = world[k]["food_2019_2025_pct"], world[k]["all_2019_2025_pct"]
        world[k]["food_minus_all_2019_2025"] = r(f - al, 4) if al is not None else None
    A.results["cities"] = world
    own = ["new_york"] + OWN_INDEX
    order = sorted(own, key=lambda k: -world[k]["food_2019_2025_pct"])
    order_grocery = sorted(GROCERY_ONLY, key=lambda k: -world[k]["food_2019_2025_pct"])
    order_all = sorted(world, key=lambda k: -world[k]["food_2019_2025_pct"])
    ny = world["new_york"]["food_2019_2025_pct"]
    A.results["order"] = {
        "food_2019_2025": order, "new_york_rank": order.index("new_york") + 1, "n_own_index": len(own),
        "grocery_only": order_grocery, "new_york_rank_grocery_only": order_grocery.index("new_york") + 1,
        "n_grocery_only": len(GROCERY_ONLY),
        "new_york_rank_all_rows": order_all.index("new_york") + 1, "n_rows": len(world),
        "higher_than_new_york": [k for k in OWN_INDEX if world[k]["food_2019_2025_pct"] > ny and apart(world[k]["food_2019_2025_pct"], ny)],
        "lower_than_new_york": [k for k in OWN_INDEX if world[k]["food_2019_2025_pct"] < ny and apart(world[k]["food_2019_2025_pct"], ny)],
        "close_to_new_york": [k for k in OWN_INDEX if not apart(world[k]["food_2019_2025_pct"], ny)],
        "food_outran_all_items": [k for k in own if world[k]["food_minus_all_2019_2025"] is not None
                                  and world[k]["food_2019_2025_pct"] > world[k]["all_2019_2025_pct"]
                                  and apart(world[k]["food_2019_2025_pct"], world[k]["all_2019_2025_pct"])],
        "rule": "two changes are called different only when their printed whole percents differ by more than two points"}
    o = A.results["order"]
    for key in ("higher_than_new_york", "lower_than_new_york", "close_to_new_york", "food_outran_all_items"):
        o[key + "_n"] = len(o[key])
    assert apart(world["us"]["food_2019_2025_pct"], ny) and world["us"]["food_2019_2025_pct"] > ny, \
        "the page says New York's rose less than the country's"
    assert o["higher_than_new_york"] == ["los_angeles", "madrid", "berlin"], o["higher_than_new_york"]
    assert o["lower_than_new_york"] == ["hong_kong", "singapore"], o["lower_than_new_york"]
    assert o["close_to_new_york"] == ["chicago", "tokyo", "osaka", "sydney", "melbourne"], o["close_to_new_york"]
    assert not apart(world["paris"]["food_2019_2025_pct"], ny) and apart(world["london"]["food_2019_2025_pct"], ny)
    assert o["new_york_rank_grocery_only"] == 5 and o["new_york_rank"] == 6 and o["new_york_rank_all_rows"] == 11, \
        (o["new_york_rank_grocery_only"], o["new_york_rank"], o["new_york_rank_all_rows"])
    assert "new_york" not in o["food_outran_all_items"], "the page says New York's groceries and all its prices rose about as much since 2019"

    # ---- New York over thirty-five years, and against the country
    nya, usa = annuals["new_york"], annuals["us"]
    A.results["new_york"] = {
        "food_1990_2025_pct": r(change(nya, FIRST, TO), 4), "all_1990_2025_pct": r(change(nya, FIRST, TO, "all_items"), 4),
        "us_food_1990_2025_pct": r(change(usa, FIRST, TO), 4),
        "food_2005_2025_pct": world["new_york"]["food_2005_2025_pct"], "us_food_2005_2025_pct": world["us"]["food_2005_2025_pct"],
        "food_2019_2025_pct": ny, "all_2019_2025_pct": world["new_york"]["all_2019_2025_pct"],
        "us_food_2019_2025_pct": world["us"]["food_2019_2025_pct"]}
    # the Mayor's "33% nationwide since 2019": the national index from 2019's average to the latest month, and New York's
    nym, usm = P.monthly("new_york").set_index("period"), P.monthly("us").set_index("period")
    last = MAYOR_LATEST         # the latest month the Bureau had published when the Mayor spoke (27 July 2026)
    base_us = usm.loc[[f"{FROM}-{m:02d}" for m in range(1, 13)], "food"].mean()
    base_ny = nym.loc[[f"{FROM}-{m:02d}" for m in range(1, 13)], "food"].mean()
    A.results["since_2019_to_latest"] = {"period": last, "us_pct": r(100 * (usm.at[last, "food"] / base_us - 1), 4),
                                         "new_york_pct": r(100 * (nym.at[last, "food"] / base_ny - 1), 4)}
    assert round(A.results["since_2019_to_latest"]["us_pct"]) == 33, "the page calls the Mayor's 33% true of the national index"
    # the same to the latest month on file, and how the gap between the country and New York has moved
    now_m = max(p for p in nym.index if pd.notna(nym.at[p, "food"]))
    def since(p: str) -> dict:
        us_, ny_ = 100 * (usm.at[p, "food"] / base_us - 1), 100 * (nym.at[p, "food"] / base_ny - 1)
        return {"period": p, "us_pct": r(us_, 4), "new_york_pct": r(ny_, 4), "gap_points": r(us_ - ny_, 4)}
    A.results["since_2019_to_now"] = since(now_m)
    A.results["since_2019_gap"] = {"2025_average": r(world["us"]["food_2019_2025_pct"] - ny, 4),
                                   MAYOR_LATEST: A.results["since_2019_to_latest"]["us_pct"] - A.results["since_2019_to_latest"]["new_york_pct"],
                                   now_m: A.results["since_2019_to_now"]["gap_points"]}
    A.results["since_2019_gap"][MAYOR_LATEST] = r(A.results["since_2019_gap"][MAYOR_LATEST], 4)
    assert A.results["since_2019_gap"][now_m] < A.results["since_2019_gap"]["2025_average"], "the page says the gap has narrowed"
    assert A.results["since_2019_to_now"]["new_york_pct"] < A.results["since_2019_to_now"]["us_pct"]
    # the Bureau collected no prices in October 2025: the 2019-2025 changes again on the eleven months both years have
    def eleven(m: pd.DataFrame) -> float:
        mm = [f"{{y}}-{mo:02d}" for mo in range(1, 13) if mo != 10]
        return 100 * (m.loc[[x.format(y=TO) for x in mm], "food"].mean() / m.loc[[x.format(y=FROM) for x in mm], "food"].mean() - 1)
    A.results["eleven_months"] = {"new_york_pct": r(eleven(nym), 4), "us_pct": r(eleven(usm), 4),
                                  "note": "2019 to 2025 on the eleven months collected in both years (October left out of each)"}
    whole = lambda v: f"{v:.0f}"      # noqa: E731  the printed whole percent, made from the unrounded value
    A.results["eleven_months"]["same_whole_percents"] = bool(
        whole(eleven(nym)) == whole(change(nya, FROM, TO)) and whole(eleven(usm)) == whole(change(usa, FROM, TO)))
    A.results["eleven_months"]["difference_points"] = {"new_york": r(eleven(nym) - change(nya, FROM, TO), 4),
                                                       "us": r(eleven(usm) - change(usa, FROM, TO), 4)}
    assert all(abs(v) < 0.2 for v in A.results["eleven_months"]["difference_points"].values()), \
        "the page says the missing October moves each change by under two-tenths of a point"
    # groceries against all prices in New York: the ratio of the two indexes, its low, and each stretch
    ratio = (nya["food"] / nya["all_items"]).dropna()
    ratio = ratio / ratio[FIRST]
    low = int(ratio.loc[FIRST:TO].idxmin())
    A.results["food_vs_all"] = {
        "low_year": low, "ratio_low": r(float(ratio[low]), 4), "ratio_2025": r(float(ratio[TO]), 4),
        "to_low": {"food_pct": r(change(nya, FIRST, low), 4), "all_pct": r(change(nya, FIRST, low, "all_items"), 4)},
        "since_low": {"food_pct": r(change(nya, low, TO), 4), "all_pct": r(change(nya, low, TO, "all_items"), 4)},
        "since_2019_called_different": bool(apart(ny, world["new_york"]["all_2019_2025_pct"]))}
    fva = A.results["food_vs_all"]
    assert fva["to_low"]["food_pct"] < fva["to_low"]["all_pct"] and fva["since_low"]["food_pct"] > fva["since_low"]["all_pct"], \
        "the page says groceries lagged all prices to the low year and have outrun them since"
    assert not fva["since_2019_called_different"]
    # the current year, month by month: New York and the country, each month against the same month a year before
    first_m, last_m = "2024-01", now_m
    cal = [f"{y}-{mo:02d}" for y in range(2024, int(last_m[:4]) + 1) for mo in range(1, 13)]
    months = [p for p in cal if first_m <= p <= last_m]
    yoy, two = {}, {}
    for k, m in (("new_york", nym), ("us", usm)):
        yoy[k], two[k] = {}, {}
        for p in months:
            before, before2 = f"{int(p[:4]) - 1}{p[4:]}", f"{int(p[:4]) - 2}{p[4:]}"
            ok = p in m.index and pd.notna(m.at[p, "food"])
            if ok and before in m.index and pd.notna(m.at[before, "food"]):
                yoy[k][p] = r(100 * (m.at[p, "food"] / m.at[before, "food"] - 1), 4)
            if ok and before2 in m.index and pd.notna(m.at[before2, "food"]):
                two[k][p] = r(100 * (m.at[p, "food"] / m.at[before2, "food"] - 1), 4)
    peak = max(yoy["new_york"], key=lambda p: yoy["new_york"][p])
    run = [p for p in sorted(yoy["new_york"]) if p >= "2025-07"]
    above = [p for p in run if yoy["new_york"][p] > yoy["us"][p]]
    last_yoy = max(yoy["new_york"])
    called = [p for p in run if apart(yoy["new_york"][p], yoy["us"][p])]
    gaps = {p: r(yoy["new_york"][p] - yoy["us"][p], 4) for p in run}
    A.results["now"] = {"latest": world["new_york"]["latest"], "us_latest": world["us"]["latest"],
                        "run": {"from": run[0], "to": run[-1], "readings": len(run), "new_york_above": len(above),
                                "called_by_the_rule": called, "gap_points": gaps,
                                "gap_2026_05": gaps["2026-05"], "gap_latest": gaps[run[-1]],
                                "gap_fell_every_month_since_2026_05": bool(all(
                                    gaps[q] < gaps[p_] for p_, q in zip([x for x in run if x >= "2026-05"],
                                                                        [x for x in run if x >= "2026-05"][1:])))},
                        "peak_month": peak, "peak_pct": yoy["new_york"][peak], "peak_us_pct": yoy["us"].get(peak),
                        "yoy": yoy, "two_year": two,
                        "months_since_2025_07": len(run), "months_new_york_above": len(above),
                        "two_year_latest": {"period": last_yoy, "new_york_pct": two["new_york"][last_yoy], "us_pct": two["us"][last_yoy]},
                        "latest_gap_points": r(yoy["new_york"][last_yoy] - yoy["us"][last_yoy], 4)}
    assert world["new_york"]["latest"]["period"] == last_yoy, "the latest change on a year is the last month with one"
    assert len(above) == len(run) == 14 and run[0] == "2025-07" and run[-1] == "2026-09", \
        f"the page says New York's reading was above the country's in all fourteen comparable months: {len(above)} of {len(run)}"
    assert called == ["2026-04"], f"the page says only April 2026's gap clears the rule: {called}"
    assert gaps[run[-1]] < gaps["2026-05"] and not A.results["now"]["run"]["gap_fell_every_month_since_2026_05"], \
        "the page says the gap was smaller in September than in May, having moved up and down between"
    A.latest(now_m, "The Bureau of Labor Statistics' food at home for the New York area to October 2026, against its 2019 "
             "average; the latest change on a year is September's (October 2025 was not collected, so October 2026 has none)")
    A.long_view(FIRST, TO, "Food at home and all items for the New York area, and food at home for the U.S. city average, "
                "yearly averages 1990-2025, with the months of 2026")

    # ---- the plan: a 30% discount against a grocer's whole gross margin
    margin = P.grocery_gross_margin()
    A.results["margin"] = {"latest_year": max(margin), "latest_pct": margin[max(margin)],
                           "range_1993_2022": [min(margin.values()), max(margin.values())]}
    hist = {key: Q.quote(src, fname, needle) for key, src, fname, needle in HISTORY}
    A.results["history"] = {"quotes": hist, "discount_pct": 30, "bill_cut_pct": 15, "monthly_saving": 90, "capital_millions": 70,
                            "mayor_since_2019_pct": 33, "comptroller_april_pct": 5.9, "comptroller_may_pct": 4.0,
                            "comptroller_us_may_pct": 2.7, "thanksgiving_dinner": 58.63}
    A.results["margin"]["discount_minus_margin_points"] = r(A.results["history"]["discount_pct"] - A.results["margin"]["latest_pct"], 1)
    assert abs(A.results["margin"]["discount_minus_margin_points"]) <= 3, "the page says the discount is about the size of the margin"

    # Australia changed from a quarterly to a monthly index in 2025 (the two are chained here): the same comparison on
    # 2019 to 2024, the quarterly series alone, to see that the reading does not rest on the splice
    pre = {k: change(annuals[k], FROM, TO - 1) for k in ("new_york", "sydney", "melbourne")}
    A.results["australia_before_the_change"] = {
        "period": f"{FROM} to {TO - 1}", **{k: r(v, 4) for k, v in pre.items()},
        "within_the_rule_of_new_york": {k: bool(not apart(pre[k], pre["new_york"])) for k in ("sydney", "melbourne")}}
    assert all(A.results["australia_before_the_change"]["within_the_rule_of_new_york"].values()), \
        "the page says Sydney's and Melbourne's rises are within two points of New York's before the change of index too"

    # ---- printed figures (each made from its value, so the prose cannot drift from the numbers)
    for path in ("new_york.food_2019_2025_pct", "new_york.us_food_2019_2025_pct", "new_york.all_2019_2025_pct",
                 "new_york.food_1990_2025_pct", "new_york.all_1990_2025_pct", "since_2019_to_latest.us_pct",
                 "since_2019_to_latest.new_york_pct", "since_2019_to_now.us_pct", "since_2019_to_now.new_york_pct",
                 "now.two_year_latest.new_york_pct", "now.two_year_latest.us_pct"):
        A.printed(path, fmt="pct0")
    for path in ("now.latest.food_pct", "now.us_latest.food_pct", "margin.latest_pct"):
        A.printed(path, fmt="pct1")
    for k in ("berlin", "madrid", "hong_kong", "singapore", "tokyo", "osaka", "sydney", "melbourne", "chicago", "los_angeles",
              "london", "paris"):
        A.printed(f"cities.{k}.food_2019_2025_pct", fmt="pct0")
    A.printed("cities.tokyo.all_2019_2025_pct", fmt="pct0")
    A.printed("food_vs_all.low_year", str(A.results["food_vs_all"]["low_year"]))
    A.printed("food_vs_all.since_low.food_pct", fmt="pct0")
    A.printed("food_vs_all.since_low.all_pct", fmt="pct0")
    A.printed("now.months_new_york_above", fmt="int")
    A.printed("order.new_york_rank_grocery_only", fmt="int")
    A.printed("order.n_grocery_only", fmt="int")
    h = A.results["history"]
    h["implied_bill_dollars"] = round(h["monthly_saving"] / (h["bill_cut_pct"] / 100))
    h["thanksgiving_rise_pct"] = 6
    A.printed("history.implied_bill_dollars", f"${h['implied_bill_dollars']:,}")
    A.printed("history.monthly_saving", "$90")
    A.printed("history.capital_millions", "$70")
    A.printed("history.thanksgiving_dinner", "$58.63")
    A.printed("history.thanksgiving_rise_pct", "6%")
    A.printed("history.discount_pct", "30%")
    A.printed("history.bill_cut_pct", "15")
    A.printed("history.comptroller_april_pct", "5.9%")
    A.printed("history.comptroller_may_pct", "4.0%")
    A.printed("history.comptroller_us_may_pct", "2.7%")
    A.results["margin"]["low_pct"], A.results["margin"]["high_pct"] = A.results["margin"]["range_1993_2022"]
    A.printed("margin.low_pct", fmt="pct1")
    A.printed("margin.high_pct", fmt="pct1")
    h["since_year"] = FROM
    A.printed("history.since_year", str(FROM))

    # ---- charts
    years = list(range(FIRST, TO + 1))
    ix = lambda a, col: {str(y): r(100 * float(a.at[y, col]) / float(a.at[FIRST, col]), 1) for y in years if y in a.index}   # noqa: E731
    A.chart("long_view", lines(
        title="New York's groceries fell behind its other prices until the mid-2000s and have risen faster since; they track the country's",
        subtitle="Consumer price index, yearly averages, 1990 = 100: food at home and all items in the New York area, food at home in the U.S.",
        x=[[str(y), str(y)] for y in years],
        series=[["ny_food", "Food at home, New York area", "NY food"], ["ny_all", "All items, New York area", "NY all items"],
                ["us_food", "Food at home, United States", "US food"]],
        cells={"": {"ny_food": ix(nya, "food"), "ny_all": ix(nya, "all_items"), "us_food": ix(usa, "food")}},
        format="num", axis="Index, 1990 = 100", x_ticks=[str(y) for y in years if y % 5 == 0 or y == TO], zero=False,
        note="The Bureau of Labor Statistics' consumer price index for all urban consumers, not seasonally adjusted, averaged "
             "over each calendar year. The New York area is the New York-Newark-Jersey City metropolitan area. October 2025 was "
             "not collected, so 2025's averages are of eleven months.",
        provenance="U.S. Bureau of Labor Statistics"))

    # months in words: the template spaces labels that start with a year by that year, which would stack a year's months
    shown = [p for p in months if p <= last_yoy]
    in_words = {p: f"{MONTH_ABBR[int(p[5:]) - 1]} {p[:4]}" for p in shown}
    A.chart("this_year", lines(
        title="New York's yearly rise in grocery prices has read above the country's in fourteen comparable months running",
        subtitle="Food at home, change on the same month a year before, New York area and United States, January 2024 to September 2026",
        x=[[p, in_words[p]] for p in shown],
        series=[["new_york", "New York area", "New York"], ["us", "United States", "U.S."]],
        cells={"": {k: {p: yoy[k].get(p) for p in shown} for k in ("new_york", "us")}},
        format="dec1", axis="Change on a year, %", x_axis="Month", zero=False,
        x_ticks=[p for p in shown if p[5:] in ("01", "07")],
        # July's tick says "Jul" alone: six full labels stand edge to edge on a phone
        x_tick_labels={p: (in_words[p] if p[5:] == "01" else "Jul") for p in shown if p[5:] in ("01", "07")},
        note="Each month against the same month a year before. October 2025 was not collected, so the lines break there and "
             "October 2026 has no change on a year. A change on a year depends on the month it starts from: April 2026's "
             "high follows a low April 2025. These are survey estimates; only April 2026's gap is large enough for the rule "
             "used here to call a difference.",
        provenance="U.S. Bureau of Labor Statistics"))

    srt = sorted([k for k, _ in CITIES], key=lambda k: -world[k]["food_2019_2025_pct"])
    A.chart("world_2019", strip(
        title="Since 2019, New York's grocery prices rose less than Berlin's, the Madrid region's or the UK's, and more than Hong Kong's or Singapore's",
        subtitle="Change in each office's food price index and all-items index, 2019 to 2025 (yearly averages)",
        x=[["all", "All items"], ["food", "Food"]],     # food last, so the figure at the right is the food change
        series=[[k, LABEL[k], LABEL[k]] for k in srt],
        cells={"": {k: {"food": world[k]["food_2019_2025_pct"], "all": world[k]["all_2019_2025_pct"]} for k in srt}},
        format="chg", axis="Change, 2019 to 2025", order="series",
        note="Food is food at home in the U.S. cities, food purchased from stores in Ontario and Quebec, food excluding meals "
             "out in Hong Kong, Singapore, the Madrid region and Berlin, and food including meals out in Tokyo, Osaka, Sydney "
             "and Melbourne. Toronto's and Montreal's food is their province's, London's and Paris's their country's. Berlin's "
             "all-items is its Land's yearly average.",
        provenance="BLS; Statistics Canada; Statistics Bureau of Japan; C&SD; SingStat; INE; Amt für Statistik Berlin-Brandenburg; "
                   "ABS; ONS; INSEE"))

    srt_long = sorted([k for k, _ in CITIES if world[k]["food_2005_2025_pct"] is not None], key=lambda k: -world[k]["food_2005_2025_pct"])
    A.chart("world_long", strip(
        title="Over twenty years New York's grocery prices rose about two-thirds, near the middle of sixteen places",
        subtitle="Change in each office's food price index, 2005 to 2025 (yearly averages)",
        x=[["food", "2005 to 2025"]],
        series=[[k, LABEL[k], LABEL[k]] for k in srt_long],
        cells={"": {k: {"food": world[k]["food_2005_2025_pct"]} for k in srt_long}},
        format="chg", axis="Change, 2005 to 2025", order="series",
        note="As in the chart above. Hong Kong's index starts in 2005, the Madrid region's in 2002.",
        provenance="BLS; Statistics Canada; Statistics Bureau of Japan; C&SD; SingStat; INE; Amt für Statistik Berlin-Brandenburg; "
                   "ABS; ONS; INSEE"))

    rows = []
    for k, label in CITIES:
        for y, x in annuals[k].iterrows():
            rows.append({"place": label, "food_index_covers": P.CITIES[k][0], "area": P.CITIES[k][1], "year": int(y),
                         "food_index_yearly_average": r(float(x["food"]), 3) if pd.notna(x["food"]) else None,
                         "all_items_yearly_average": r(float(x["all_items"]), 3) if pd.notna(x["all_items"]) else None,
                         "months": int(x["months"]), "publisher": P.CITIES[k][2]})
    A.write(data=pd.DataFrame(rows))
    print(f"{SLUG}: wrote {A.out}")
    return 0


#: What is said about grocery prices, and what New York's plan promises: (key, source id, saved file, needle).
HISTORY = [
    ("mayor_33", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "Grocery costs have risen 33% nationwide since 2019"),
    ("mayor_30", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "a core basket of everyday groceries will be 30 percent cheaper at the five new municipal grocery stores"),
    ("mayor_15", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "Combined, the savings are projected to cut New Yorkers' average grocery bill by 15 percent, about $90 a month"),
    ("mayor_basket", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "The basket will include all fresh produce, meat and seafood, along with roughly 20 additional categories of pantry staples, dairy and refrigerated goods"),
    ("mayor_operator", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "The selected operator will be responsible for day-to-day store operations"),
    ("mayor_70m", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "The Mayor has allocated $70 million in the capital budget"),
    ("mayor_first", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "The first grocery store will open by the end of 2027 at Hunts Point in the Bronx"),
    ("mayor_prices", "nyc_mayor_grocery_discount_2026_07", "nyc_mayor_grocery_discount_2026_07.html",
     "prices for core items locked in monthly and updated periodically to reflect market conditions"),
    ("comptroller_may", "nyc_comptroller_newsletter_114_2026_06", "nyc_comptroller_newsletter_114_2026_06.html",
     "Local-area prices for food at home (groceries) decelerated in May"),
    ("comptroller_us", "nyc_comptroller_newsletter_114_2026_06", "nyc_comptroller_newsletter_114_2026_06.html",
     "but still well above the nationwide rise of 2.7%"),
    ("afbf_dinner", "afbf_thanksgiving_survey_2026", "afbf_thanksgiving_survey_2026.html",
     "the cost of a Thanksgiving dinner for ten people is going up. It will be $58.63"),
]


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