"""
cvd_check.py — see your figure the way colour-blind readers and greyscale printers do.

Hu Lab · https://hulab.pages.dev/en/guides/scientific-figure-colours/
Requires: pip install numpy pillow matplotlib colorspacious

    python cvd_check.py Fig2.png
    -> writes Fig2_cvd_check.png with four panels:
       original | protanopia (red-blind) | deuteranopia (green-blind) | greyscale
"""
import sys
import os
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image
from colorspacious import cspace_convert

path = sys.argv[1]
img = Image.open(path).convert("RGB")
if max(img.size) > 1600:                       # keep it fast for large TIFFs
    img.thumbnail((1600, 1600))
rgb = np.asarray(img).astype(float) / 255.0

def simulate(kind):
    out = cspace_convert(rgb, {"name": "sRGB1+CVD", "cvd_type": kind, "severity": 100}, "sRGB1")
    return np.clip(out, 0, 1)

grey = np.asarray(img.convert("L")).astype(float) / 255.0
panels = [("original", rgb), ("protanopia (simulated)", simulate("protanomaly")),
          ("deuteranopia (simulated)", simulate("deuteranomaly")), ("greyscale print", grey)]

fig, axes = plt.subplots(2, 2, figsize=(10, 10 * img.height / img.width + 0.6), layout="constrained")
for ax, (name, data) in zip(axes.flat, panels):
    ax.imshow(data, cmap="gray" if data.ndim == 2 else None, vmin=0, vmax=1)
    ax.set_title(name, fontsize=11)
    ax.axis("off")
out = os.path.splitext(path)[0] + "_cvd_check.png"
fig.savefig(out, dpi=150, facecolor="white")
print("saved", out)
