"""Rebuild the December 1 TidyTuesday figure with Python 3 and matplotlib.

Run: python chart.py
Output: country-coverage.png, in the current directory.
"""
import csv
import hashlib
import io
from collections import Counter
from urllib.request import urlopen

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

SOURCE = (
    "https://raw.githubusercontent.com/rfordatascience/tidytuesday/"
    "c608a60d1798bbcd73ac50bb573e470444a18c28/data/2026/2026-12-01/"
    "catholic_miracles.csv"
)
SHA256 = "ec1218568adf9e23a9296be05d60a017509de2b30d353b72255d5cc2899a4089"


def summarize():
    with urlopen(SOURCE, timeout=30) as response:
        raw = response.read()
    if hashlib.sha256(raw).hexdigest() != SHA256:
        raise ValueError("Source CSV does not match the December 1 snapshot")
    totals, recorded = Counter(), Counter()
    for record in csv.DictReader(io.StringIO(raw.decode("utf-8"), newline="")):
        category = record["category"].strip()
        totals[category] += 1
        if record["country"].strip() not in ("", "NA"):
            recorded[category] += 1
    ordered = sorted(totals, key=lambda k: (-recorded[k] / totals[k], k))
    return [(k, recorded[k], totals[k]) for k in ordered]


def render(rows):
    ink, accent, guide = "#172b2b", "#176a66", "#e2e9e6"
    fig = plt.figure(figsize=(8, 8), dpi=135, facecolor="white")
    fig.text(.07, .937, "Country coverage by category", color=ink,
             fontsize=27, fontweight="bold", va="top")
    fig.text(.07, .87, "Share of records with a country in the December 1, 2026\n"
             "TidyTuesday dataset on documented Catholic miracles.",
             color=ink, linespacing=1.4, fontsize=15, va="top")
    ax = fig.add_axes([.07, .170, .86, .595])
    ax.set_axis_off()
    ax.set(xlim=(0, 100), ylim=(-.60, len(rows)-.4))
    for index, (label, known, total) in enumerate(rows):
        y = len(rows) - 1 - index
        percent = 100 * known / total
        ax.barh(y-.17, 100, height=.22, color=guide)
        ax.barh(y-.17, percent, height=.22, color=accent)
        ax.text(0, y+.15, label, fontsize=15, va="center", color=ink)
        ax.text(100, y+.15, f"{known:,}/{total:,}   ·   {percent:.1f}%",
                fontsize=14, fontweight="bold", ha="right", va="center", color=ink)
    fig.text(.07, .135, f"{sum(n for _, n, _ in rows):,} of "
             f"{sum(n for _, _, n in rows):,} records include a country.",
             color=ink, fontsize=15, fontweight="bold")
    fig.text(.07, .078, "Source: Data Science Learning Community · "
             "curated by Tony Galvan.\nEmpty values and the literal NA count as missing.",
             color="#35494a", linespacing=1.45, fontsize=11)
    fig.savefig("country-coverage.png", facecolor="white")
    plt.close(fig)


if __name__ == "__main__":
    render(summarize())
