"""New York's school rolls against eleven other big cities', 1994-95 to 2026-27: the analysis behind a SparkyData article.

    py src/build_article.py school-rolls-in-big-cities

New York's counts are the State Education Department's (card ``world_city_schools``, loader
``nycdata.world_schools``): the City's district schools by grade from 1994-95, and its charter schools beside them
from 2011-12, on BEDS day each October; private schools and children taught at home from the State's files; births
to city residents from the State's file (nycdata.world_fertility).

The question is how much of the fall is fewer births. New York's schools take children by calendar year of birth, so
each grade is set against the births of its own birth year: kindergarten in autumn F against births in F - 5, grade g
against births in F - 5 - g. The elementary grades (kindergarten to grade 5) are then set against the six birth years
in them, from 2014-15 (the first school year whose six birth years are all on file). The change in students splits,
as arithmetic, into the part the births alone would give (the students the base year's ratio would yield from the
latest births) and the rest (fewer students per birth). That ratio is students over births years earlier, not a share
of the children living in the city now: it moves with families moving in and out since the births, with the kind of
school chosen and with the grade a child is placed in, and its numerator counts every child in the grade, born here
or arrived since. So it cannot say who left or came, or where any child went. The other kinds of school are then
counted on one set of grades and years (kindergarten to grade 6, the band the home-instruction file uses, 2017-18 to
2025-26, the years the private-school files cover), against the seven birth years in those grades: these are changes
in each kind's count, not children followed.
The Census Bureau's estimates of the city's children are a cross-check, never spliced in.

Every other city's count is its own education or statistics office's (``W.CITIES``). Nine cities have a count of
their primary grades from age five or six and are ordered together (``PRIMARY``): New York's kindergarten to grade 5,
London's Years 1 to 6, Paris's écoles élémentaires, grades 1 to 6 in Berlin, Tokyo, Hong Kong, Singapore and the
Madrid region, kindergarten to year 6 in Sydney. Three publish only a broader count and are shown beside them, never
ranked with them (``BROADER``): Toronto's runs to grade 8, Vienna's is its compulsory schools, and Chicago's is all
grades with pre-K, which is set beside New York's all-grades count. Each city is compared with itself, 2015-16 (the
first year every series covers) to its latest year.

The counts are administrative head counts, not samples: the comparisons are observed changes in published counts.
The current year is the Education Department's preliminary count of its own district schools for 2026-27 as reported
on 16 November 2026 (the Department has not posted the file); the latest counts on file are the State's for 2025-26.
What each city did when its rolls fell comes from its own documents, quoted, never as a cause.

Writes results.json, viz.json, charts.json, data.csv and build.json into output/articles/school_rolls_in_big_cities/
and site/public/articles/school-rolls-in-big-cities/, and copies this script there as analysis.py. Deterministic: no
sampling.
"""

from __future__ import annotations

import re

import pandas as pd

from article_kit import Article, lines, r, strip
from nycdata import popest, world_schools as W

SLUG = "school-rolls-in-big-cities"
SEED = 20261123
BASE = 2016            # 2015-16, the first school year every city's series covers (London's and Hong Kong's start there)
COMPTROLLER = (2021, 2026)   # 2020-21 to 2025-26, the Comptroller's window for the split by kind of school
PRE_PANDEMIC = (2012, 2020)  # the kindergarten classes of 2011-12 to 2019-20
THRESHOLD = 5                # a change within 5% either way is called level
CURRENT = 2027               # the current school year, 2026-27, filed by the year it ends
CURRENT_CALENDAR = 2026      # the current school year where it is the calendar year
#: The cities, New York first: (key, label). New York here is its kindergarten to grade 5.
CITIES = [("new_york", "New York"), ("london", "London"), ("paris", "Paris"), ("berlin", "Berlin"),
          ("vienna", "Vienna"), ("madrid", "Madrid region"), ("toronto", "Toronto"), ("chicago", "Chicago"),
          ("tokyo", "Tokyo"), ("hong_kong", "Hong Kong"), ("singapore", "Singapore"), ("sydney", "Sydney")]
LABEL = dict(CITIES)
#: The cities whose count is of their primary grades, ordered together; and those with only a broader count.
PRIMARY = ["new_york", "london", "paris", "berlin", "madrid", "tokyo", "hong_kong", "singapore", "sydney"]
BROADER = ["toronto", "vienna", "chicago"]
OTHERS = [k for k in PRIMARY if k != "new_york"]
#: The same cities on a wider count, for the sensitivity the page states: all grades, or with the pre-school classes.
WIDER = [("new_york_k12", "New York, all grades"), ("london_all", "London, with reception and nursery"),
         ("paris_all", "Paris, with the maternelles")]
#: The European and American cities, for the Financial Times's sentence about "cities in Europe and the US".
EUROPE_US = ["new_york", "chicago", "london", "paris", "madrid", "berlin", "vienna"]
WORLD_LINES = ["new_york", "london", "paris", "hong_kong", "berlin", "tokyo"]

#: Cities whose school year is the calendar year, labelled by the year itself.
CALENDAR = {"singapore", "sydney"}


def sy(spring: int, city: str | None = None) -> str:
    """A school year by its spring: 2026 -> '2025-26' (a calendar school year by its year: 2024 -> '2024')."""
    return str(spring) if city in CALENDAR else f"{spring - 1}-{spring % 100:02d}"


def pct_from(a: float, b: float) -> float:
    return 100 * (a / b - 1)


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: the State's district series since 1994-95, and district and charter schools since 2011-12
    d = W.nyc_districts().set_index("year")
    s = W.nyc_schools().set_index("year")
    peak = int(d["k12"].idxmax())
    last = int(d.index.max())
    A.results["new_york"] = {
        "district": {"first": {"year": int(d.index.min()), "k12": int(d["k12"].iloc[0])},
                     "peak": {"year": peak, "school_year": sy(peak), "k12": int(d.at[peak, "k12"])},
                     "last": {"year": last, "school_year": sy(last), "k12": int(d.at[last, "k12"])},
                     "fall_from_peak": int(d.at[peak, "k12"] - d.at[last, "k12"]),
                     "fall_from_peak_pct": r(pct_from(d.at[last, "k12"], d.at[peak, "k12"]), 2)},
        "public": {"first": {"year": int(s.index.min()), "k12": int(s["public_k12"].iloc[0])},
                   "base": {"year": BASE, "k12": int(s.at[BASE, "public_k12"])},
                   "last": {"year": last, "k12": int(s.at[last, "public_k12"])},
                   "k12": {str(y): int(v) for y, v in s["public_k12"].items()},
                   "change_since_base_pct": r(pct_from(s.at[last, "public_k12"], s.at[BASE, "public_k12"]), 2),
                   "charter_first": int(s["charter_k12"].iloc[0]), "charter_last": int(s.at[last, "charter_k12"]),
                   "charter_share_last_pct": r(100 * s.at[last, "charter_k12"] / s.at[last, "public_k12"], 2)},
    }
    assert peak == 1999, f"the page says the district schools peaked in 1998-99: {peak}"
    # the per-resident reading of the long comparison: district students per 100 residents on 1 July of the autumn counted
    city_pop = popest.july_population_since_1990().groupby("year")["pop"].sum()
    A.results["new_york"]["district"]["per_100_residents"] = {
        "peak": r(100 * d.at[peak, "k12"] / city_pop[peak - 1], 2), "last": r(100 * d.at[last, "k12"] / city_pop[last - 1], 2),
        "residents_peak": int(city_pop[peak - 1]), "residents_last": int(city_pop[last - 1])}
    pub = s["public_k12"]
    assert pub[2023] < pub[2024] < pub[2025] and pub[2026] < pub[2025], \
        "the page says the public schools' count rose in 2023-24 and 2024-25 and fell in 2025-26"

    # ---- the test: each grade against the births of its birth year; kindergarten to grade 5 against six birth years
    kb = W.kindergarten_per_birth().set_index("year")
    pre = kb.loc[PRE_PANDEMIC[0]:PRE_PANDEMIC[1], "per_birth"]
    low_year = int(kb["per_birth"].idxmin())
    k_from, k_to = 2015, last           # the largest public kindergarten (2014-15) to the latest
    below = [int(y) for y, v in kb["per_birth"].items() if y > PRE_PANDEMIC[1] and v < pre.min()]
    A.results["kindergarten"] = {
        "per_birth": {str(y): r(float(v), 4) for y, v in kb["per_birth"].items()},
        "pre_pandemic_mean": r(float(pre.mean()), 4), "pre_pandemic_low": r(float(pre.min()), 4),
        "pre_pandemic_high": r(float(pre.max()), 4),
        "low": {"year": low_year, "school_year": sy(low_year), "per_birth": r(float(kb.at[low_year, "per_birth"]), 4)},
        "last": {"year": last, "school_year": sy(last), "per_birth": r(float(kb.at[last, "per_birth"]), 4),
                 "public_k": int(kb.at[last, "public_k"]), "births": int(kb.at[last, "births"]),
                 "birth_year": int(kb.at[last, "birth_year"])},
        "first": {"year": int(kb.index.min()), "per_birth": r(float(kb["per_birth"].iloc[0]), 4)},
        "below_pre_pandemic_range": below, "n_below": len(below),
        "public_k_from": {"year": k_from, "k": int(kb.at[k_from, "public_k"]), "births": int(kb.at[k_from, "births"]),
                          "birth_year": int(kb.at[k_from, "birth_year"])},
        "public_k_change_pct": r(pct_from(kb.at[k_to, "public_k"], kb.at[k_from, "public_k"]), 2),
        "births_change_pct": r(pct_from(kb.at[k_to, "births"], kb.at[k_from, "births"]), 2),
    }
    assert int(s["public_k"].idxmax()) == k_from, "the page says 2014-15 had the largest public kindergarten"
    assert below == [2021, 2022, 2023, 2024, 2025], f"the page says five classes entered below the earlier range: {below}"
    assert pre.min() <= kb.at[last, "per_birth"] <= pre.max(), \
        "the page says the latest kindergarten per birth is inside its pre-pandemic range"

    el = W.elementary_per_birth().set_index("year")
    e0, e1 = el.loc[BASE], el.loc[last]
    expected = e0["per_birth"] * e1["births"]            # the students the base year's ratio would give from the latest births
    fall = float(e0["students"] - e1["students"])
    births_part, ratio_part = float(e0["students"] - expected), float(expected - e1["students"])
    e_low = int(el["per_birth"].idxmin())
    A.results["elementary"] = {
        "grades": "kindergarten to grade 5, district and charter schools",
        "per_birth": {str(y): r(float(v), 4) for y, v in el["per_birth"].items()},
        "base": {"year": BASE, "school_year": sy(BASE), "students": int(e0["students"]), "births": int(e0["births"]),
                 "per_birth": r(float(e0["per_birth"]), 4)},
        "last": {"year": last, "school_year": sy(last), "students": int(e1["students"]), "births": int(e1["births"]),
                 "per_birth": r(float(e1["per_birth"]), 4)},
        "pre_pandemic": {"year": 2020, "per_birth": r(float(el.at[2020, "per_birth"]), 4)},
        "low": {"year": e_low, "school_year": sy(e_low), "per_birth": r(float(el.at[e_low, "per_birth"]), 4)},
        "students_change_pct": r(pct_from(e1["students"], e0["students"]), 2),
        "births_change_pct": r(pct_from(e1["births"], e0["births"]), 2),
        "per_birth_change_pct": r(pct_from(e1["per_birth"], e0["per_birth"]), 2),
        "fall": int(fall), "expected_at_base_ratio": int(round(expected)),
        "births_part": int(round(births_part)), "ratio_part": int(round(ratio_part)),
        "births_share_pct": r(100 * births_part / fall, 1), "ratio_share_pct": r(100 * ratio_part / fall, 1),
    }
    assert 45 <= 100 * births_part / fall <= 60, "the page says births account for about half of the elementary fall"
    # the same split from other base years: 2015-16 is the year the ratio stood highest, so the births' share is also
    # given from the year before it and from the last school year before the pandemic
    other_bases = {}
    for y0 in (2015, 2020):
        b0 = el.loc[y0]
        exp = b0["per_birth"] * e1["births"]
        f0 = float(b0["students"] - e1["students"])
        other_bases[str(y0)] = {"school_year": sy(y0), "students": int(b0["students"]), "per_birth": r(float(b0["per_birth"]), 4),
                                "fall": int(f0), "births_part": int(round(float(b0["students"] - exp))),
                                "births_share_pct": r(100 * float(b0["students"] - exp) / f0, 1)}
    A.results["elementary"]["other_bases"] = other_bases
    assert int(el["per_birth"].idxmax()) == BASE, "the page says the ratio stood highest in 2015-16"
    assert all(45 <= v["births_share_pct"] <= 70 for v in other_bases.values()), other_bases
    assert e_low in (2022, 2023), "the page says the ratio was lowest in the pandemic years"
    assert el.at[last, "per_birth"] > el.at[e_low, "per_birth"], "the page says the ratio has come part of the way back"

    gp = W.grades_per_birth()
    by_grade = {str(y): {str(int(g)): r(float(v), 4) for g, v in gp[gp["year"] == y].set_index("grade")["per_birth"].items()}
                for y in (BASE, 2020, last)}
    A.results["grades"] = {"per_birth": by_grade,
                           "grade_5": {"2020": by_grade["2020"]["5"], str(last): by_grade[str(last)]["5"]}}
    older = [g for g in range(1, 9) if by_grade[str(last)][str(g)] < by_grade["2020"][str(g)] - 0.02]
    A.results["grades"]["below_2020_by_more_than_0.02"] = older
    assert older == list(range(1, 9)), f"the page says every grade from 1 to 8 holds fewer children per birth than in 2019-20: {older}"

    # ---- where the others went: the change by kind of school, 2020-21 to 2025-26 (the Comptroller's window)
    npub = W.nyc_nonpublic().set_index("year")
    n = npub["k12"]
    h = W.nyc_home().set_index("year")["children"]
    a, b = COMPTROLLER
    split = {"district": int(s.at[b, "district_k12"] - s.at[a, "district_k12"]),
             "charter": int(s.at[b, "charter_k12"] - s.at[a, "charter_k12"]),
             "private": int(n[b] - n[a]), "home": int(h[b] - h[a])}
    split["all"] = sum(split.values())
    split["other_kinds"] = split["charter"] + split["private"] + split["home"]
    split["gained"] = split["charter"] + split["home"]          # the two kinds that grew, before private schools' loss
    A.results["split"] = {"from": sy(a), "to": sy(b), **split,
                          "gained_share_of_district_loss_pct": r(100 * split["gained"] / -split["district"], 2),
                          "other_kinds_share_of_district_loss_pct": r(100 * split["other_kinds"] / -split["district"], 2),
                          "private_k5": {"first": {"year": int(npub.index.min()), "k5": int(npub["k5"].iloc[0])},
                                         "last": {"year": last, "k5": int(npub.at[last, "k5"])},
                                         "change_pct": r(pct_from(npub.at[last, "k5"], npub["k5"].iloc[0]), 2)}}
    assert split["district"] < 0 < split["charter"] and split["private"] < 0 < split["home"]
    assert 0.1 < split["gained"] / -split["district"] < 0.2, "the page says charter and home schooling gained about a sixth of the district loss"
    assert npub.at[last, "k5"] < npub["k5"].iloc[0], "the page says private schools' elementary grades shrank too"

    # ---- one set of grades and years for every kind of school: kindergarten to grade 6 (the band the home-instruction
    # file uses), 2017-18 (the private-school files' first year) to 2025-26, against the seven birth years in those grades
    gr = W.nyc_grades()
    k6 = gr[gr["grade"] <= 6].groupby("year")[["district", "charter"]].sum()
    hk6 = W.nyc_home().set_index("year")["k6"]
    el7 = W.elementary_per_birth(6).set_index("year")
    m0, m1 = int(npub.index.min()), last
    kinds = {"district": (int(k6.at[m0, "district"]), int(k6.at[m1, "district"])),
             "charter": (int(k6.at[m0, "charter"]), int(k6.at[m1, "charter"])),
             "private": (int(npub.at[m0, "k6"]), int(npub.at[m1, "k6"])),
             "home": (int(hk6[m0]), int(hk6[m1]))}
    all0, all1 = sum(v[0] for v in kinds.values()), sum(v[1] for v in kinds.values())
    A.results["matched"] = {
        "grades": "kindergarten to grade 6, every kind of school", "from": sy(m0), "to": sy(m1), "years": m1 - m0,
        **{k: {"first": v[0], "last": v[1], "change": v[1] - v[0]} for k, v in kinds.items()},
        "births": {"first": int(el7.at[m0, "births"]), "last": int(el7.at[m1, "births"])},
        "all_kinds": {"first": all0, "last": all1, "change": all1 - all0, "change_pct": r(pct_from(all1, all0), 2),
                      "per_birth_first": r(all0 / float(el7.at[m0, "births"]), 4),
                      "per_birth_last": r(all1 / float(el7.at[m1, "births"]), 4)},
        "gained": (kinds["charter"][1] - kinds["charter"][0]) + (kinds["home"][1] - kinds["home"][0]),
        "births_change_pct": r(pct_from(el7.at[m1, "births"], el7.at[m0, "births"]), 2),
    }
    mt = A.results["matched"]
    mt["gained_share_of_district_loss_pct"] = r(100 * mt["gained"] / -mt["district"]["change"], 2)
    assert int(el7.at[m0, "students"]) == kinds["district"][0] + kinds["charter"][0], "the public grades and their births are one band"
    assert mt["district"]["change"] < 0 < mt["charter"]["change"] and mt["private"]["change"] < 0 < mt["home"]["change"]
    assert mt["all_kinds"]["per_birth_last"] < mt["all_kinds"]["per_birth_first"], \
        "the page says every kind of school together holds fewer students per birth than eight years ago"
    assert mt["all_kinds"]["change_pct"] < mt["births_change_pct"], "the page says all kinds fell by more than the births"
    ung = gr.groupby("year")["ungraded"].first()
    A.results["ungraded"] = {sy(BASE): int(ung[BASE]), sy(last): int(ung[last])}

    # ---- a cross-check that is not a school count: the Census Bureau's estimates of the city's children
    ca = W.nyc_school_age().set_index("year")
    g = W.nyc_grades()
    k8 = g[g["grade"] <= 8].groupby("year")["students"].sum()
    A.results["census"] = {
        "age_5_13": {"2015": int(ca.at[2015, "age_5_13"]), "2025": int(ca.at[2025, "age_5_13"]),
                     "change_pct": r(pct_from(ca.at[2025, "age_5_13"], ca.at[2015, "age_5_13"]), 2)},
        "public_k8": {sy(BASE): int(k8[BASE]), sy(last): int(k8[last]), "change_pct": r(pct_from(k8[last], k8[BASE]), 2)},
        "note": "1 July estimates of residents aged 5 to 13 (intercensal 2010-2020, then Vintage 2025) against the public "
                "schools' kindergarten to grade 8 the following October; estimates, not counts",
    }
    assert A.results["census"]["age_5_13"]["change_pct"] > A.results["census"]["public_k8"]["change_pct"], \
        "the page says the estimates fell less than the school count"

    births = W.nyc_births().set_index("year")["births"]
    A.results["births"] = {"2020": int(births[2020]), "2023": int(births[2023]),
                           "after_2020": {str(y): int(births[y]) for y in (2021, 2022, 2023)}}
    assert all(births[y] < births[2020] for y in (2021, 2022, 2023)), "the page says each later year had fewer births than 2020"

    # ---- the other cities: each against itself, 2015-16 to its latest year, on its primary grades
    def city(k: str, label: str) -> dict:
        t = W.pupils(k).set_index("year")["pupils"]
        y0, y1 = BASE, int(t.index.max())
        return {"label": label, "covers": W.CITIES[k][0], "publisher": W.CITIES[k][1],
                "first_year": int(t.index.min()), "first_school_year": sy(int(t.index.min()), k),
                "base": int(t[y0]), "latest_year": y1, "latest_school_year": sy(y1, k), "latest": int(t[y1]),
                "years_since_base": y1 - y0, "change_pct": r(pct_from(t[y1], t[y0]), 2)}
    world = {k: city(k, label) for k, label in CITIES}
    A.results["cities"] = world
    A.results["wider"] = {k: city(k, label) for k, label in WIDER}
    order = sorted(PRIMARY, key=lambda k: world[k]["change_pct"])
    fell = [k for k in order if world[k]["change_pct"] <= -THRESHOLD]
    rose = [k for k in order if world[k]["change_pct"] >= THRESHOLD]
    eu_us_fell = [k for k in EUROPE_US if world[k]["change_pct"] <= -THRESHOLD]
    eu_us_down = [k for k in EUROPE_US if world[k]["change_pct"] < 0]
    A.results["order"] = {"primary": PRIMARY, "broader": BROADER, "change": order, "new_york_rank": order.index("new_york") + 1,
                          "n_primary": len(PRIMARY), "n_other_primary": len(OTHERS),
                          "fell_5pct": fell, "rose_5pct": rose, "within_5pct": [k for k in order if k not in fell + rose],
                          "fell_more_than_new_york": [k for k in OTHERS if world[k]["change_pct"] < world["new_york"]["change_pct"]],
                          "europe_us": EUROPE_US, "europe_us_fell_5pct": eu_us_fell, "europe_us_fell_at_all": eu_us_down,
                          "london_share_of_new_york": r(world["london"]["change_pct"] / world["new_york"]["change_pct"], 3)}
    for key in ("fell_5pct", "rose_5pct", "within_5pct", "fell_more_than_new_york", "europe_us", "europe_us_fell_5pct"):
        A.results["order"][key + "_n"] = len(A.results["order"][key])
    assert len(OTHERS) == 8, "the page says eight other cities count their primary grades"
    assert rose == ["berlin"], f"the page says Berlin's is the only primary count that rose by more than 5%: {rose}"
    assert world["vienna"]["change_pct"] >= THRESHOLD, "the page says Vienna's broader count grew too"
    assert A.results["order"]["fell_more_than_new_york"] == ["paris"], "the page says only Paris fell more than New York"
    assert world["london"]["change_pct"] / world["new_york"]["change_pct"] < 0.5, "the page says London fell less than half as much"
    assert set(fell) == {"paris", "new_york", "hong_kong", "london"}, fell
    assert set(A.results["order"]["within_5pct"]) == {"madrid", "sydney", "singapore", "tokyo"}, A.results["order"]["within_5pct"]
    assert abs(world["toronto"]["change_pct"]) < THRESHOLD and world["chicago"]["change_pct"] <= -THRESHOLD
    assert set(eu_us_fell) == {"new_york", "chicago", "london", "paris"} and set(eu_us_down) == set(eu_us_fell) | {"madrid"}, eu_us_down
    ts = W.toronto_suppressed()
    A.results["toronto_suppressed"] = {"cells": int(ts["suppressed"].sum()), "years": int(len(ts)),
                                       "at_most_pupils_in_a_year": int(ts["at_most"].max())}
    assert ts["at_most"].max() <= 18, "the page says Toronto's suppressed cells are at most two schools a year"
    import json as _json
    paris_rows = {int(x["rentree_scolaire"][:4]) + 1: x for x in _json.loads(W.PARIS.read_text(encoding="utf-8"))["results"]
                  if x["secteur"] == "PUBLIC"}
    with_ulis = lambda y: paris_rows[y]["elem"] + paris_rows[y]["ulis"]
    A.results["paris_with_ulis"] = {"base": int(with_ulis(BASE)), "latest": int(with_ulis(world["paris"]["latest_year"])),
                                    "change_pct": r(pct_from(with_ulis(world["paris"]["latest_year"]), with_ulis(BASE)), 2)}
    assert round(A.results["paris_with_ulis"]["change_pct"]) == round(world["paris"]["change_pct"]), \
        "the page says Paris's fall is the same with the ULIS classes"
    A.results["tokyo_public"] = {str(k): v for k, v in W.tokyo_public_2026().items()}
    A.results["chicago_2026_27"] = W.chicago_2026_27()

    # ---- carried to the current school year (owner, 19 November 2026: a projection to the current date where the
    # data stop earlier). Projections, not counts. New York's all-grades count applies the fall the Education
    # Department reported for its district schools to the State's district count and carries its charter schools at
    # their last three years' pace; the Department has not published this year's count by grade, so the elementary
    # grades are carried at their own pace like the other cities'. Paris's applies its academy's projected change for
    # all primary pupils; Tokyo's its public schools' count of May 2026.
    reported_now, reported_drop = 766900, 23018
    reported_before = reported_now + reported_drop     # derived: the two reported figures added, not a published count
    proj = {}
    for k, _ in CITIES:
        t = W.pupils(k).set_index("year")["pupils"].astype(float)
        y1 = int(t.index.max())
        target = CURRENT_CALENDAR if k in CALENDAR else CURRENT
        pace = (t[y1] / t[y1 - 3]) ** (1 / 3) - 1
        if k == "paris":
            value = t[y1] * (133240 / (101071 + 35386))
            method = ("the Académie de Paris's projection for the rentrée of 2026 (133,240 pupils in public and private "
                      "primary schools, maternelles included) against 2025's count, applied to the public écoles élémentaires")
        elif k == "tokyo":
            tp = W.tokyo_public_2026()
            value = t[y1] * tp[2027] / tp[2026]
            method = "Tokyo's public elementary count of 1 May 2026 against 1 May 2025, applied to all sectors"
        else:
            value = t[y1] * (1 + pace) ** (target - y1)
            method = f"its average yearly change over its last three years ({100 * pace:+.1f}% a year) carried {target - y1} year(s)"
        proj[k] = {"school_year": sy(target, k), "pupils": int(round(value)), "from_latest_years": target - y1,
                   "change_since_base_pct": r(pct_from(value, t[BASE]), 2), "method": method}
    s_ch = s["charter_k12"]
    ch_pace = (s_ch[last] / s_ch[last - 3]) ** (1 / 3) - 1
    ny_k12 = s.at[last, "district_k12"] * (1 - reported_drop / reported_before) + s_ch[last] * (1 + ch_pace)
    A.results["projection"] = {
        "cities": proj, "note": "projections, not counts",
        "new_york_k12": {"school_year": sy(CURRENT), "students": int(round(ny_k12)),
                         "change_since_base_pct": r(pct_from(ny_k12, s.at[BASE, "public_k12"]), 2),
                         "method": "the fall the Education Department reported for its district schools (23,018 on the "
                                   "789,918 the two reported figures imply) applied to the State's district count; charter "
                                   "schools at their last three years' pace"},
    }

    # ---- the current year, as reported: the Education Department's preliminary count of its district schools
    now = {"chalkbeat_drop": Q.quote("chalkbeat_nyc_enrollment_2026_27_preliminary", "chalkbeat_nyc_enrollment_2026_27_preliminary.html",
                                     "about 23,000 students, or nearly 3%"),
           "chalkbeat_k12": Q.quote("chalkbeat_nyc_enrollment_2026_27_preliminary", "chalkbeat_nyc_enrollment_2026_27_preliminary.html",
                                    "766,900"),
           "nydn_k12": Q.quote("nydn_nyc_enrollment_2026_27_preliminary", "nydn_nyc_enrollment_2026_27_preliminary.html", "23,018"),
           "nydn_total": Q.quote("nydn_nyc_enrollment_2026_27_preliminary", "nydn_nyc_enrollment_2026_27_preliminary.html", "863,100")}
    A.results["now"] = {"quotes": now, "k12_reported": reported_now, "k12_drop_reported": reported_drop,
                        "k12_before_derived": reported_before, "with_prek_reported": 863100,
                        "universe": "the Education Department's own district schools, kindergarten to grade 12, 31 October, preliminary"}
    A.latest("2026-10", "The Education Department's preliminary register of its district schools for 2026-27 (31 October 2026), "
             "as reported by Chalkbeat and the Daily News on 16 November 2026; the State's counts for 2025-26 are the latest on file")
    A.long_view(1995, last, "Students from kindergarten to grade 12 in New York City's district schools, the State's October count, "
                "1994-95 to 2025-26, with charter schools from 2011-12")

    # ---- what is being said, and what the cities did: 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,
                            "comptroller_district": -93781, "comptroller_charter": 11287, "comptroller_private": -6841,
                            "comptroller_home": 4097, "sca_projection": 128000, "chicago_closed": 47,
                            "chicago_students": 12000, "london_closures": 90, "paris_lost": 30000,
                            "hold_harmless_billion": 2}
    for key, pat in (("comptroller_district", r"-93,781"), ("comptroller_charter", r"\+11,287"),
                     ("sca_projection", r"128,000"), ("chicago_closed", r"\b47\b"), ("london_closures", r"approximately 90"),
                     ("paris_lost", r"30 000")):
        src = {"comptroller_district": "comptroller_split", "comptroller_charter": "comptroller_split",
               "sca_projection": "sca_projection", "chicago_closed": "chicago_47", "london_closures": "london_closures",
               "paris_lost": "paris_lost"}[key]
        assert re.search(pat, hist[src]["quote"]), f"{key}: {pat} is not in the quote it is read from"

    # ---- printed figures
    P = A.printed
    ny, el_r, kg, sp = A.results["new_york"], A.results["elementary"], A.results["kindergarten"], A.results["split"]
    for path in ("new_york.district.peak.k12", "new_york.district.last.k12", "new_york.public.base.k12",
                 "new_york.public.last.k12", "new_york.public.charter_first", "new_york.public.charter_last",
                 "new_york.public.k12.2023", "new_york.public.k12.2025",
                 "elementary.base.students", "elementary.last.students", "elementary.fall", "elementary.births_part",
                 "elementary.ratio_part", "kindergarten.last.public_k", "kindergarten.last.births",
                 "kindergarten.public_k_from.k", "kindergarten.public_k_from.births",
                 "split.charter", "split.home", "chicago_2026_27",
                 "births.2020", "births.2023", "now.k12_reported", "now.k12_drop_reported"):
        P(path, fmt="int")
    P("new_york.public.change_since_base_pct", f"{abs(ny['public']['change_since_base_pct']):.0f}%")
    P("new_york.district.fall_from_peak_pct", f"{abs(ny['district']['fall_from_peak_pct']):.0f}%")
    P("new_york.district.per_100_residents.peak", fmt="dec1")
    P("new_york.district.per_100_residents.last", fmt="dec1")
    for k in list(world) + [w for w, _ in WIDER]:          # both counts of every city's change, for the table in the questions
        node = "cities" if k in world else "wider"
        P(f"{node}.{k}.base", fmt="int")
        P(f"{node}.{k}.latest", fmt="int")
        P(f"{node}.{k}.change_pct", f"{abs(A.results[node][k]['change_pct']):.0f}%")
    P("elementary.students_change_pct", f"{abs(el_r['students_change_pct']):.0f}%")
    P("elementary.births_change_pct", f"{abs(el_r['births_change_pct']):.0f}%")
    P("elementary.base.per_birth", f"{el_r['base']['per_birth']:.2f}")
    P("elementary.last.per_birth", f"{el_r['last']['per_birth']:.2f}")
    P("elementary.low.per_birth", f"{el_r['low']['per_birth']:.2f}")
    P("elementary.births_share_pct", f"{el_r['births_share_pct']:.0f}%")
    P("elementary.other_bases.2020.births_share_pct", f"{el_r['other_bases']['2020']['births_share_pct']:.0f}%")
    P("kindergarten.last.per_birth", f"{kg['last']['per_birth']:.2f}")
    P("kindergarten.low.per_birth", f"{kg['low']['per_birth']:.2f}")
    P("kindergarten.public_k_change_pct", f"{abs(kg['public_k_change_pct']):.0f}%")
    P("kindergarten.births_change_pct", f"{abs(kg['births_change_pct']):.0f}%")
    P("grades.grade_5.2020", f"{A.results['grades']['grade_5']['2020']:.2f}")
    P(f"grades.grade_5.{last}", f"{A.results['grades']['grade_5'][str(last)]:.2f}")
    P("matched.district.change", f"{-mt['district']['change']:,}")
    P("matched.charter.change", fmt="int")
    P("matched.home.change", fmt="int")
    P("matched.private.change", f"{-mt['private']['change']:,}")
    P("matched.gained", fmt="int")
    P("matched.all_kinds.first", fmt="int")
    P("matched.all_kinds.last", fmt="int")
    P("matched.all_kinds.per_birth_first", f"{mt['all_kinds']['per_birth_first']:.2f}")
    P("matched.all_kinds.per_birth_last", f"{mt['all_kinds']['per_birth_last']:.2f}")
    P(f"ungraded.{sy(BASE)}", fmt="int")
    P(f"ungraded.{sy(last)}", fmt="int")
    P("cities.madrid.change_pct", f"{abs(world['madrid']['change_pct']):.0f}%")
    P("split.district", f"{-sp['district']:,}")
    P("split.private", f"{-sp['private']:,}")
    P("census.age_5_13.change_pct", f"{abs(A.results['census']['age_5_13']['change_pct']):.0f}%")
    P("census.public_k8.change_pct", f"{abs(A.results['census']['public_k8']['change_pct']):.0f}%")
    A.results["order"]["threshold_pct"] = THRESHOLD
    P("order.threshold_pct", "5%")
    A.results["new_york"]["public"]["charter_growth_2012_2021"] = int(s.at[2021, "charter_k12"] - s.at[2012, "charter_k12"])
    P("new_york.public.charter_growth_2012_2021", fmt="int")
    P("history.chicago_students", "12,000")
    P("history.sca_projection", "128,000")
    P("history.hold_harmless_billion", "$2")
    P("projection.new_york_k12.change_since_base_pct", f"{abs(A.results['projection']['new_york_k12']['change_since_base_pct']):.0f}%")
    P("projection.cities.paris.change_since_base_pct", f"{abs(proj['paris']['change_since_base_pct']):.0f}%")
    porder = sorted(proj, key=lambda k: proj[k]["change_since_base_pct"])
    A.results["projection"]["order"] = porder
    pprimary = [k for k in porder if k in PRIMARY]
    assert pprimary[:2] == ["paris", "new_york"] and pprimary[-1] == "berlin" and \
        all(proj[k]["change_since_base_pct"] < THRESHOLD for k in pprimary[:-1]), \
        "the page says Paris and New York stay the two steepest falls among the primary counts and Berlin the only one growing"

    # ---- charts
    years = list(range(1995, last + 1))
    A.chart("long_view", lines(
        title="New York's district schools have lost more than a quarter of their students since 1998-99",
        subtitle="Students from kindergarten to grade 12, New York City, district schools 1994-95 to 2025-26 and "
                 "district and charter schools from 2011-12",
        x=[[str(y), sy(y)] for y in years],
        series=[["district", "District schools", "District"], ["public", "District and charter schools", "With charters"]],
        cells={"": {"district": {str(y): int(d.at[y, "k12"]) for y in years},
                    "public": {str(y): (int(s.at[y, "public_k12"]) if y in s.index else None) for y in years}}},
        format="count", axis="Students, kindergarten to grade 12", x_axis="School year",
        x_ticks=[str(y) for y in years if y % 5 == 0 or y in (1995, last)],
        x_tick_labels={str(y): sy(y) for y in years},
        note="The State Education Department's count on BEDS day each October, the City's district schools (the "
             "community districts, the high-school districts until 2002-03, and District 75) and, from 2011-12, its "
             "charter schools, which the State's by-school files carry from that year. New York's pre-K is not in "
             "these counts.",
        provenance="New York State Education Department, public school enrollment by district and by school"))

    pb_years = [int(y) for y in kb.index]
    A.chart("per_birth", lines(
        title="The newest kindergarten class is back at two-thirds of its birth year; the elementary grades as a whole are not",
        subtitle="Students in New York City's public schools (district and charter) per birth to a city resident in the "
                 "grades' birth years: kindergarten from 2011-12, kindergarten to grade 5 from 2014-15",
        x=[[str(y), sy(y)] for y in pb_years],
        series=[["k", "Kindergarten, per birth five years earlier", "Kindergarten"],
                ["k5", "Kindergarten to grade 5, per birth in their six birth years", "K to grade 5"]],
        cells={"": {"k": {str(y): r(float(kb.at[y, "per_birth"]), 3) for y in pb_years},
                    "k5": {str(y): (r(float(el.at[y, "per_birth"]), 3) if y in el.index else None) for y in pb_years}}},
        format="dec2", axis="Students per birth", x_axis="School year", zero=False,
        note="Each grade in October of the school year (the State's count) over the births to residents of the five "
             "counties in that grade's birth year: kindergarten in 2025-26 against 2020, grade 5 against 2015. The "
             "numerator counts every child in the grade, born here or arrived since, so the ratio is net of moves in "
             "and out. The births file starts in 2004, so the six-grade ratio starts in 2014-15.",
        provenance="New York State Education Department; New York State Department of Health"))

    A.chart("where_went", strip(
        title="From kindergarten to grade 6, district schools lost far more students in eight years than charter and home "
              "schooling gained, and private schools shrank too",
        subtitle=f"Change in students in kindergarten to grade 6 in New York City by kind of school, {sy(m0)} to {sy(m1)}",
        x=[["change", f"{sy(m0)} to {sy(m1)}"]],
        series=[["district", "District schools", "District"], ["charter", "Charter schools", "Charter"],
                ["private", "Private schools", "Private"], ["home", "Taught at home", "Home"]],
        cells={"": {k: {"change": mt[k]["change"]} for k in ("district", "charter", "private", "home")}},
        format="num", axis="Change in students", order="series", zero=True,
        note="The State's counts each October, on one set of grades and years: district and charter schools from its "
             "school files, private schools from its nonpublic files (which start in 2017-18), children taught at home "
             "from its home-instruction file, whose younger band is kindergarten to grade 6, so that band is used for "
             "every kind. These are changes in each kind's count, not children followed from one school to another.",
        provenance="New York State Education Department"))

    ix_years = list(range(2006, max(world[k]["latest_year"] for k in world) + 1))
    series_ix = {}
    for k in WORLD_LINES:
        t = W.pupils(k).set_index("year")["pupils"]
        series_ix[k] = {str(y): (r(100 * float(t[y]) / float(t[BASE]), 1) if y in t.index else None) for y in ix_years}
    A.chart("world_lines", lines(
        title="On the primary grades, New York's schools shrank faster than London's and nearly as fast as Paris's, while Berlin's grew",
        subtitle="Students in each city's primary grades as its office counts them, 2015-16 = 100, 2005-06 to the latest year",
        x=[[str(y), sy(y)] for y in ix_years],
        series=[[k, LABEL[k], LABEL[k]] for k in WORLD_LINES],
        cells={"": series_ix}, format="num", axis="Index, 2015-16 = 100", x_axis="School year", zero=False,
        x_ticks=[str(y) for y in ix_years if y % 5 == 1 or y == ix_years[-1]], x_tick_labels={str(y): sy(y) for y in ix_years},
        note="New York's public schools, kindergarten to grade 5 (from 2011-12); London's state-funded primary schools, "
             "Years 1 to 6 (from 2015-16); Paris's public écoles élémentaires; Hong Kong's government and aided primary "
             "schools (from 2015-16); Berlin's grades 1 to 6; Tokyo's elementary schools (all sectors; a school year that "
             "starts in April is filed under the year it ends). The other cities are in the next chart and the data file.",
        provenance="NYSED; DfE; DEPP; NCES; Amt für Statistik Berlin-Brandenburg; Tokyo Metropolitan Government"))

    def node_of(k: str) -> dict:
        return world.get(k) or A.results["wider"][k]
    bar_order = sorted(PRIMARY, key=lambda k: world[k]["change_pct"]) + \
        sorted(BROADER + ["new_york_k12"], key=lambda k: node_of(k)["change_pct"])
    scope = {"toronto": "Toronto, to grade 8", "vienna": "Vienna, compulsory schools", "chicago": "Chicago, all grades",
             "new_york_k12": "New York, all grades"}
    def bar_label(k: str) -> list[str]:
        name = scope.get(k, LABEL.get(k, k))
        return [k, f"{name} (to {node_of(k)['latest_school_year']})", name + ("*" if k in scope else "")]
    A.chart("then_and_now", strip(
        title="Of nine big cities' primary grades, only Paris's fell more than New York's since 2015-16; Berlin's grew by a fifth",
        subtitle="Change in students from 2015-16 to each city's latest year, as its office counts them: nine primary-grade "
                 "counts, then four broader counts (*)",
        x=[["change", "2015-16 to the latest year"]],
        series=[bar_label(k) for k in bar_order],
        cells={"": {k: {"change": node_of(k)["change_pct"]} for k in bar_order}},
        format="chg", axis="Change since 2015-16", order="series",
        note="The first nine rows are counts of primary grades from age five or six (kindergarten to grade 5 in New York, "
             "Years 1 to 6 in London, the écoles élémentaires in Paris), ordered from the largest fall. The four rows "
             "marked * are broader counts and are not ranked with them: Toronto's runs to grade 8 (to 2024-25), Vienna's "
             "is its compulsory schools (to 2023-24), Chicago's is all grades with pre-K (to 2024-25), set beside New "
             "York's all grades. Tokyo and Berlin count public and private schools together; the Madrid region is the "
             "Comunidad, and its 2025-26 figure is provisional; Singapore ends in 2024.",
        provenance="NYSED; DfE; DEPP; Amt für Statistik Berlin-Brandenburg; Stadt Wien; Spain's education ministry; "
                   "Ontario's education ministry; NCES; Tokyo Metropolitan Government; Hong Kong Education Bureau; "
                   "SingStat; NSW Department of Education"))

    rows = []
    for k, label in CITIES + WIDER:
        t = W.pupils(k)
        for _, x in t.iterrows():
            rows.append({"city": label, "series": "students", "covers": W.CITIES[k][0], "school_year": sy(int(x["year"]), k),
                         "year_ending": int(x["year"]), "students": int(x["pupils"]), "kind": "count",
                         "publisher": W.CITIES[k][1], "source": x["source"]})
    for k, _ in CITIES:
        rows.append({"city": LABEL[k], "series": "students", "covers": W.CITIES[k][0], "school_year": proj[k]["school_year"],
                     "year_ending": CURRENT_CALENDAR if k in CALENDAR else CURRENT, "students": proj[k]["pupils"],
                     "kind": "projection", "publisher": "SparkyData projection: " + proj[k]["method"], "source": "derived"})
    for y in d.index:
        rows.append({"city": "New York, district schools", "series": "students",
                     "covers": "New York City's district schools, kindergarten to grade 12", "school_year": sy(int(y)),
                     "year_ending": int(y), "students": int(d.at[y, "k12"]), "kind": "count",
                     "publisher": "New York State Education Department", "source": d.at[y, "source"]})
    def birth_sources(years) -> str:
        ids = sorted({f"nys_doh_vital_statistics_{y}_table07" for y in years if y <= 2007}) + \
              (["nys_doh_live_births_by_resident_county"] if any(y >= 2008 for y in years) else [])
        return "; ".join(ids)
    for _, x in gp.iterrows():
        rows.append({"city": "New York", "series": "grade per birth",
                     "covers": f"public schools, {'kindergarten' if x['grade'] == 0 else 'grade ' + str(int(x['grade']))}, "
                               "against births to city residents in the grade's birth year",
                     "school_year": sy(int(x["year"])), "year_ending": int(x["year"]), "students": int(x["students"]),
                     "births": int(x["births"]), "birth_years": str(int(x["birth_year"])),
                     "students_per_birth": r(float(x["per_birth"]), 4), "kind": "count",
                     "publisher": "New York State Education Department; New York State Department of Health",
                     "source": f"nysed_public_school_enrollment_{int(x['year'])}; {birth_sources([int(x['birth_year'])])}"})
    for y in el.index:
        rows.append({"city": "New York", "series": "kindergarten to grade 5 per birth",
                     "covers": "public schools, kindergarten to grade 5, against births to city residents in the six birth years",
                     "school_year": sy(int(y)), "year_ending": int(y), "students": int(el.at[y, "students"]),
                     "births": int(el.at[y, "births"]), "birth_years": f"{int(y) - 11}-{int(y) - 6}",
                     "students_per_birth": r(float(el.at[y, "per_birth"]), 4), "kind": "count",
                     "publisher": "New York State Education Department; New York State Department of Health",
                     "source": f"nysed_public_school_enrollment_{int(y)}; {birth_sources(range(int(y) - 11, int(y) - 5))}"})
    for k in ("district", "charter", "private", "home"):
        for which, yy in (("first", m0), ("last", m1)):
            rows.append({"city": "New York", "series": "kindergarten to grade 6 by kind of school",
                         "covers": f"{k} schools, kindergarten to grade 6" if k != "home" else "children taught at home, kindergarten to grade 6",
                         "school_year": sy(yy), "year_ending": yy, "students": mt[k][which], "kind": "count",
                         "publisher": "New York State Education Department",
                         "source": {"district": f"nysed_public_school_enrollment_{yy}", "charter": f"nysed_public_school_enrollment_{yy}",
                                    "private": f"nysed_nonpublic_enrollment_by_grade_{yy - 1}_{yy % 100:02d}",
                                    "home": "nysed_home_instructed_2010_on"}[k]})
    out = pd.DataFrame(rows)
    for c in ("students", "births", "year_ending"):
        out[c] = out[c].astype("Int64")
    A.write(data=out)
    print(f"{SLUG}: wrote {A.out}")
    return 0


#: What is being said about school rolls, and what cities did: (key, source id, saved file, needle). Each is quoted on the
#: page with its date; none is used as a cause.
HISTORY = [
    ("comptroller_reflects", "nyc_comptroller_k12_student_population_2026", "nyc_comptroller_tracking_k12_student_population_2026.pdf",
     "The decline in NYCPS enrollment largely reflects a broader decrease in the number of school-aged children in New York City"),
    ("comptroller_not_other", "nyc_comptroller_k12_student_population_2026", "nyc_comptroller_tracking_k12_student_population_2026.pdf",
     "not increased enrollment in other school types"),
    ("closures_proposed", "chalkbeat_nyc_enrollment_2026_27_preliminary", "chalkbeat_nyc_enrollment_2026_27_preliminary.html",
     "proposals to close two small schools in Harlem and one in Brooklyn"),
    ("officials_declined", "chalkbeat_nyc_enrollment_2026_27_preliminary", "chalkbeat_nyc_enrollment_2026_27_preliminary.html",
     "Officials declined to say whether they planned to continue that policy"),
    ("chalkbeat_factors", "chalkbeat_nyc_enrollment_2026_27_preliminary", "chalkbeat_nyc_enrollment_2026_27_preliminary.html",
     "falling birth rates, families leaving the city, and a slowdown of immigra"),
    ("comptroller_split", "nyc_comptroller_k12_student_population_2026", "nyc_comptroller_tracking_k12_student_population_2026.pdf",
     "-81,506 -93,781 +11,287 -6,841 +4,097"),
    ("sca_projection", "nyc_comptroller_k12_student_population_2026", "nyc_comptroller_tracking_k12_student_population_2026.pdf",
     "will decline by an additional 128,000 from SY2025-26 to SY2034-35"),
    ("doe_response", "nydn_nyc_enrollment_2026_27_preliminary", "nydn_nyc_enrollment_2026_27_preliminary.html",
     "affordability challenges and changing demographics"),
    ("nydn_migrants", "nydn_nyc_enrollment_2026_27_preliminary", "nydn_nyc_enrollment_2026_27_preliminary.html",
     "The downturn finally started to stabilize with the arrival of school-aged migrant children"),
    ("nydn_amid", "nydn_nyc_enrollment_2026_27_preliminary", "nydn_nyc_enrollment_2026_27_preliminary.html",
     "began decreasing again last school year amid President Trump's federal immigration crackdown"),
    ("hold_harmless", "chalkbeat_nyc_enrollment_2026_27_preliminary", "chalkbeat_nyc_enrollment_2026_27_preliminary.html",
     "Since 2020, New York City has spent nearly $2 billion to prop up budgets at schools with declinin"),
    ("ft_mirrored", "theweek_londons_disappearing_children_2026", "theweek_londons_disappearing_children_2026.html",
     "mirrored across cities in Europe and the US"),
    ("london_closures", "london_councils_falling_pupil_numbers_2026", "london_councils_falling_pupil_numbers_2026.html",
     "approximately 90 school closures or mergers in the last five years"),
    ("paris_lost", "ac_paris_dossier_presse_2026_27", "ac_paris_dossier_presse_2026_27.pdf",
     "En 10 ans, les écoles publiques parisiennes ont perdu 30 000 élèves"),
    ("chicago_47", "uchicago_consortium_school_closings_2018", "uchicago_consortium_school_closings_2018.pdf",
     "Ultimately, 47 elementary schools and one high school program at an elementary school were closed at the end of the 2012"),
    ("chicago_students", "uchicago_consortium_school_closings_2018", "uchicago_consortium_school_closings_2018.pdf",
     "nearly 12,000 students were attending the 47 elementary schools that closed that year"),
    ("chicago_math", "uchicago_consortium_school_closings_2018", "uchicago_consortium_school_closings_2018.pdf",
     "the gap in math test scores remained for four years post-closings"),
]


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