"""Pixel-level scatter overlap check (WCAG Success Criterion 1.3.1)."""

import numpy as np


def check_overlap(fig):
    ax = fig.axes[0] if hasattr(fig, "axes") else fig
    if not ax.collections:
        return {"total": 0, "obscured": 0, "fraction": 0.0,
                "recommendation": "no scatter points to evaluate"}

    coords = np.vstack([c.get_offsets() for c in ax.collections])
    fig_obj = ax.figure
    fig_obj.canvas.draw()
    pixels = ax.transData.transform(coords).astype(np.int64)
    keys = pixels[:, 0] * 100000 + pixels[:, 1]
    _, counts = np.unique(keys, return_counts=True)
    obscured = int(np.sum(counts[counts > 1]))
    total = int(len(keys))
    fraction = round(obscured / total, 3)
    rec = ("no alpha needed (no pixel-level occlusion; SC 1.3.1 satisfied)"
           if obscured == 0
           else f"{fraction:.0%} of points share a pixel; if alpha is added, "
                "verify composited contrast >= 3:1 via "
                "check_palette(alpha=...) (SC 1.4.11)")
    return {"total": total, "obscured": obscured,
            "fraction": fraction, "recommendation": rec}
