"""Visualize a palette with WCAG contrast overlay."""

from a11yviz._rules import check_level, contrast_ratio, relative_luminance
from a11yviz.palette import palette as _palette


def show_palette(name: str = "dark2_8", bg: str = "#ffffff", level: str = "AA"):
    """Render swatches of a built-in palette with contrast overlay.

    Each swatch is annotated with hex, contrast ratio vs ``bg``, and
    pass/fail status for ``level``. Returns the matplotlib Figure.
    """
    import matplotlib.pyplot as plt

    level = check_level(level)
    cols = _palette(name)
    ratios = [contrast_ratio(c, bg) for c in cols]
    threshold = 4.5 if level == "AA" else 7.0
    statuses = [level if r >= threshold else "todo" for r in ratios]

    fig, ax = plt.subplots(figsize=(len(cols) * 1.2, 1.6))
    for i, (c, r, s) in enumerate(zip(cols, ratios, statuses)):
        ax.add_patch(plt.Rectangle((i, 0), 0.95, 1, color=c))
        text_col = "#000000" if relative_luminance(c) > 0.5 else "#ffffff"
        ax.text(
            i + 0.475, 0.5, f"{c}\n{r:.1f}:1\n{s}",
            color=text_col, ha="center", va="center",
            fontsize=8, linespacing=1.1,
        )
    ax.set_xlim(0, len(cols))
    ax.set_ylim(0, 1)
    ax.set_aspect("equal")
    ax.set_title(f"{name} palette  (vs {bg}, {level})", fontsize=10)
    ax.set_xticks([])
    ax.set_yticks([])
    for spine in ax.spines.values():
        spine.set_visible(False)
    return fig
