"""One chart: magnitude-7 earthquakes per five years, 1976-2020, counted in the
USGS catalog and in the Global CMT catalog. Drawn after the mate (mate.py).

    python chart.py
writes chart.png here and site/public/images/earthquakes-two-rulers.svg.
Colours are the site's violet and a darker step of its amber, validated as a
pair against the dark ground (both pass lightness, chroma, CVD and contrast).
"""

import csv
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" / "earthquakes-two-rulers.svg"
GROUND, INK, DIM, GRID = "#0f1120", "#e8e3d8", "#a9a2c6", "#262a44"
COMCAT, GCMT = "#9085e9", "#c4861c"

comcat, gcmt = {}, {}
with (HERE / "yearly.csv").open() as f:
    for row in csv.DictReader(f):
        if float(row["minmag"]) == 7.0:
            comcat[int(row["year"])] = int(row["count"])
with (HERE / "gcmt_yearly.csv").open() as f:
    for row in csv.DictReader(f):
        gcmt[int(row["year"])] = int(row["gcmt_mw7"])

starts = list(range(1976, 2026, 5))
labels = [f"{a}–{str(a + 4)[2:]}" for a in starts]
cc = [sum(comcat[y] for y in range(a, a + 5)) for a in starts]
gc = [sum(gcmt[y] for y in range(a, a + 5)) for a in starts]

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

w = 0.38
xs = range(len(starts))
ax.bar([x - w / 2 for x in xs], cc, width=w, color=COMCAT, edgecolor=GROUND, linewidth=2,
       label="USGS ComCat (Ms until the mid-1980s, then Mw)", zorder=2)
ax.bar([x + w / 2 for x in xs], gc, width=w, color=GCMT, edgecolor=GROUND, linewidth=2,
       label="Global CMT (Mw, one method throughout)", zorder=2)

for i in (0, len(starts) - 1):
    ax.text(i - w / 2, cc[i] + 1.2, str(cc[i]), ha="center", color=INK, fontsize=8.5)
    ax.text(i + w / 2, gc[i] + 1.2, str(gc[i]), ha="center", color=INK, fontsize=8.5)
ax.annotate("sized on Ms, no deep M7 seen", xy=(-w / 2, cc[0] + 5), xytext=(-0.45, 80),
            color=DIM, fontsize=8, ha="left",
            arrowprops=dict(arrowstyle="-", color=DIM, linewidth=0.8))

ax.set_xticks(list(xs))
ax.set_xticklabels(labels)
ax.set_ylim(0, 112)
ax.set_ylabel("earthquakes of magnitude ≥ 7", color=DIM, fontsize=9)
ax.tick_params(colors=DIM, labelsize=9, length=0)
ax.grid(True, axis="y", color=GRID, linewidth=0.6, zorder=0)
for side in ax.spines.values():
    side.set_visible(False)
ax.legend(loc="upper left", frameon=False, labelcolor=INK, fontsize=8.5)
ax.set_title("Magnitude-7 earthquakes per five years, counted with two rulers",
             color=INK, fontsize=11, loc="left", pad=12)
ax.text(0, -0.12, "USGS ComCat count service, fetched 2026-09-11 · Global CMT catalog 1976–2025 · "
        "untilnextsession.com/research/earthquakes/",
        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)
