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

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

from wled_controller.storage.key_colors_output_target import KeyColorRectangle


@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)

    def to_dict(self) -> dict:
        """Convert to dictionary."""
        return {
            "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,
        }

    @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", []),
        )
