"""New York's births per woman against ten other big cities', 2004-2025: the analysis behind a SparkyData article.

    py src/build_article.py births-in-big-cities

The total fertility rate, the number of children a woman would have at one year's rates for each age, for New York
City and ten other big cities (card ``world_city_fertility``, loader ``nycdata.world_fertility``). New York's is
computed here from the State's births to residents by the mother's age (Table 7 of the yearly reports for 2004-2007,
the State's file from 2008, to 2023) over women by age in the five counties (the Census Bureau's estimates); every
other city's is its own statistics office's: London (the GLA, then the ONS), Paris (INSEE), Berlin (Destatis), Vienna
(the City, from Statistik Austria), the Comunidad de Madrid (INE), Tokyo (the health ministry), Seoul (Statistics
Korea), Hong Kong (C&SD), Singapore (SingStat) and Greater Sydney (the ABS, three-year averages).

A published rate is a census of registered births over an estimated population, not a sample: the comparisons here are
the observed order and the observed change, each city against itself, three years against three (2008-2010, the first
years every city's series covers, Seoul's from 2008, against 2021-2023, the last years New York's covers). Greater
Sydney's rates are already three-year averages, so its two periods are the ABS's own averages for them. Where the
offices count differently (whose births, which population, a change of population base), the page names it beside the
number, and Berlin is also compared within its current base (from 2012). New York's 2020s rates rest on the Census
Bureau's latest estimates of women by age (Vintage 2025); the previous vintage's, on a base about 4% lower, are
reported beside them as the size of one year's revision. New York's own fall is split by the mother's age: the change
in each age group's rate, times five, adds to the change in the total. The current year is the City's provisional
count of births in the city, the first half of 2026 against the first half of 2025: a different count (every birth in
the city, whoever the mother) compared only with itself, the change named only when it survives the swing of the
quarterly counts, each quarter set against the same quarter a year before (``Article.recheck`` with ``season=4``).
What each city does for families comes from its own documents, quoted (``RESPONSES``), never as a cause.

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

from __future__ import annotations

import math
import re
from decimal import ROUND_HALF_UP, Decimal

import pandas as pd

from _paths import RAW
from article_kit import Article, lines, r, strip
from nycdata import world_fertility as F
from sparkylib.stats import count_change, dispersion

SLUG = "births-in-big-cities"
SEED = 20261118
EARLY = (2008, 2010)          # the first three years every city's series covers (Seoul's starts in 2008)
LATE = (2021, 2023)           # the last three years New York's covers (the State's file ends in 2023)
BERLIN_BASE = (2012, 2014)    # Berlin's first three years on its current population base (Destatis: from 2012)
PEAK_FROM = 2004
REPLACEMENT = 2.1             # the rate at which a generation replaces itself (with low mortality), a reference only
#: Rates the office publishes as three-year averages, each labelled by the last of its three years (the ABS's Greater
#: Sydney: "averaged using data for the three years ending in the reference year"): a period is the value labelled
#: with its last year, not a mean of three averages.
THREE_YEAR = {"sydney"}
#: The cities, New York first: (key in world_fertility, label, short label).
CITIES = [("new_york", "New York", "New York"), ("london", "London", "London"), ("paris", "Paris", "Paris"),
          ("berlin", "Berlin", "Berlin"), ("vienna", "Vienna", "Vienna"), ("madrid", "Madrid region", "Madrid region"),
          ("sydney", "Sydney", "Sydney"), ("tokyo", "Tokyo", "Tokyo"), ("seoul", "Seoul", "Seoul"),
          ("hong_kong", "Hong Kong", "Hong Kong"), ("singapore", "Singapore", "Singapore")]
OTHERS = [k for k, _, _ in CITIES if k != "new_york"]
WORLD_LINES = ["new_york", "london", "paris", "tokyo", "seoul", "hong_kong"]
#: The City's provisional births files: November 2026 (source nyc_provisional_vital_statistics_2026_11) and the August
#: 2026 edition (nyc_provisional_vital_statistics), which shows how much a recent quarter is revised.
PROVISIONAL = RAW / "world_cities" / "fertility" / "nyc_provisional_vital_statistics_2026-11.csv"
PROVISIONAL_AUGUST = RAW / "health" / "nyc_provisional_vital_statistics.csv"
#: January to March 2026 in the August edition, as a recorded observation: the City serves one address and replaces the
#: file, so a later download of nyc_provisional_vital_statistics is a later edition and a rebuild prints this instead.
AUGUST_EDITION_Q1_2026 = 23214
NOW_YEAR = 2026
YOUNG = ("15-19", "20-24", "25-29")
OLDER = ("35-39", "40-44", "45-49")
MIDPOINT = {a: int(a[:2]) + 2.5 for a in F.AGE_GROUPS}    # the middle of each five-year group, for the mean age


def mean_years(s: pd.Series, a: tuple[int, int]) -> float:
    x = s.loc[a[0]:a[1]]
    if len(x) != a[1] - a[0] + 1:
        raise ValueError(f"missing years in {a}: {list(x.index)}")
    return float(x.mean())


def tfr_over(k: str, s: pd.Series, a: tuple[int, int]) -> float:
    """A city's rate over the years ``a``: the mean of its yearly rates, or for a three-year-average series the
    value labelled with the last year."""
    if k in THREE_YEAR:
        return float(s[a[1]])
    return mean_years(s, a)


def tfr_text(x: float, nd: int = 2) -> str:
    """A rate as the page prints it, rounded half up from its stored value (1.285 prints 1.29, not the binary 1.28)."""
    return str(Decimal(repr(float(x))).quantize(Decimal(1).scaleb(-nd), rounding=ROUND_HALF_UP))


def quarters(path) -> pd.Series:
    """The City's total births by quarter (start date -> births) from one edition of its provisional file."""
    pv = pd.read_csv(path)
    tb = pv[pv["metric"].eq("Total births") & pv["submetric"].eq("Total")].copy()
    months = {m: i for i, m in enumerate(("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
                                          "Dec"), start=1)}
    parts = tb["date"].str.extract(r"^(\w{3}) (\d{1,2}) (\d{4})$")
    if parts.isna().any().any():
        raise ValueError(f"{path.name}: a date is not 'Mon D YYYY'")
    tb["date"] = pd.to_datetime(dict(year=parts[2].astype(int), month=parts[0].map(months), day=parts[1].astype(int)))
    return tb.set_index("date")["value"].astype(int).sort_index()


def main(argv: list[str] | None = None) -> int:
    """Run the analysis and write every file (no options)."""
    A = Article(SLUG, __file__, seed=SEED)
    S = {k: F.tfr(k).set_index("year")["tfr"].astype(float) for k, _, _ in CITIES}

    # ---- each city: the two periods, the change, its highest year since 2004 and its latest year
    cities = {}
    for k, label, _ in CITIES:
        s = S[k]
        early, late = tfr_over(k, s, EARLY), tfr_over(k, s, LATE)
        since = s.loc[PEAK_FROM:]
        top = [int(y) for y in since.index if since[y] == since.max()]
        low_year = int(since.idxmin())
        cities[k] = {"label": label, "area": F.AREAS[k][0], "publisher": F.AREAS[k][1],
                     "first_year": int(s.index.min()), "early": r(early, 4), "late": r(late, 4),
                     "change_pct": r(100 * (late / early - 1), 2),
                     "peak": {"year": top[0], "years": top, "tfr": r(float(s[top[0]]), 4)},
                     "low": {"year": low_year, "tfr": r(float(s[low_year]), 4)},
                     "latest": {"year": int(s.index.max()), "tfr": r(float(s.iloc[-1]), 4)},
                     "rose_last_two_years": bool(s.iloc[-1] > s.iloc[-2] > s.iloc[-3]),
                     "fall_from_peak_pct": r(100 * (float(s.iloc[-1]) / float(s[top[0]]) - 1), 2)}
    # Berlin within its current population base: Destatis's rates from 2012 are on the 2022 census's population
    b_base = mean_years(S["berlin"], BERLIN_BASE)
    cities["berlin"]["current_base"] = {"years": list(BERLIN_BASE), "early": r(b_base, 4),
                                        "change_pct": r(100 * (cities["berlin"]["late"] / b_base - 1), 2)}
    A.results["cities"] = cities
    order_late = sorted(cities, key=lambda k: -cities[k]["late"])
    order_change = sorted(cities, key=lambda k: cities[k]["change_pct"])
    rose_two = [k for k in cities if cities[k]["rose_last_two_years"]]
    not_lower = [k for k in cities if cities[k]["change_pct"] >= 0]
    assert rose_two == ["seoul"], f"the page says only Seoul's rate rose in each of its last two years: {rose_two}"
    assert not_lower == ["berlin"], f"the page says every city but Berlin is lower than in 2008-2010: {not_lower}"
    assert cities["berlin"]["current_base"]["change_pct"] < 0
    A.results["order"] = {"late": order_late, "change": order_change,
                          "new_york_late_rank": order_late.index("new_york") + 1,
                          "n_cities": len(cities), "n_others": len(OTHERS),
                          "above_new_york_late": [k for k in order_late if cities[k]["late"] > cities["new_york"]["late"]],
                          "fell_more_than_new_york": [k for k in OTHERS if cities[k]["change_pct"] < cities["new_york"]["change_pct"]],
                          "below_one_latest": [k for k in cities if cities[k]["latest"]["tfr"] < 1],
                          "rose_last_two_years": rose_two, "not_lower_than_early": not_lower,
                          "all_below_replacement": all(cities[k]["latest"]["tfr"] < REPLACEMENT for k in cities)}
    for key in ("above_new_york_late", "fell_more_than_new_york", "below_one_latest"):
        A.results["order"][key + "_n"] = len(A.results["order"][key])
    A.results["replacement"] = REPLACEMENT
    hk = S["hong_kong"]
    A.results["hong_kong_path"] = {str(y): r(float(hk[y]), 4) for y in (2022, 2023, 2024, 2025)}
    # ---- the policies against the history (owner, 14 November 2026): where each city stands at its latest year against
    # 2008-2010, and the paths the story sets beside each city's measures
    latest_change = {k: r(100 * (cities[k]["latest"]["tfr"] / cities[k]["early"] - 1), 2) for k in cities}
    A.results["order"]["latest_against_early_pct"] = latest_change
    assert all(v < 0 for v in latest_change.values()), f"the page says all eleven are below their 2008-2010 rate at their latest year: {latest_change}"
    lowest_four = order_late[-4:]
    lowest_four_early = sorted(cities, key=lambda k: -cities[k]["early"])[-4:]
    assert set(lowest_four_early) == set(lowest_four), f"the page says the four lowest were the four lowest in 2008-2010 too: {lowest_four_early}"
    assert set(lowest_four) == {"seoul", "hong_kong", "tokyo", "singapore"}, f"the page says the four Asian cities are the lowest: {lowest_four}"
    se = S["seoul"]
    A.results["seoul_path"] = {"peak_year": cities["seoul"]["peak"]["year"], "peak": cities["seoul"]["peak"]["tfr"],
                               "low_year": cities["seoul"]["low"]["year"], "low": cities["seoul"]["low"]["tfr"],
                               "y2024": r(float(se[2024]), 4), "latest": cities["seoul"]["latest"]["tfr"],
                               "share_of_fall_recovered": r((float(se.iloc[-1]) - float(se.min())) / (float(se.max()) - float(se.min())), 4)}
    assert 0.13 < A.results["seoul_path"]["share_of_fall_recovered"] < 0.2, "the page says about a sixth"
    tk = S["tokyo"]
    A.results["tokyo_path"] = {str(y): r(float(tk[y]), 4) for y in (2023, 2024, 2025)}
    assert float(tk[2025]) == float(tk.loc[PEAK_FROM:].min()), "the page says Tokyo's rate is at its lowest in the series"
    sg = S["singapore"]
    A.results["singapore_path"] = {str(y): r(float(sg[y]), 4) for y in (2023, 2024, 2025)}
    assert float(sg[2025]) == float(sg.loc[PEAK_FROM:].min()), "the page says Singapore's rate is at its lowest"
    bl = S["berlin"]
    A.results["berlin_path"] = {str(y): r(float(bl[y]), 4) for y in (2007, 2016, 2025)}
    A.results["hong_kong_dragon"] = {str(y): r(float(hk[y]), 4) for y in (2011, 2012, 2013)}
    assert float(hk[2012]) > float(hk[2011]) and float(hk[2012]) > float(hk[2013]) and float(hk[2024]) > float(hk[2023]) and float(hk[2024]) > float(hk[2025]), \
        "the page says Hong Kong's rate rose in each Dragon year and fell back the next"

    # ---- New York: the long view, the peak, and the fall by the mother's age
    parts = F.nyc_tfr_parts()
    ny = S["new_york"]
    peak = cities["new_york"]["peak"]["year"]
    last = int(ny.index.max())
    by_age = parts[parts["year"].isin([peak, last])].pivot(index="age", columns="year", values="rate")
    contrib = {a: r(5 * float(by_age.loc[a, last] - by_age.loc[a, peak]), 4) for a in F.AGE_GROUPS}
    fall = float(ny[last] - ny[peak])
    young = sum(contrib[a] for a in YOUNG)
    older = sum(contrib[a] for a in OLDER)
    per1000 = {a.replace("-", "_"): {"peak": r(1000 * float(by_age.loc[a, peak]), 1), "last": r(1000 * float(by_age.loc[a, last]), 1)}
               for a in F.AGE_GROUPS}
    mean_age = {w: r(sum(MIDPOINT[a] * float(by_age.loc[a, y]) for a in F.AGE_GROUPS)
                     / sum(float(by_age.loc[a, y]) for a in F.AGE_GROUPS), 2) for w, y in (("peak", peak), ("last", last))}
    births = parts.groupby("year")["births"].sum()
    women = parts.groupby("year")["women"].sum()
    # the rate's own uncertainty, treating each age group's births as Poisson counts (tiny for a city of this size)
    se = {int(y): math.sqrt(sum(25 * g["births"] / g["women"] ** 2 for _, g in grp.iterrows()))
          for y, grp in parts.groupby("year")}
    # the 2020s on the previous vintage of the Census estimates: the size of one year's revision
    prev = F.nyc_tfr_parts(vintage=2024)
    prev_tfr = 5 * prev.groupby("year")["rate"].sum()
    prev_women = prev.groupby("year")["women"].sum()
    prev_late = mean_years(prev_tfr, LATE)
    A.results["new_york"] = {
        "first": {"year": int(ny.index.min()), "tfr": r(float(ny.iloc[0]), 4)},
        "peak": {"year": peak, "tfr": r(float(ny[peak]), 4)}, "last": {"year": last, "tfr": r(float(ny[last]), 4)},
        "y2019": r(float(ny[2019]), 4), "y2020": r(float(ny[2020]), 4),
        "drop_2020_pct": r(100 * (float(ny[2020]) / float(ny[2019]) - 1), 2),
        "births_2019": int(round(births[2019])), "births_2020": int(round(births[2020])),
        "fall": r(fall, 4), "fall_pct": r(100 * (float(ny[last]) / float(ny[peak]) - 1), 2),
        "fall_by_2019_pct": r(100 * (float(ny[2019]) / float(ny[peak]) - 1), 2),
        "share_of_fall_by_2019": r((float(ny[2019]) - float(ny[peak])) / fall, 4),
        "contribution": contrib, "young_contribution": r(young, 4), "older_contribution": r(older, 4),
        "young_share_of_fall": r(young / fall, 4), "per_1000": per1000, "mean_age": mean_age,
        "births_peak": int(round(births[peak])), "births_last": int(round(births[last])),
        "births_change_pct": r(100 * (births[last] / births[peak] - 1), 2),
        "women_peak": int(women[peak]), "women_last": int(women[last]),
        "women_change_pct": r(100 * (women[last] / women[peak] - 1), 2),
        "tfr_se_last": r(se[last], 4),
        "tfr_range_last": {"lo": r(float(ny[last]) - 1.645 * se[last], 3), "hi": r(float(ny[last]) + 1.645 * se[last], 3)},
        "previous_vintage": {"vintage": 2024, "late": r(prev_late, 4),
                             "change_pct": r(100 * (prev_late / cities["new_york"]["early"] - 1), 2),
                             "women_last": int(prev_women[last]),
                             "women_change_pct": r(100 * (prev_women[last] / women[peak] - 1), 2),
                             "women_revision_pct": r(100 * (women[last] / prev_women[last] - 1), 2)}}
    A.results["new_york"]["at_measures"] = {str(y): r(float(ny[y]), 4) for y in (2014, 2017, 2018)}
    A.results["new_york"]["after_2020"] = {str(y): r(float(ny[y]), 4) for y in (2020, 2021, 2022, 2023)}
    assert float(ny[2022]) > float(ny[2021]) > float(ny[2020]) and float(ny[last]) < float(ny[2019]),         "the page says the rate rose in the two years after 2020 and was still below 2019 in 2023"
    assert float(ny[2014]) > float(ny[2017]) > float(ny[2018]) > float(ny[2019]) > float(ny[last]), \
        "the page says the rate kept falling through pre-K, 3-K and paid leave"
    A.long_view(int(ny.index.min()), last, "New York City's births per woman, computed from the State's births to residents by "
                "the mother's age, 2004-2023; London's from 1993 for comparison",
                why_shorter="New York's rate on births to residents is computed here from the State's births by the mother's "
                            "age, online from 2004 (the yearly reports' Table 7) and 2008 (the State's file); the City's own "
                            "published rate counts every birth in the city, mothers who live elsewhere included")

    # ---- the City's own published rate, which counts every birth in the city (Table PC1 of its 2023 summary)
    Q = A.quotes()
    pc1 = Q.quote("nyc_vital_statistics_2023", "nyc_summary_of_vital_statistics_2023.pdf",
                  "2023 8,258,035 98,389 11.9 56.0 1,569.5", page=53)
    nonres = Q.quote("nyc_vital_statistics_2023", "nyc_summary_of_vital_statistics_2023.pdf", "NON-RESIDENTS 12,701", page=62)
    tfr_city = float(re.search(r"2023 8,258,035 98,389 11\.9 56\.0 ([\d,]+\.\d)", pc1["quote"]).group(1).replace(",", "")) / 1000
    A.results["city_rate"] = {"year": 2023, "tfr": r(tfr_city, 4), "births_in_city": 98389,
                              "births_to_non_residents": int(re.search(r"NON-RESIDENTS ([\d,]+)", nonres["quote"]).group(1).replace(",", "")),
                              "quotes": {"pc1": pc1, "non_residents": nonres}}

    # ---- the current year: births in the city, provisional, the first half against the first half
    q = quarters(PROVISIONAL)
    need = [pd.Timestamp(y, m, 1) for y in (2024, 2025, NOW_YEAR) for m in (1, 4)]
    missing = [str(d.date()) for d in need if d not in q.index]
    if missing:
        raise ValueError(f"the provisional file lacks the quarters {missing}")
    h1 = {y: int(q[pd.Timestamp(y, 1, 1)] + q[pd.Timestamp(y, 4, 1)]) for y in (2024, 2025, NOW_YEAR)}
    yoy = {str(d.date()): r(100 * (int(v) / int(q[d - pd.DateOffset(years=1)]) - 1), 2)
           for d, v in q.items() if d - pd.DateOffset(years=1) in q.index}
    aug = quarters(PROVISIONAL_AUGUST)
    q1 = pd.Timestamp(NOW_YEAR, 1, 1)
    august_copy = aug.index.max() == q1                       # the August edition ends with January to March 2026
    if august_copy:
        assert int(aug[q1]) == AUGUST_EDITION_Q1_2026, "the recorded August count must be the August file's"
    else:
        print("note: the file at raw/health is a later edition than August 2026; its first quarter is printed as recorded then")
    aug_q1 = AUGUST_EDITION_Q1_2026
    A.results["now"] = {"last_quarter_start": str(q.index.max().date()), "first_half": {str(y): v for y, v in h1.items()},
                        "change": count_change(h1[NOW_YEAR], h1[2025]),
                        "quarters": {str(d.date()): int(v) for d, v in q.items()},
                        "year_on_year_pct": yoy, "every_quarter_down": all(v < 0 for v in yoy.values()),
                        "quarters_compared": len(yoy),
                        "q1_revision": {"august": aug_q1, "november": int(q[q1]), "births": int(q[q1]) - aug_q1,
                                        "local_copy_is_the_august_edition": bool(august_copy)}}
    # each quarter against the same quarter a year before, with the quarters' own swing allowed for: every count is lower,
    # but a single quarter's gap can be within chance, so the page names the half-year fall and counts the quarters that
    # clear both ranges (outside review, 15 November 2026)
    swing_q = max(1.0, dispersion(q.tolist(), season=4))
    by_quarter = {}
    for d, v in q.items():
        before = d - pd.DateOffset(years=1)
        if before in q.index:
            plain, wide = count_change(int(v), int(q[before])), count_change(int(v), int(q[before]), dispersion=swing_q)
            by_quarter[str(d.date())] = {"now": int(v), "before": int(q[before]), "change_pct": plain["change_pct"],
                                         "plain": plain["direction"], "allowing_for_swing": wide["direction"],
                                         "lo_pct": wide["lo_pct"], "hi_pct": wide["hi_pct"]}
    clear = [d for d, c in by_quarter.items() if c["plain"] == "down" and c["allowing_for_swing"] == "down"]
    A.results["now"].update({"by_quarter": by_quarter, "quarter_swing": r(swing_q, 2), "quarters_clearly_down": len(clear),
                             "quarters_within_chance": [d for d in by_quarter if d not in clear]})
    assert A.results["now"]["every_quarter_down"] and A.results["now"]["quarters_compared"] == 6, \
        "the page says each of the six quarters since January 2025 is below the same quarter a year before"
    assert len(clear) == 4 and A.results["now"]["quarters_within_chance"] == ["2025-01-01", "2025-04-01"], \
        "the page says the gaps in the first two quarters of 2025 could be chance (April to June 2026 clears only just)"
    A.recheck("now.change", q.tolist(), season=4)
    again = A.results["robustness"]["changes"]["now_change"]
    if A.results["now"]["change"]["direction"] in ("up", "down") and again["direction"] == A.results["now"]["change"]["direction"]:
        A.claim("now.change", A.results["now"]["change"]["direction"])
    A.latest(f"{NOW_YEAR}-06", "NYC Health's provisional births in the city, January to June 2026 against January to June 2025 "
             "(the file of 2 November 2026)")

    # ---- London's rate is read on the ONS's earlier convention (ages 15 to 44, births at 45 and over counted with
    # 40-44); its 2025 edition prints a second rate on ages 15 to 49, which is lower for London (outside review, 15 November)
    lw = F.london_wider_ages()
    A.results["london_conventions"] = {str(y): {k: r(v, 2) for k, v in d.items()} for y, d in lw.items()}
    assert list(lw) == [2025] and lw[2025]["ages_15_49"] < lw[2025]["ages_15_44"], "the page says London's 2025 rate is lower on the wider ages"
    assert abs(lw[2025]["ages_15_44"] - float(F.tfr("london").set_index("year").loc[2025, "tfr"])) < 1e-9, "the series reads ages 15 to 44"

    # ---- what each city does for families, from its own documents
    A.quote_responses(RESPONSES)

    # ---- what is being said about births, and what each office says its measures did: every sentence from its saved page
    hist = {}
    for key, src, fname, needle in HISTORY:
        hist[key] = Q.quote(src, fname, needle)
    num = lambda key, pat, cast=int: cast(re.search(pat, hist[key]["quote"]).group(1).replace(",", ""))   # noqa: E731
    A.results["history"] = {
        "quotes": hist,
        "mayor_share_of_city_pct": num("mayor_14", r"about (\d+)% of the city"),
        "mayor_share_of_leavers_pct": num("mayor_30", r"about (\d+)% of the set of New Yorkers"),
        "seoul_low_reported": num("korea_times_rebound", r"historic low of ([\d.]+) in 2023", float),
        "seoul_latest_reported": num("korea_times_rebound", r"climbed to ([\d.]+),", float),
        "tokyo_rate_reported": num("tokyo_rate", r"fertility rate of ([\d.]+), the lowest", float),
        "hong_kong_births_2025": num("hk_record_low", r"record low of ([\d,]+) in 2025"),
        "hong_kong_target_pct": num("hk_target", r"increase by (\d+) per cent"),
        "hong_kong_target_births": num("hk_target", r"to around ([\d,]+) a year"),
        "hong_kong_bonus_later_children": num("hk_extension_raise", r"bonus to \$([\d,]+)"),
        "singapore_per_child_before": num("sg_payments_before", r"up to \$([\d,]+) per child"),
        "singapore_per_child_now": num("sg_payments_now", r"up to \$([\d,]+) per child"),
        "singapore_rate_2025_reported": num("sg_rate", r"TFR for 2025 was ([\d.]+)", float),
        "new_york_2k_seats": num("ny_2k", r"launch with ([\d,]+) free seats"),
        "seoul_project_trillion_won": num("seoul_project", r"approximately KRW ([\d.]+) trillion over 2025 and 2026", float),
        "seoul_project_before_trillion_won": float(re.search(r"compared to the KRW ([\d.]+) trillion invested from 2023 to 2024",
                                                             A.results["responses"]["seoul"][0]["quote"]).group(1))}
    H = A.results["history"]
    # the offices' own figures match the series the page draws
    assert H["seoul_low_reported"] == round(cities["seoul"]["low"]["tfr"], 2) and H["seoul_latest_reported"] == round(cities["seoul"]["latest"]["tfr"], 2)
    assert H["tokyo_rate_reported"] == round(A.results["tokyo_path"]["2025"], 2)
    assert H["singapore_rate_2025_reported"] == round(A.results["singapore_path"]["2025"], 2)
    assert "sieben Prozent mehr Kinder geboren" in hist["germany_evaluation"]["quote"]

    # ---- what the prose prints
    for k in cities:
        c = cities[k]
        A.printed(f"cities.{k}.early", tfr_text(c["early"]))
        A.printed(f"cities.{k}.late", tfr_text(c["late"]))
        A.printed(f"cities.{k}.latest.tfr", tfr_text(c["latest"]["tfr"]))
        A.printed(f"cities.{k}.latest.year", str(c["latest"]["year"]))
        A.printed(f"cities.{k}.peak.tfr", tfr_text(c["peak"]["tfr"]))
        A.printed(f"cities.{k}.peak.years", " and ".join(str(y) for y in c["peak"]["years"]))
    for k in ("new_york", "seoul", "hong_kong"):
        A.printed(f"cities.{k}.change_pct", f"{abs(cities[k]['change_pct']):.0f}%")
    A.printed("cities.berlin.current_base.change_pct", f"{abs(cities['berlin']['current_base']['change_pct']):.0f}%")
    A.printed("cities.seoul.low.tfr", tfr_text(cities["seoul"]["low"]["tfr"]))
    A.printed("cities.seoul.low.year", str(cities["seoul"]["low"]["year"]))
    for y in ("2022", "2024"):
        A.printed(f"hong_kong_path.{y}", tfr_text(A.results["hong_kong_path"][y]))
    nyr = A.results["new_york"]
    A.printed("new_york.peak.tfr", tfr_text(nyr["peak"]["tfr"]))
    A.printed("new_york.peak.year", str(nyr["peak"]["year"]))
    A.printed("new_york.last.tfr", tfr_text(nyr["last"]["tfr"]))
    A.printed("new_york.y2019", tfr_text(nyr["y2019"]))
    A.printed("new_york.y2020", tfr_text(nyr["y2020"]))
    A.printed("new_york.tfr_range_last.lo", tfr_text(nyr["tfr_range_last"]["lo"]))
    A.printed("new_york.tfr_range_last.hi", tfr_text(nyr["tfr_range_last"]["hi"]))
    A.printed("new_york.share_of_fall_by_2019", f"{100 * nyr['share_of_fall_by_2019']:.0f}%")
    A.printed("new_york.fall_pct", f"{abs(nyr['fall_pct']):.0f}%")
    A.printed("new_york.fall_by_2019_pct", f"{abs(nyr['fall_by_2019_pct']):.0f}%")
    A.printed("new_york.young_share_of_fall", f"{100 * nyr['young_share_of_fall']:.0f}%")
    for a in ("15_19", "20_24", "25_29", "30_34", "35_39", "40_44"):
        for when, y in (("peak", peak), ("last", last)):
            A.printed(f"new_york.per_1000.{a}.{when}", tfr_text(1000 * float(by_age.loc[a.replace("_", "-"), y]), 0))
    A.printed("new_york.mean_age.peak", tfr_text(nyr["mean_age"]["peak"], 1))
    A.printed("new_york.mean_age.last", tfr_text(nyr["mean_age"]["last"], 1))
    A.printed("new_york.births_peak", f"{nyr['births_peak']:,}")
    A.printed("new_york.births_last", f"{nyr['births_last']:,}")
    A.printed("new_york.women_change_pct", f"{abs(nyr['women_change_pct']):.0f}%")
    A.printed("new_york.women_peak", f"{nyr['women_peak'] / 1e6:.2f} million")
    A.printed("new_york.women_last", f"{nyr['women_last'] / 1e6:.2f} million")
    pv_ = nyr["previous_vintage"]
    A.printed("new_york.previous_vintage.late", tfr_text(pv_["late"]))
    A.printed("new_york.previous_vintage.change_pct", f"{abs(pv_['change_pct']):.0f}%")
    A.printed("new_york.previous_vintage.women_change_pct", f"{abs(pv_['women_change_pct']):.0f}%")
    A.printed("new_york.previous_vintage.women_revision_pct", f"{abs(pv_['women_revision_pct']):.1f}%")
    cr = A.results["city_rate"]
    A.printed("city_rate.tfr", tfr_text(cr["tfr"]))
    A.printed("city_rate.births_to_non_residents", f"{cr['births_to_non_residents']:,}")
    nw = A.results["now"]
    for y in ("2025", str(NOW_YEAR)):
        A.printed(f"now.first_half.{y}", f"{nw['first_half'][y]:,}")
    A.printed("now.change.change_pct", f"{abs(nw['change']['change_pct']):.0f}%")
    A.printed("now.q1_revision.births", str(nw["q1_revision"]["births"]))
    for ages in ("ages_15_44", "ages_15_49"):
        A.printed(f"london_conventions.2025.{ages}", tfr_text(A.results["london_conventions"]["2025"][ages]))
    for y in ("2014", "2017", "2018"):
        A.printed(f"new_york.at_measures.{y}", tfr_text(nyr["at_measures"][y]))
    A.printed("new_york.births_change_pct", f"{abs(nyr['births_change_pct']):.0f}%")
    for y in ("2023", "2024", "2025"):
        A.printed(f"tokyo_path.{y}", tfr_text(A.results["tokyo_path"][y]))
    A.printed("singapore_path.2025", tfr_text(A.results["singapore_path"]["2025"]))
    for y in ("2016", "2025"):
        A.printed(f"berlin_path.{y}", tfr_text(A.results["berlin_path"][y]))
    for y in ("2023", "2025"):
        A.printed(f"hong_kong_path.{y}", tfr_text(A.results["hong_kong_path"][y]))
    for y in ("2012", "2013"):
        A.printed(f"hong_kong_dragon.{y}", tfr_text(A.results["hong_kong_dragon"][y]))
    Hh = A.results["history"]
    A.printed("history.mayor_share_of_city_pct", f"{Hh['mayor_share_of_city_pct']}%")
    A.printed("history.mayor_share_of_leavers_pct", f"{Hh['mayor_share_of_leavers_pct']}%")
    A.printed("history.hong_kong_births_2025", f"{Hh['hong_kong_births_2025']:,}")
    A.printed("history.hong_kong_target_pct", f"{Hh['hong_kong_target_pct']}%")
    A.printed("history.hong_kong_bonus_later_children", f"${Hh['hong_kong_bonus_later_children']:,}")
    A.printed("history.singapore_per_child_before", f"${Hh['singapore_per_child_before']:,}")
    A.printed("history.singapore_per_child_now", f"${Hh['singapore_per_child_now']:,}")
    A.printed("history.new_york_2k_seats", f"{Hh['new_york_2k_seats']:,}")
    A.printed("history.seoul_project_trillion_won", f"{Hh['seoul_project_trillion_won']:.1f}")
    A.printed("history.seoul_project_before_trillion_won", f"{Hh['seoul_project_before_trillion_won']:.1f}")
    # the documents' own figures the measures table repeats, read from their quotes
    figures = {"madrid_income": ("madrid", "rentas inferiores a 30.000 €", "30.000", 30000),
               "tokyo_monthly": ("tokyo", "月額5,000円", "5,000", 5000),
               "hong_kong_bonus": ("hong_kong", "a cash reward of $20,000", "$20,000", 20000),
               "singapore_cash": ("singapore", "will receive $10,000 in cash", "$10,000", 10000)}
    A.results["responses_figures"] = {}
    for key, (city, needle, text, value) in figures.items():
        assert any(needle in d["quote"] for d in A.results["responses"][city]), (key, needle)
        A.results["responses_figures"][key] = value
        A.printed(f"responses_figures.{key}", text)
    A.results["responses_figures"]["madrid_income_en"] = 30000
    A.printed("responses_figures.madrid_income_en", "30,000")

    # the FAQ's table: each city's change, signed from the unrounded rates (a change that rounds to nothing is 0%)
    A.results["table"] = {k: {"change": cities[k]["change_pct"]} for k in cities}
    for k in cities:
        x = cities[k]["change_pct"]
        A.printed(f"table.{k}.change", "0%" if round(x) == 0 else f"{x:+.0f}%".replace("-", "−"))

    # ---- charts
    E, L = f"{EARLY[0]}-{EARLY[1]}", f"{LATE[0]}-{LATE[1]}"
    A.chart("long_view", lines(
        title="New York's births per woman fell by about a quarter from 2007 to 2023, and London's fell almost as far",
        subtitle="Total fertility rate, New York City (2004 to 2023) and London (2004 to 2025)",
        x=[[str(t), str(t)] for t in range(2004, 2026)],
        series=[["new_york", "New York City", "New York"], ["london", "Greater London", "London"]],
        cells={"": {k: {str(t): (r(float(S[k][t]), 3) if t in S[k].index else None) for t in range(2004, 2026)}
                    for k in ("new_york", "london")}},
        format="dec2", axis="Children per woman, at that year's rates",
        x_ticks=[str(t) for t in range(2004, 2026) if t % 5 == 0 or t in (2004, 2025)],
        note="New York's rate is computed from the State's births to residents by the mother's age over the Census "
             "Bureau's women by age (its latest estimates, Vintage 2025, for the 2020s); its series ends in 2023, the "
             "State's latest year. London's is the GLA's to 2023 and the ONS's first published rates for 2024 and 2025.",
        provenance="NYS Department of Health; U.S. Census Bureau; GLA; ONS"))

    A.chart("ages", strip(
        title="New York's births per woman fell most under 30 and rose a little after 35",
        subtitle=f"Births a year per 1,000 women in New York City, by the mother's age, {peak} against {last}",
        x=[[str(peak), str(peak)], [str(last), str(last)]],
        series=[[a, a, a] for a in F.AGE_GROUPS],
        cells={"": {a: {str(peak): per1000[a.replace("-", "_")]["peak"], str(last): per1000[a.replace("-", "_")]["last"]}
                    for a in F.AGE_GROUPS}},
        format="dec1", axis="Births per 1,000 women of that age", order="series",
        note="Births to residents of the five boroughs by the mother's age, over women of that age on 1 July. Births to "
             "mothers under 15 are counted with 15-19 and those 45 and over with 45-49.",
        provenance="NYS Department of Health; U.S. Census Bureau"))

    A.chart("then_and_now", strip(
        title="New York is still among the highest of eleven cities, and every city but Berlin is lower than in 2008-2010",
        subtitle=f"Total fertility rate, average of {E} against {L}",
        x=[[E, f"{EARLY[0]} to {EARLY[1]}"], [L, f"{LATE[0]} to {LATE[1]}"]],
        series=[[k, label + (" (three-year averages)" if k == "sydney" else ""), short] for k, label, short in CITIES],
        cells={"": {k: {E: r(cities[k]["early"], 3), L: r(cities[k]["late"], 3)} for k in cities}},
        format="dec2", axis="Children per woman, at that year's rates",
        note="Each city's own statistics office's rate, except New York's, computed here on births to residents. "
             "Berlin's rates from 2012 are on a new population base, which raised them, so its two periods are not on one "
             "base. Tokyo's and Seoul's count births to their nationals; Hong Kong's leaves foreign domestic helpers out "
             "of the women; Sydney's are the ABS's three-year averages for the two periods; the Madrid region is the "
             "Comunidad de Madrid.",
        provenance="NYS DOH and the Census Bureau; GLA and ONS; INSEE; Destatis; Stadt Wien; INE; ABS; MHLW; Statistics "
                   "Korea; C&SD; SingStat"))

    A.chart("world_lines", lines(
        title="Seoul, Hong Kong and Tokyo sit far below New York, London and Paris, and only Seoul's rate has risen two "
              "years running",
        subtitle="Total fertility rate, 2004 (Seoul 2008) to the latest year (New York 2023)",
        x=[[str(t), str(t)] for t in range(2004, 2026)],
        series=[[k, dict((a, b) for a, b, _ in CITIES)[k], dict((a, c) for a, _, c in CITIES)[k]] for k in WORLD_LINES],
        cells={"": {k: {str(t): (r(float(S[k][t]), 3) if t in S[k].index else None) for t in range(2004, 2026)} for k in WORLD_LINES}},
        format="dec2", axis="Children per woman, at that year's rates",
        x_ticks=[str(t) for t in range(2004, 2026) if t % 5 == 0 or t in (2004, 2025)],
        note="Seoul's series starts in 2008 and New York's ends in 2023; Paris's latest three years and Tokyo's 2025 are "
             "provisional. Berlin, Vienna, the Madrid region, Sydney and Singapore are in the data file.",
        provenance="NYS DOH and the Census Bureau; GLA and ONS; INSEE; MHLW; Statistics Korea; C&SD"))

    qs = list(A.results["now"]["quarters"].items())
    A.chart("this_year", lines(
        title="Births in New York City ran about 3% below last year in the first half of 2026",
        subtitle="Births in the city by quarter, provisional, January 2024 to June 2026",
        x=[[d, f"Q{(int(d[5:7]) - 1) // 3 + 1} {d[:4]}"] for d, _ in qs],
        series=[["births", "Births in the city", "Births"]],
        cells={"": {"births": {d: v for d, v in qs}}}, format="count", axis="Births in the quarter",
        x_axis="Quarter",
        note="NYC Health's provisional counts of every birth in the city, whoever the mother: a different count from the "
             "State's births to residents the rate is computed from, and revised when each year is final.",
        provenance="NYC Department of Health and Mental Hygiene, provisional vital statistics (file of 2 November 2026)"))

    rows = []
    for k, label, _ in CITIES:
        src = F.tfr(k).set_index("year")["source_id"]
        for y, v in S[k].items():
            rows.append({"city": label, "area": F.AREAS[k][0], "year": int(y), "total_fertility_rate": r(float(v), 4),
                         "publisher": F.AREAS[k][1], "source": src.get(y)})
    births_source = F.tfr("new_york").set_index("year")["source_id"]
    for _, x in parts.iterrows():
        rows.append({"city": "New York", "area": "New York City, by the mother's age " + x["age"], "year": int(x["year"]),
                     "births": r(float(x["births"]), 1), "women": int(x["women"]), "births_per_1000_women": r(1000 * float(x["rate"]), 2),
                     "publisher": F.AREAS["new_york"][1],
                     "source": f"{births_source[int(x['year'])]}; women: {x['source_id']}"})
    A.write(data=pd.DataFrame(rows))
    print(f"{SLUG}: wrote {A.out}")
    return 0


#: What each city or its country does for families, from its own documents: city -> [(source id, saved file, needle,
#: what it establishes)]. Every sentence the page prints about a measure rests on one of these quotes.
RESPONSES = {
    "new_york": [("nyc_mayor_free_child_care_twos_2026", "nyc_mayor_free_child_care_twos_2026.html",
                  "deliver free child care for two-year-olds in New York City, in addition to strengthening the existing 3K program",
                  "childcare: free care for two-year-olds, announced January 2026"),
                 ("nyc_mayor_free_child_care_twos_2026", "nyc_mayor_free_child_care_twos_2026.html",
                  "the first year of the program will focus on high-need areas selected by New York City and expand to serve "
                  "all interested families across the city by year 4", "phased: high-need areas first, every family by year 4"),
                 ("nyc_mayor_2k_first_four_communities_2026", "nyc_mayor_2k_first_four_communities_2026.html",
                  "The program will launch with 2,000 free seats this fall and expand to full universality within four years",
                  "childcare: 2-K, 2,000 free seats from autumn 2026 (announced 3 March 2026)")],
    "london": [("uk_dfe_30_hours_from_nine_months_2025", "uk_dfe_30_hours_from_nine_months_2025.html",
                "they can now apply for 30 hours of funded childcare from September", "childcare: 30 funded hours a week from nine months"),
               ("uk_dwp_two_child_limit_budget_2025", "uk_dwp_two_child_limit_budget_2025.html",
                "In November 2025, the UK government announced that from April 2026 it will be removing the two-child limit",
                "cash: the two-child limit removed from April 2026, announced November 2025")],
    "paris": [("service_public_conge_naissance_2026", "service_public_conge_naissance_2026.html",
               "Le congé supplémentaire de naissance entre en vigueur le 1 er juillet 2026", "leave: a new birth leave from July 2026"),
              ("service_public_conge_naissance_2026", "service_public_conge_naissance_2026.html",
               "octroie 1 à 2 mois de congé indemnisé à chaque parent", "one to two paid months for each parent, on top of existing leave"),
              ("elysee_conference_de_presse_2024_01_16", "elysee_conference_de_presse_2024_01_16.html",
               "il sera mieux rémunéré et permettra aux deux parents d'être auprès de leur enfant pendant six mois s'ils le souhaitent",
               "the President's announcement of January 2024, in other terms (six months): the terms in force are the page's"),
              ("paris_creches_choisir_mode_accueil", "paris_creches_choisir_mode_accueil.html",
               "Depuis 2014, 46 nouvelles crèches et 4 720 nouvelles places", "childcare: 46 new crèches since 2014")],
    "berlin": [("berlin_kita_kostenfrei", "berlin_kita_kostenfrei.html",
                "In Berlin ist die Kindertagesbetreuung seit August 2018 kostenfrei", "childcare: free since August 2018")],
    "vienna": [("wien_kindergarten_foerderungen", "wien_kindergarten_foerderungen.html",
                "ist in Wien für alle Kinder bis zum Beginn der Schulpflicht beitragsfrei oder stark vergünstigt",
                "childcare: free or heavily discounted until school")],
    "madrid": [("comunidad_madrid_ayudas_natalidad", "comunidad_madrid_ayudas_natalidad.html",
                "las madres de 30 años o menos con rentas inferiores a 30.000 € percibirán 500 € mensuales desde el quinto mes "
                "de embarazo hasta que el niño cumpla 2 años",
                "cash: €500 a month to mothers 30 or under below the income limit, since 2022"),
               ("comunidad_madrid_ayudas_natalidad", "comunidad_madrid_ayudas_natalidad.html", "Tener 30 años o menos",
                "the age requirement in the page's own list, met when applying (one line of the page says 'menores de 30 años')")],
    "tokyo": [("tmg_018_support_2024", "tmg_018_support_2024.html", "都内在住の子供に月額5,000円を支給する",
               "cash: ¥5,000 a month for every child"),
              ("tmg_018_support_2024", "tmg_018_support_2024.html", "所得制限はありません", "with no income limit"),
              ("tmg_018_support_2024", "tmg_018_support_2024.html", "報道発表資料 2024年3月29日",
               "the press release for fiscal 2024, 29 March 2024")],
    "hong_kong": [("hk_lcq16_newborn_bonus_2026", "hk_lcq16_newborn_bonus_2026.html",
                   "providing a cash reward of $20,000 to eligible parents for each baby born on or after October 25, 2023",
                   "cash: HK$20,000 a baby since October 2023"),
                  ("hk_lcq16_newborn_bonus_2026", "hk_lcq16_newborn_bonus_2026.html",
                   "The implementation period of this initiative is 3 years (i.e. from October 25, 2023, to October 24, 2026)",
                   "for three years, to October 2026"),
                  ("hk_policy_address_press_2026_09_16", "hk_policy_address_press_2026_09_16.html",
                   "extending the $20,000 newborn baby bonus for three years", "extended for three more years (16 September 2026)"),
                  ("hk_policy_address_press_2026_09_16", "hk_policy_address_press_2026_09_16.html",
                   "increasing the newborn baby bonus to $30,000", "raised to HK$30,000 for a second or later child")],
    "seoul": [("seoul_solution_birth_encouragement_project_2024", "seoul_solution_birth_encouragement_project_2024.html",
               "committing approximately KRW 6.7 trillion over 2025 and 2026, compared to the KRW 3.6 trillion invested from 2023 to 2024",
               "a package of housing, care and payments: KRW 6.7 trillion for 2025-2026 (4 November 2024)"),
              ("seoul_solution_birth_encouragement_project_2024", "seoul_solution_birth_encouragement_project_2024.html",
               "reversing the decline in birth rates", "the city's own claim for its first two years")],
    "singapore": [("sg_child_support_package_lifesg", "sg_child_support_package_lifesg.html",
                   "Singapore citizen children born on or after 1 April 2027 will receive $10,000 in cash",
                   "cash: S$10,000 a baby from April 2027"),
                  ("sg_child_support_package_lifesg", "sg_child_support_package_lifesg.html",
                   "the SG Child Support Package will replace the Baby Bonus Scheme and Large Families Scheme",
                   "replacing the Baby Bonus")],
    "sydney": [("au_pm_paid_parental_leave_26_weeks_2026", "au_pm_paid_parental_leave_26_weeks_2026.html",
                "From 1 July eligible families will be able to access up to 26 weeks of Paid Parental Leave",
                "leave: up to 26 weeks of paid parental leave, Australia")],
}

#: What is being said about births, and what each office says its own measures did: (key, source id, saved file, needle).
#: Each is quoted on the page with its date; none is used as a cause.
HISTORY = [
    ("prek_2014", "nyc_comptroller_child_care_affordability_2025", "nyc_comptroller_child_care_affordability_2025.pdf",
     "provided working parents with a guarantee of free, reliable, high-quality, early childhood education for four-year-olds"),
    ("threek_2017", "nyc_comptroller_child_care_affordability_2025", "nyc_comptroller_child_care_affordability_2025.pdf",
     "with the promise of Universal 3-K in 2017"),
    ("paid_leave_2018", "nys_osc_paid_family_leave_2023", "nys_osc_paid_family_leave_2023.html",
     "The program began providing benefits on January 1, 2018"),
    ("ny_2k", "nyc_mayor_2k_first_four_communities_2026", "nyc_mayor_2k_first_four_communities_2026.html",
     "The program will launch with 2,000 free seats this fall and expand to full universality within four years"),
    ("mayor_14", "abc7_mamdani_universal_child_care_2025_11_13", "abc7_mamdani_universal_child_care_2025_11_13.html",
     "While families with young children comprise about 14% of the city"),
    ("mayor_30", "abc7_mamdani_universal_child_care_2025_11_13", "abc7_mamdani_universal_child_care_2025_11_13.html",
     "they comprise about 30% of the set of New Yorkers who are leaving the city"),
    ("london_assembly", "london_assembly_declining_children_2025", "london_assembly_declining_children_2025.html",
     "This has been driven by a drop in fertility rates rather than a decrease in the number of potential mothers"),
    ("korea_times_headline", "koreatimes_seoul_birthrate_rebounds_2026_08_27", "koreatimes_seoul_birthrate_rebounds_2026_08_27.html",
     "birthrate rebounds as births and marriages surge"),
    ("korea_times_rebound", "koreatimes_seoul_birthrate_rebounds_2026_08_27", "koreatimes_seoul_birthrate_rebounds_2026_08_27.html",
     "climbed to 0.63, steadily rebounding from its historic low of 0.55 in 2023"),
    ("seoul_doubt", "afp_jakartapost_korea_baby_bump_2026_05_10", "afp_jakartapost_korea_baby_bump_2026_05_10.html",
     "to conclude that the latest government policies had caused the upturn in births"),
    ("seoul_echo", "afp_jakartapost_korea_baby_bump_2026_05_10", "afp_jakartapost_korea_baby_bump_2026_05_10.html",
     "of a larger-than-normal cohort born in the early 1990s"),
    ("seoul_project", "seoul_solution_birth_encouragement_project_2024", "seoul_solution_birth_encouragement_project_2024.html",
     "committing approximately KRW 6.7 trillion over 2025 and 2026"),
    ("seoul_claim", "seoul_solution_birth_encouragement_project_2024", "seoul_solution_birth_encouragement_project_2024.html",
     "reversing the decline in birth rates"),
    ("tokyo_governor", "ann_straitstimes_tokyo_baby_bust_2026_09_07", "ann_straitstimes_tokyo_baby_bust_2026_09_07.html",
     "we have managed to achieve an increase in the number of births"),
    ("tokyo_rate", "ann_straitstimes_tokyo_baby_bust_2026_09_07", "ann_straitstimes_tokyo_baby_bust_2026_09_07.html",
     "dismal fertility rate of 0.96, the lowest across Japan"),
    ("hk_record_low", "scmp_thestar_hk_births_record_low_2026_01_18", "scmp_thestar_hk_births_record_low_2026_01_18.html",
     "plunged to a record low of 31,714 in 2025, despite a range of government incentives"),
    ("hk_target", "scmp_thestar_hk_births_record_low_2026_01_18", "scmp_thestar_hk_births_record_low_2026_01_18.html",
     "authorities predicted the number of births would increase by 20 per cent from about 32,500 in 2022 to around 39,000 a year"),
    ("hk_extension", "hk_policy_address_press_2026_09_16", "hk_policy_address_press_2026_09_16.html",
     "extending the $20,000 newborn baby bonus for three years"),
    ("hk_extension_raise", "hk_policy_address_press_2026_09_16", "hk_policy_address_press_2026_09_16.html",
     "increasing the newborn baby bonus to $30,000"),
    ("hk_review", "hk_lcq16_newborn_bonus_2026", "hk_lcq16_newborn_bonus_2026.html",
     "The review of the Newborn Baby Bonus Scheme is still undergoing"),
    ("sg_alone", "sg_nptd_indranee_cos_speech_2026", "sg_nptd_indranee_cos_speech_2026.html",
     "They cannot be addressed by policy measures alone"),
    ("sg_payments_before", "sg_nptd_indranee_cos_speech_2026", "sg_nptd_indranee_cos_speech_2026.html",
     "parents received up to $32,000 per child"),
    ("sg_payments_now", "sg_nptd_indranee_cos_speech_2026", "sg_nptd_indranee_cos_speech_2026.html",
     "it is up to $54,000 per child"),
    ("sg_rate", "sg_nptd_indranee_cos_speech_2026", "sg_nptd_indranee_cos_speech_2026.html",
     "our preliminary resident TFR for 2025 was 0.87"),
    ("germany_evaluation", "bmfsfj_gesamtevaluation_endbericht_2014", "bmfsfj_gesamtevaluation_endbericht_2014.pdf",
     "insgesamt sieben Prozent mehr Kinder geboren"),
    ("uk_two_child_limit", "lse_two_child_limit_fertility_2025", "lse_two_child_limit_fertility_2025.html",
     "We find little to no decline in higher-order fertility among low-income families"),
    ("uk_two_child_limit_start", "lse_two_child_limit_fertility_2025", "lse_two_child_limit_fertility_2025.html",
     "born on or after 6 April 2017"),
    ("germany_model", "bmfsfj_gesamtevaluation_endbericht_2014", "bmfsfj_gesamtevaluation_endbericht_2014.pdf",
     "nach dem kurzfristigen Simulationsmodell"),
    ("korea_president", "koreaherald_lee_population_policy_2026_10_14", "koreaherald_lee_population_policy_2026_10_14.html",
     "demographic challenges remained unresolved, Lee noted"),
    ("tokyo_count", "ann_straitstimes_tokyo_baby_bust_2026_09_07", "ann_straitstimes_tokyo_baby_bust_2026_09_07.html",
     "it was the first such increase in 10 years"),
    ("hk_dragon", "scmp_thestar_hk_births_record_low_2026_01_18", "scmp_thestar_hk_births_record_low_2026_01_18.html",
     "the uptick in 2024 was largely due to the Year of the Dragon"),
    ("ny_2k_offers", "nyc_mayor_2k_offers_2026", "nyc_mayor_2k_offers_2026.html",
     "more than 2,000 children are receiving offers to join New York City"),
    ("sg_dragon", "sg_nptd_indranee_cos_speech_2026", "sg_nptd_indranee_cos_speech_2026.html",
     "This is due in part to the typical post-Dragon Year decrease"),
    ("korea_two_decades", "koreaherald_lee_population_policy_2026_10_14", "koreaherald_lee_population_policy_2026_10_14.html",
     "Over the past two decades, successive governments have spent heavily"),
    ("paid_leave_phase_in", "nys_osc_paid_family_leave_2023", "nys_osc_paid_family_leave_2023.html",
     "phased in over four years by January 1, 2021"),
    ("tokyo_count_pct", "ann_straitstimes_tokyo_baby_bust_2026_09_07", "ann_straitstimes_tokyo_baby_bust_2026_09_07.html",
     "a modest year-on-year increase of 1.02 per cent"),
    ("seoul_doubt_difficult", "afp_jakartapost_korea_baby_bump_2026_05_10", "afp_jakartapost_korea_baby_bump_2026_05_10.html",
     "very difficult"),
    ("seoul_echo_partly", "afp_jakartapost_korea_baby_bump_2026_05_10", "afp_jakartapost_korea_baby_bump_2026_05_10.html",
     "the rise partly reflected the demographic"),
]


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