"""Pattern template storage using JSON files."""

import uuid
from datetime import datetime, timezone
from typing import List, Optional

from wled_controller.storage.base_store import BaseJsonStore
from wled_controller.storage.key_colors_output_target import KeyColorRectangle
from wled_controller.storage.pattern_template import PatternTemplate
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class PatternTemplateStore(BaseJsonStore[PatternTemplate]):
    """Storage for pattern templates (rectangle layouts for key color extraction).

    All templates are persisted to the JSON file.
    On startup, if no templates exist, a default one is auto-created.
    """

    _json_key = "pattern_templates"
    _entity_name = "Pattern template"

    def __init__(self, file_path: str):
        super().__init__(file_path, PatternTemplate.from_dict)
        self._ensure_initial_template()

    # Backward-compatible aliases
    get_all_templates = BaseJsonStore.get_all
    get_template = BaseJsonStore.get
    delete_template = BaseJsonStore.delete

    def _ensure_initial_template(self) -> None:
        """Auto-create a default pattern template if none exist."""
        if self._items:
            return

        now = datetime.now(timezone.utc)
        template_id = f"pat_{uuid.uuid4().hex[:8]}"

        template = PatternTemplate(
            id=template_id,
            name="Full Screen",
            rectangles=[
                KeyColorRectangle(name="Full Frame", x=0.0, y=0.0, width=1.0, height=1.0),
            ],
            created_at=now,
            updated_at=now,
            description="Default pattern template with full-frame rectangle",
        )

        self._items[template_id] = template
        self._save()
        logger.info(f"Auto-created initial pattern template: {template.name} ({template_id})")

    def create_template(
        self,
        name: str,
        rectangles: Optional[List[KeyColorRectangle]] = None,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
    ) -> PatternTemplate:
        self._check_name_unique(name)

        if rectangles is None:
            rectangles = []

        template_id = f"pat_{uuid.uuid4().hex[:8]}"
        now = datetime.now(timezone.utc)

        template = PatternTemplate(
            id=template_id,
            name=name,
            rectangles=rectangles,
            created_at=now,
            updated_at=now,
            description=description,
            tags=tags or [],
        )

        self._items[template_id] = template
        self._save()

        logger.info(f"Created pattern template: {name} ({template_id})")
        return template

    def update_template(
        self,
        template_id: str,
        name: Optional[str] = None,
        rectangles: Optional[List[KeyColorRectangle]] = None,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
    ) -> PatternTemplate:
        template = self.get(template_id)

        if name is not None:
            self._check_name_unique(name, exclude_id=template_id)
            template.name = name
        if rectangles is not None:
            template.rectangles = rectangles
        if description is not None:
            template.description = description
        if tags is not None:
            template.tags = tags

        template.updated_at = datetime.now(timezone.utc)
        self._save()

        logger.info(f"Updated pattern template: {template_id}")
        return template

    def get_targets_referencing(self, template_id: str, output_target_store) -> List[str]:
        """Return names of KC targets that reference this template."""
        from wled_controller.storage.key_colors_output_target import KeyColorsOutputTarget

        return [
            target.name for target in output_target_store.get_all_targets()
            if isinstance(target, KeyColorsOutputTarget) and target.settings.pattern_template_id == template_id
        ]
