"""matplotlib accessible theme — context manager + rcParams updater."""

from contextlib import contextmanager

from a11yviz._rules import check_level, load_rules


def _rc_for(level: str, dark: bool = False) -> dict:
    level = check_level(level)
    rules = load_rules()
    fz = rules["font_size"][level]
    fg = "#dee2e6" if dark else "#222222"
    bg = "#2d2d2d" if dark else "#ffffff"
    grid = "#495057" if dark else "#e5e5e5"
    return {
        "font.family": "sans-serif",
        "font.sans-serif": ["Roboto", "Helvetica", "Arial", "DejaVu Sans"],
        "font.size": fz["body"],
        "axes.titlesize": fz["title"],
        "axes.labelsize": fz["body"] + 1,
        "xtick.labelsize": fz["body"],
        "ytick.labelsize": fz["body"],
        "legend.title_fontsize": fz["legend"] + 1,
        "legend.fontsize": fz["legend"],
        "axes.facecolor": bg,
        "figure.facecolor": bg,
        "savefig.facecolor": bg,
        "text.color": fg,
        "axes.edgecolor": fg,
        "axes.labelcolor": fg,
        "xtick.color": fg,
        "ytick.color": fg,
        "axes.titlecolor": fg,
        "grid.color": grid,
        "grid.linewidth": 0.5,
    }


@contextmanager
def theme(level: str = "AA", dark: bool = False):
    """Apply WCAG-aligned matplotlib rcParams within a `with` block.

    Example:
        >>> with a11yviz.theme(level="AA"):
        ...     fig, ax = plt.subplots()
        ...     ax.plot(x, y)
    """
    rc = _rc_for(level, dark)
    try:
        import matplotlib as mpl
    except ImportError as e:
        raise ImportError(
            "theme() requires matplotlib. Install with: pip install a11yviz[matplotlib]"
        ) from e

    saved = {k: mpl.rcParams[k] for k in rc if k in mpl.rcParams}
    mpl.rcParams.update(rc)
    try:
        yield
    finally:
        mpl.rcParams.update(saved)
