"""Loader for the WCAG rules YAML — same source of truth as a11yviz (R)."""

from functools import lru_cache
from importlib import resources

import yaml


@lru_cache(maxsize=1)
def load_rules() -> dict:
    text = resources.files("a11yviz").joinpath("_rules.yaml").read_text(encoding="utf-8")
    return yaml.safe_load(text)


def check_level(level: str) -> str:
    return level.upper()


def relative_luminance(hex_color: str) -> float:
    hex_color = hex_color.lstrip("#")
    rgb = [int(hex_color[i : i + 2], 16) / 255 for i in (0, 2, 4)]
    lin = [c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4 for c in rgb]
    return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2]


def contrast_ratio(fg: str, bg: str) -> float:
    l1, l2 = relative_luminance(fg), relative_luminance(bg)
    hi, lo = max(l1, l2), min(l1, l2)
    return (hi + 0.05) / (lo + 0.05)
