"""Color parsing shared by drawing code (``#RGB``, ``#RRGGBB``, ``#RRGGBBAA``, ``{"cmyk": [c,m,y,k]}``)."""

from __future__ import annotations

from functools import lru_cache
from typing import Any

RGB = tuple[float, float, float]
CMYK = tuple[float, float, float, float]


@lru_cache(maxsize=1024)
def _parse_hex(value: str) -> tuple[RGB, float]:
    s = value.strip().lstrip("#")
    if len(s) in (3, 4):
        s = "".join(ch * 2 for ch in s)
    try:
        r, g, b = int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16)
        a = int(s[6:8], 16) / 255 if len(s) >= 8 else 1.0
    except (ValueError, IndexError):
        return (0.0, 0.0, 0.0), 1.0
    return (r / 255, g / 255, b / 255), a


def parse_color(value: Any) -> tuple[RGB, float, CMYK | None]:
    """Return (rgb 0..1, alpha 0..1, cmyk 0..1 or None)."""
    if isinstance(value, dict) and isinstance(value.get("cmyk"), (list, tuple)) and len(value["cmyk"]) == 4:
        c, m, y, k = (max(0.0, min(100.0, float(v))) / 100 for v in value["cmyk"])
        rgb = ((1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k))
        return rgb, float(value.get("alpha", 1.0)), (c, m, y, k)
    if isinstance(value, str) and value:
        rgb, a = _parse_hex(value)
        return rgb, a, None
    return (0.0, 0.0, 0.0), 1.0, None
