"""Pattern template data model for key color rectangle layouts."""

from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import List, Optional


@dataclass
class KeyColorRectangle:
    """A named rectangle in relative coordinates (0.0 to 1.0)."""

    name: str
    x: float
    y: float
    width: float
    height: float

    def to_dict(self) -> dict:
        return {
            "name": self.name,
            "x": self.x,
            "y": self.y,
            "width": self.width,
            "height": self.height,
        }

    @classmethod
    def from_dict(cls, data: dict) -> "KeyColorRectangle":
        return cls(
            name=data["name"],
            x=float(data.get("x", 0.0)),
            y=float(data.get("y", 0.0)),
            width=float(data.get("width", 1.0)),
            height=float(data.get("height", 1.0)),
        )


@dataclass
class PatternTemplate:
    """Pattern template containing a named layout of key color rectangles."""

    id: str
    name: str
    rectangles: List[KeyColorRectangle]
    created_at: datetime
    updated_at: datetime
    description: Optional[str] = None
    tags: List[str] = field(default_factory=list)
    icon: str = ""
    icon_color: str = ""

    def to_dict(self) -> dict:
        """Convert to dictionary."""
        d: dict = {
            "id": self.id,
            "name": self.name,
            "rectangles": [r.to_dict() for r in self.rectangles],
            "created_at": self.created_at.isoformat(),
            "updated_at": self.updated_at.isoformat(),
            "description": self.description,
            "tags": self.tags,
        }
        if self.icon:
            d["icon"] = self.icon
        if self.icon_color:
            d["icon_color"] = self.icon_color
        return d

    @classmethod
    def from_dict(cls, data: dict) -> "PatternTemplate":
        """Create from dictionary."""
        rectangles = [KeyColorRectangle.from_dict(r) for r in data.get("rectangles", [])]
        return cls(
            id=data["id"],
            name=data["name"],
            rectangles=rectangles,
            created_at=(
                datetime.fromisoformat(data["created_at"])
                if isinstance(data.get("created_at"), str)
                else data.get("created_at", datetime.now(timezone.utc))
            ),
            updated_at=(
                datetime.fromisoformat(data["updated_at"])
                if isinstance(data.get("updated_at"), str)
                else data.get("updated_at", datetime.now(timezone.utc))
            ),
            description=data.get("description"),
            tags=data.get("tags", []),
            icon=data.get("icon", "") or "",
            icon_color=data.get("icon_color", "") or "",
        )
