"""Parsing helpers for color strings."""

from __future__ import annotations

import re
from typing import Iterable

from .models import Color

_HEX_RE = re.compile(r"^#?(?P<body>[0-9a-fA-F]{3,8})$")


def parse_color(value: str | Color | Iterable[float]) -> Color | None:
    """Parse a CSS-style color string or iterable into a Color."""

    if isinstance(value, Color):
        return value
    if isinstance(value, str):
        match = _HEX_RE.match(value.strip())
        if not match:
            return None
        body = match.group("body")
        if len(body) in {3, 4}:
            body = "".join(ch * 2 for ch in body)
        if len(body) not in {6, 8}:
            return None
        r = int(body[0:2], 16) / 255.0
        g = int(body[2:4], 16) / 255.0
        b = int(body[4:6], 16) / 255.0
        if len(body) == 8:
            a = int(body[6:8], 16) / 255.0
        else:
            a = 1.0
        return Color(r, g, b, a)

    try:
        seq = [float(v) for v in value]
    except Exception:
        return None
    if len(seq) not in (3, 4):
        return None
    r, g, b = seq[:3]
    a = seq[3] if len(seq) == 4 else 1.0
    return Color(r, g, b, a).clamp()


def hex_to_ooxml_rgb(hex_color: str) -> str:
    """Convert a hex color string to OOXML sRGB format.

    Args:
        hex_color: Hex color string (e.g., "#4A90D9" or "4A90D9")

    Returns:
        OOXML-format color string (uppercase hex, no # prefix).
        Returns "000000" if parsing fails.
    """
    color = parse_color(hex_color)
    if color is None:
        return "000000"
    return color.to_ooxml_rgb()


def hex_to_ooxml_argb(hex_color: str) -> str:
    """Convert a hex color string to OOXML ARGB format (for Excel).

    Args:
        hex_color: Hex color string (e.g., "#4A90D9" or "4A90D9")

    Returns:
        OOXML-format ARGB string (uppercase hex, no # prefix).
        Returns "FF000000" if parsing fails.
    """
    color = parse_color(hex_color)
    if color is None:
        return "FF000000"
    return color.to_ooxml_argb()


__all__ = ["parse_color", "hex_to_ooxml_rgb", "hex_to_ooxml_argb"]
