# core/settings.py
from __future__ import annotations

import structlog

from core.protocol import SettingsAction
from core.store import StateStore
from sdk.interface import PlatformClient, UserSettings

logger = structlog.get_logger(__name__)


class SettingsManager:
    def __init__(self, platform: PlatformClient, store: StateStore) -> None:
        self._platform = platform
        self._store = store

    async def get(self, user_id: str) -> UserSettings:
        cached = await self._store.get(f"settings:{user_id}")
        if cached:
            return UserSettings(**cached)
        settings = await self._platform.get_settings(user_id)
        await self._store.set(f"settings:{user_id}", settings.model_dump())
        return settings

    async def apply(self, user_id: str, action: SettingsAction) -> None:
        await self._platform.update_settings(user_id, action)
        await self._store.delete(f"settings:{user_id}")  # invalidate cache
        logger.info("Settings applied", user_id=user_id, action=action.action)
