"""Pattern template storage using SQLite."""

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

from wled_controller.storage.base_sqlite_store import BaseSqliteStore
from wled_controller.storage.database import Database
from wled_controller.storage.pattern_template import KeyColorRectangle, PatternTemplate
from wled_controller.utils import get_logger

logger = get_logger(__name__)


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

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

    _table_name = "pattern_templates"
    _entity_name = "Pattern template"

    def __init__(self, db: Database):
        super().__init__(db, PatternTemplate.from_dict)
        self._ensure_initial_template()

    # Backward-compatible aliases
    get_all_templates = BaseSqliteStore.get_all
    get_template = BaseSqliteStore.get
    delete_template = BaseSqliteStore.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_item(template_id, template)
        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_item(template_id, template)

        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_item(template_id, template)

        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 targets that reference this template (legacy, always empty)."""
        return []
