"""Audit plotly's built-in discrete colour sequences."""

from statistics import median

from a11yviz._rules import check_level, contrast_ratio


def plotly_sequences(bg: str = "#ffffff", level: str = "AA") -> list[dict]:
    """WCAG contrast statistics for each plotly built-in colour sequence.

    One row per sequence with ``name``, ``n``, ``min_ratio``,
    ``median_ratio``, ``n_pass``, ``pct_pass``. Sorted by ``pct_pass``
    descending. ``bg`` is the reference background hex. ``level`` picks
    the contrast threshold (4.5 for AA, 7 for AAA).
    """
    threshold = 7 if check_level(level) == "AAA" else 4.5
    rows = [_audit_one(name, cols, bg, threshold)
            for name, cols in _sequences.items()]
    return sorted(rows, key=lambda r: -r["pct_pass"])


def _audit_one(name, cols, bg, threshold):
    ratios = [contrast_ratio(c, bg) for c in cols]
    n_pass = sum(r >= threshold for r in ratios)
    return {
        "name":         name,
        "n":            len(cols),
        "min_ratio":    round(min(ratios), 2),
        "median_ratio": round(median(ratios), 2),
        "n_pass":       n_pass,
        "pct_pass":     round(100 * n_pass / len(cols), 1),
    }


_sequences = {
    "Plotly":  ["#636EFA", "#EF553B", "#00CC96", "#AB63FA", "#FFA15A",
                "#19D3F3", "#FF6692", "#B6E880", "#FF97FF", "#FECB52"],
    "D3":      ["#1F77B4", "#FF7F0E", "#2CA02C", "#D62728", "#9467BD",
                "#8C564B", "#E377C2", "#7F7F7F", "#BCBD22", "#17BECF"],
    "G10":     ["#3366CC", "#DC3912", "#FF9900", "#109618", "#990099",
                "#0099C6", "#DD4477", "#66AA00", "#B82E2E", "#316395"],
    "T10":     ["#4C78A8", "#F58518", "#E45756", "#72B7B2", "#54A24B",
                "#EECA3B", "#B279A2", "#FF9DA6", "#9D755D", "#BAB0AC"],
    "Vivid":   ["#E58606", "#5D69B1", "#52BCA3", "#99C945", "#CC61B0",
                "#24796C", "#DAA51B", "#2F8AC4", "#764E9F", "#ED645A",
                "#CC3A8E", "#A5AA99"],
    "Bold":    ["#7F3C8D", "#11A579", "#3969AC", "#F2B701", "#E73F74",
                "#80BA5A", "#E68310", "#008695", "#CF1C90", "#F97B72",
                "#4B4B8F", "#A5AA99"],
    "Pastel":  ["#66C5CC", "#F6CF71", "#F89C74", "#DCB0F2", "#87C55F",
                "#9EB9F3", "#FE88B1", "#C9DB74", "#8BE0A4", "#B497E7",
                "#D3B484", "#B3B3B3"],
}
