"""MQTT source 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.mqtt_source import MQTTSource
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class MQTTSourceStore(BaseSqliteStore[MQTTSource]):
    """Persistent storage for MQTT sources (broker connections)."""

    _table_name = "mqtt_sources"
    _entity_name = "MQTT source"

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

    # Backward-compatible aliases
    get_all_sources = BaseSqliteStore.get_all
    get_source = BaseSqliteStore.get
    delete_source = BaseSqliteStore.delete

    def create_source(
        self,
        name: str,
        broker_host: str,
        broker_port: int = 1883,
        username: str = "",
        password: str = "",
        client_id: str = "ledgrab",
        base_topic: str = "ledgrab",
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
    ) -> MQTTSource:
        if not broker_host:
            raise ValueError("broker_host is required")

        self._check_name_unique(name)

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

        source = MQTTSource(
            id=sid,
            name=name,
            created_at=now,
            updated_at=now,
            broker_host=broker_host,
            broker_port=broker_port,
            username=username,
            password=password,
            client_id=client_id,
            base_topic=base_topic,
            description=description,
            tags=tags or [],
        )

        self._items[sid] = source
        self._save_item(sid, source)
        logger.info(f"Created MQTT source: {name} ({sid})")
        return source

    def update_source(
        self,
        source_id: str,
        name: Optional[str] = None,
        broker_host: Optional[str] = None,
        broker_port: Optional[int] = None,
        username: Optional[str] = None,
        password: Optional[str] = None,
        client_id: Optional[str] = None,
        base_topic: Optional[str] = None,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
    ) -> MQTTSource:
        existing = self.get(source_id)

        if name is not None and name != existing.name:
            self._check_name_unique(name)

        updated = MQTTSource(
            id=existing.id,
            name=name if name is not None else existing.name,
            created_at=existing.created_at,
            updated_at=datetime.now(timezone.utc),
            broker_host=broker_host if broker_host is not None else existing.broker_host,
            broker_port=broker_port if broker_port is not None else existing.broker_port,
            username=username if username is not None else existing.username,
            password=password if password is not None else existing.password,
            client_id=client_id if client_id is not None else existing.client_id,
            base_topic=base_topic if base_topic is not None else existing.base_topic,
            description=description if description is not None else existing.description,
            tags=tags if tags is not None else existing.tags,
        )

        self._items[source_id] = updated
        self._save_item(source_id, updated)
        logger.info(f"Updated MQTT source: {updated.name} ({source_id})")
        return updated
