"""Scene preset storage using SQLite."""

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.scene_preset import ScenePreset, TargetSnapshot
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class ScenePresetStore(BaseSqliteStore[ScenePreset]):
    """Persistent storage for scene presets."""

    _table_name = "scene_presets"
    _entity_name = "Scene preset"

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

    # Backward-compatible aliases
    get_preset = BaseSqliteStore.get
    delete_preset = BaseSqliteStore.delete

    def get_all_presets(self) -> List[ScenePreset]:
        """Get all presets sorted by order field."""
        return sorted(self._items.values(), key=lambda p: p.order)

    # Override get_all to also sort by order for consistency
    def get_all(self) -> List[ScenePreset]:
        return self.get_all_presets()

    def create_preset(self, preset: ScenePreset) -> ScenePreset:
        self._check_name_unique(preset.name)

        self._items[preset.id] = preset
        self._save_item(preset.id, preset)
        logger.info(f"Created scene preset: {preset.name} ({preset.id})")
        return preset

    def update_preset(
        self,
        preset_id: str,
        name: Optional[str] = None,
        description: Optional[str] = None,
        order: Optional[int] = None,
        targets: Optional[List[TargetSnapshot]] = None,
        tags: Optional[List[str]] = None,
    ) -> ScenePreset:
        preset = self.get(preset_id)

        if name is not None:
            self._check_name_unique(name, exclude_id=preset_id)
            preset.name = name
        if description is not None:
            preset.description = description
        if order is not None:
            preset.order = order
        if targets is not None:
            preset.targets = targets
        if tags is not None:
            preset.tags = tags

        preset.updated_at = datetime.now(timezone.utc)
        self._save_item(preset_id, preset)
        logger.info(f"Updated scene preset: {preset_id}")
        return preset

    def recapture_preset(self, preset_id: str, preset: ScenePreset) -> ScenePreset:
        """Replace snapshot data of an existing preset (recapture current state)."""
        existing = self.get(preset_id)

        existing.targets = preset.targets
        existing.updated_at = datetime.now(timezone.utc)
        self._save_item(preset_id, existing)
        logger.info(f"Recaptured scene preset: {preset_id}")
        return existing
