"""One chart: how far three days of the calendar move US births, each as an
estimate with its 95 % interval on one axis — the full-moon window in both
series, and the two calendar controls in the sealed series. Drawn after the
data, from results.json (analyse.py).

    python chart.py
writes chart.png here and site/public/images/full-moon-births.svg.
Colours are the site's violet and amber, validated as a pair against the dark
ground with the dataviz validator (all checks pass). Identity is also carried
by the row labels, so colour is never the only cue.
"""

import json
import pathlib

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

HERE = pathlib.Path(__file__).parent
SITE_SVG = HERE.parents[1] / "site" / "public" / "images" / "full-moon-births.svg"
GROUND, INK, DIM, GRID = "#0f1120", "#e8e3d8", "#a9a2c6", "#262a44"
MOON, CAL = "#c4861c", "#9085e9"

res = json.loads((HERE / "results.json").read_text())
s, n = res["ssa_2000_2014"], res["nchs_1994_1999"]
rows = [
    ("Halloween, 2000–14", *s["halloween"][:3], CAL),
    ("Valentine's Day, 2000–14", *s["valentine"][:3], CAL),
    ("full moon + day after, 1994–99", n["est_pct"], n["lo_pct"], n["hi_pct"], MOON),
    ("full moon + day after, 2000–14", s["est_pct"], s["lo_pct"], s["hi_pct"], MOON),
]

plt.rcParams["font.family"] = "monospace"
plt.rcParams["svg.fonttype"] = "none"
fig, ax = plt.subplots(figsize=(9, 3.9), dpi=160)
fig.patch.set_facecolor(GROUND)
ax.set_facecolor(GROUND)

ax.axvline(0, color=DIM, linewidth=0.8, zorder=1)
for i, (label, est, lo, hi, colour) in enumerate(rows):
    ax.plot([lo, hi], [i, i], color=colour, linewidth=2, solid_capstyle="round", zorder=2)
    ax.plot([est], [i], "o", color=colour, markersize=8, markeredgecolor=GROUND,
            markeredgewidth=2, zorder=3)
    ax.text(hi + 0.35, i, f"{est:+.2f} %", va="center", ha="left", color=INK, fontsize=8.5)

ax.set_yticks(range(len(rows)))
ax.set_yticklabels([r[0] for r in rows])
lo_all = min(r[2] for r in rows)
hi_all = max(r[3] for r in rows)
ax.set_xlim(min(lo_all, 0) - 0.8, max(hi_all, 0) + 2.2)
ax.set_ylim(-0.6, len(rows) - 0.4)
ax.set_xlabel("births on that day against the days around it, % (95 % interval)",
              color=DIM, fontsize=9)
ax.tick_params(colors=DIM, labelsize=9, length=0)
ax.grid(True, axis="x", color=GRID, linewidth=0.6, zorder=0)
for side in ax.spines.values():
    side.set_visible(False)
ax.set_title("What moves the day a US baby is born", color=INK, fontsize=11, loc="left", pad=12)
ax.text(0, -0.30, "SSA and CDC/NCHS daily births via FiveThirtyEight · rule sealed before the data · "
        "untilnextsession.com/research/full-moon-births/",
        transform=ax.transAxes, color=DIM, fontsize=7.2)

fig.tight_layout()
fig.savefig(HERE / "chart.png", facecolor=GROUND, bbox_inches="tight")
fig.savefig(SITE_SVG, facecolor=GROUND, bbox_inches="tight")
print("wrote chart.png and", SITE_SVG)
