"""Color-blindness simulation matrices (simplified).

Uses pure-Python 3×3 matrix multiplication — no numpy required.
"""

from __future__ import annotations

from .models import Color


def _mat3x3_mul(
    matrix: tuple[tuple[float, ...], ...], rgb: tuple[float, float, float]
) -> tuple[float, float, float]:
    """Multiply a 3×3 matrix by a 3-element vector."""
    return (
        max(
            0.0,
            min(
                1.0,
                matrix[0][0] * rgb[0] + matrix[0][1] * rgb[1] + matrix[0][2] * rgb[2],
            ),
        ),
        max(
            0.0,
            min(
                1.0,
                matrix[1][0] * rgb[0] + matrix[1][1] * rgb[1] + matrix[1][2] * rgb[2],
            ),
        ),
        max(
            0.0,
            min(
                1.0,
                matrix[2][0] * rgb[0] + matrix[2][1] * rgb[1] + matrix[2][2] * rgb[2],
            ),
        ),
    )


Matrix3x3 = tuple[
    tuple[float, float, float], tuple[float, float, float], tuple[float, float, float]
]


def simulate_color(color: Color, matrix: Matrix3x3) -> Color:
    r, g, b = _mat3x3_mul(matrix, (color.r, color.g, color.b))
    return Color(r, g, b, color.a).clamp()


PROTANOPIA: Matrix3x3 = (
    (0.56667, 0.43333, 0.0),
    (0.55833, 0.44167, 0.0),
    (0.0, 0.24167, 0.75833),
)

DEUTERANOPIA: Matrix3x3 = (
    (0.625, 0.375, 0.0),
    (0.7, 0.3, 0.0),
    (0.0, 0.3, 0.7),
)

TRITANOPIA: Matrix3x3 = (
    (0.95, 0.05, 0.0),
    (0.0, 0.43333, 0.56667),
    (0.0, 0.475, 0.525),
)


def simulate_palette(colors: list[Color]) -> dict[str, list[str]]:
    return {
        "protanopia": [simulate_color(color, PROTANOPIA).to_hex() for color in colors],
        "deuteranopia": [
            simulate_color(color, DEUTERANOPIA).to_hex() for color in colors
        ],
        "tritanopia": [simulate_color(color, TRITANOPIA).to_hex() for color in colors],
    }


__all__ = ["simulate_palette"]
