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

logger = get_logger(__name__)


class SyncClockStore(BaseJsonStore[SyncClock]):
    _json_key = "sync_clocks"
    _entity_name = "Sync clock"

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

    # Backward-compatible aliases
    get_all_clocks = BaseJsonStore.get_all
    get_clock = BaseJsonStore.get
    delete_clock = BaseJsonStore.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()
        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()
        logger.info(f"Updated sync clock: {clock_id}")
        return clock
