"""Synchronization clock storage."""

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.sync_clock import SyncClock
from wled_controller.utils import get_logger

logger = get_logger(__name__)


class SyncClockStore(BaseSqliteStore[SyncClock]):
    _table_name = "sync_clocks"
    _entity_name = "Sync clock"

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

    # Backward-compatible aliases
    get_all_clocks = BaseSqliteStore.get_all
    get_clock = BaseSqliteStore.get
    delete_clock = BaseSqliteStore.delete

    def create_clock(
        self,
        name: str,
        speed: float = 1.0,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
    ) -> SyncClock:
        self._check_name_unique(name)
        cid = f"sc_{uuid.uuid4().hex[:8]}"
        now = datetime.now(timezone.utc)

        clock = SyncClock(
            id=cid,
            name=name,
            speed=max(0.1, min(10.0, speed)),
            created_at=now,
            updated_at=now,
            description=description,
            tags=tags or [],
        )

        self._items[cid] = clock
        self._save_item(cid, clock)
        logger.info(f"Created sync clock: {name} ({cid}, speed={clock.speed})")
        return clock

    def update_clock(
        self,
        clock_id: str,
        name: Optional[str] = None,
        speed: Optional[float] = None,
        description: Optional[str] = None,
        tags: Optional[List[str]] = None,
    ) -> SyncClock:
        clock = self.get(clock_id)

        if name is not None:
            self._check_name_unique(name, exclude_id=clock_id)
            clock.name = name
        if speed is not None:
            clock.speed = max(0.1, min(10.0, speed))
        if description is not None:
            clock.description = description
        if tags is not None:
            clock.tags = tags

        clock.updated_at = datetime.now(timezone.utc)
        self._save_item(clock_id, clock)
        logger.info(f"Updated sync clock: {clock_id}")
        return clock
