"""Color vision deficiency audit for the exercise figures.

Reads every color the figure code states, groups the colors each function uses
together, simulates deuteranopia, protanopia and tritanopia, and reports pairs
that collapse toward each other. Also samples the matplotlib colormaps the code
names and reports how much of each ramp's spread survives each simulation.

Simulation uses the Machado, Oliveira and Fernandes (2009) severity-1 matrices,
which is the method matplotlib's own accessibility guidance cites.

usage: python cvd_audit.py <toolkit_dir>
"""
import re
import sys
from pathlib import Path

import numpy as np

M = {
    "deuteranopia": np.array([[0.367322, 0.860646, -0.227968],
                              [0.280085, 0.672501, 0.047413],
                              [-0.011820, 0.042940, 0.968881]]),
    "protanopia": np.array([[0.152286, 1.052583, -0.204868],
                            [0.114503, 0.786281, 0.099216],
                            [-0.003882, -0.048116, 1.051998]]),
    "tritanopia": np.array([[1.255528, -0.076749, -0.178779],
                            [-0.078411, 0.930809, 0.147602],
                            [0.004733, 0.691367, 0.303900]]),
}
HEX = re.compile(r'"(#[0-9a-fA-F]{6})"')
CMAP = re.compile(r'cmap="([A-Za-z_]+)"|get_cmap\("([A-Za-z_]+)"')


def srgb_to_linear(c):
    c = c / 255.0
    return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)


def linear_to_lab(rgb):
    m = np.array([[0.4124, 0.3576, 0.1805],
                  [0.2126, 0.7152, 0.0722],
                  [0.0193, 0.1192, 0.9505]])
    xyz = rgb @ m.T / np.array([0.95047, 1.0, 1.08883])
    f = np.where(xyz > 0.008856, np.cbrt(xyz), 7.787 * xyz + 16 / 116)
    return np.stack([116 * f[..., 1] - 16,
                     500 * (f[..., 0] - f[..., 1]),
                     200 * (f[..., 1] - f[..., 2])], axis=-1)


def hex_rgb(h):
    return np.array([int(h[i:i + 2], 16) for i in (1, 3, 5)], float)


def simulate(rgb, kind):
    lin = srgb_to_linear(rgb)
    return np.clip(lin @ M[kind].T, 0, 1)


def de(a, b):
    return float(np.linalg.norm(linear_to_lab(a) - linear_to_lab(b)))


def functions(text):
    """Split source into (name, body) for each top-level function."""
    out, cur, name = [], [], "module"
    for line in text.split("\n"):
        m = re.match(r"^def ([A-Za-z_]+)", line)
        if m:
            out.append((name, "\n".join(cur)))
            name, cur = m.group(1), []
        cur.append(line)
    out.append((name, "\n".join(cur)))
    return out


def main():
    tk = Path(sys.argv[1])
    print("PAIRS THAT COLLAPSE UNDER SIMULATED COLOR VISION DEFICIENCY")
    print("Reported where two colors used in one figure fall within a CIE76")
    print("distance of 18, which is roughly the limit of easy discrimination.")
    print("=" * 74)
    flagged = 0
    for f in sorted(tk.glob("*.py")):
        text = f.read_text(encoding="utf-8")
        for fname, body in functions(text):
            cols = sorted(set(HEX.findall(body)))
            cols = [c for c in cols
                    if c.lower() not in ("#ffffff", "#000000", "#666666",
                                         "#444444", "#999999", "#d9d9d9",
                                         "#e8e8e8", "#f6f7f9", "#111820",
                                         "#333333", "#d6e4f0", "#8c510a")]
            if len(cols) < 2:
                continue
            for kind in M:
                sim = {c: simulate(hex_rgb(c), kind) for c in cols}
                for i, a in enumerate(cols):
                    for b in cols[i + 1:]:
                        d0 = de(srgb_to_linear(hex_rgb(a)),
                                srgb_to_linear(hex_rgb(b)))
                        d1 = de(sim[a], sim[b])
                        if d1 < 18 and d0 >= 18:
                            print(f"{f.name}:{fname}  {a} and {b}  "
                                  f"normal dE {d0:.0f} -> {kind} dE {d1:.0f}")
                            flagged += 1
    print(f"\npairs flagged: {flagged}")

    print("\nCOLORMAPS NAMED IN THE CODE")
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    seen = set()
    for f in sorted(tk.glob("*.py")):
        for m in CMAP.finditer(f.read_text(encoding="utf-8")):
            name = m.group(1) or m.group(2)
            if name in seen:
                continue
            seen.add(name)
            try:
                cm = plt.get_cmap(name)
            except ValueError:
                continue
            ramp = (np.array([cm(x)[:3] for x in np.linspace(0, 1, 9)]) * 255)
            rows = []
            for kind in M:
                sim = [simulate(c, kind) for c in ramp]
                worst = min(de(sim[i], sim[i + 1]) for i in range(len(sim) - 1))
                rows.append(f"{kind[:5]} {worst:4.1f}")
            normal = min(de(srgb_to_linear(ramp[i]), srgb_to_linear(ramp[i + 1]))
                         for i in range(len(ramp) - 1))
            print(f"  {name:12} smallest step between neighboring classes: "
                  f"normal {normal:4.1f} | " + " | ".join(rows))


if __name__ == "__main__":
    main()
