"""Color domain models for Portal."""

from __future__ import annotations

import os
from datetime import datetime  # noqa: TCH003
from enum import StrEnum

from pydantic import BaseModel, Field, field_validator

from .base import DataResult


class ColorPalette(StrEnum):
    """Available color palettes."""

    DEFAULT = "default"
    HIGH_CONTRAST = "high_contrast"
    COLORBLIND_SAFE = "colorblind_safe"
    PASTEL = "pastel"
    DARK = "dark"


class WorktreeColor(BaseModel):
    """Immutable color definition for worktree identification."""

    name: str = Field(..., description="Human-readable color name")
    hex: str = Field(..., pattern=r"^#[0-9A-Fa-f]{6}$", description="Hex color code")
    rgb: tuple[int, int, int] = Field(..., description="RGB color values")
    hsl: tuple[int, int, int] = Field(..., description="HSL color values")
    emoji: str | None = Field(default=None, description="Optional color emoji")

    # Terminal representations
    ansi_code: str = Field(..., description="ANSI color code")
    ansi_256: int = Field(..., ge=0, le=255, description="256-color terminal code")
    ansi_rgb: str = Field(..., description="True color ANSI escape sequence")

    # Application-specific formats
    iterm_rgb: str = Field(..., description="iTerm RGB format (0.0-1.0)")
    css_var: str = Field(..., description="CSS variable name")

    # Accessibility
    contrast_ratio: float = Field(
        ..., ge=1.0, le=21.0, description="WCAG contrast ratio with white"
    )
    is_dark: bool = Field(..., description="Whether this is a dark color")

    model_config = {"frozen": True, "extra": "forbid"}

    @field_validator("rgb")
    @classmethod
    def validate_rgb(cls, v: tuple[int, int, int]) -> tuple[int, int, int]:
        """Validate RGB values are in valid range."""
        r, g, b = v
        if not all(0 <= val <= 255 for val in (r, g, b)):
            raise ValueError("RGB values must be between 0 and 255")
        return v

    @field_validator("hsl")
    @classmethod
    def validate_hsl(cls, v: tuple[int, int, int]) -> tuple[int, int, int]:
        """Validate HSL values."""
        h, s, lightness = v
        if not (0 <= h <= 360 and 0 <= s <= 100 and 0 <= lightness <= 100):
            raise ValueError("Invalid HSL values")
        return v

    def to_terminal_format(self) -> str:
        """Get appropriate terminal color format based on support."""
        # Check for true color support
        if os.environ.get("COLORTERM") in ["truecolor", "24bit"]:
            return self.ansi_rgb

        # Check for 256 color support
        term = os.environ.get("TERM", "")
        if "256color" in term:
            return f"\033[38;5;{self.ansi_256}m"

        # Fall back to basic ANSI
        return f"\033[{self.ansi_code}m"


class ColorUsageStats(BaseModel):
    """Track color usage for better distribution."""

    color_name: str
    usage_count: int = 0
    last_used: datetime | None = None
    projects: list[str] = Field(default_factory=list)

    model_config = {"extra": "forbid"}


class ColorResult(DataResult[WorktreeColor]):
    """Result of color operations."""

    @classmethod
    def create_success(cls, data: WorktreeColor) -> ColorResult:
        """Create a successful result with color data."""
        return cls(success=True, data=data)


class ColorListResult(DataResult[list[WorktreeColor]]):
    """Result of listing colors."""

    total: int = Field(..., description="Total count of colors")

    @classmethod
    def create_success(cls, data: list[WorktreeColor]) -> ColorListResult:
        """Create a successful result with colors list."""
        return cls(success=True, data=data, total=len(data))

    @property
    def colors(self) -> list[WorktreeColor]:
        """Get the colors list (alias for data)."""
        return self.data or []
