"""
In-memory кэш настроек бота с синхронизацией с БД.

При первом обращении загружает все настройки из bot_settings.
При set() обновляет и БД, и кэш.
"""
import asyncio
from typing import Optional, Dict
from sqlalchemy import select
from app.database import async_session
from app.models import BotSetting


class SettingsCache:
    def __init__(self):
        self._cache: dict[str, str] = {}
        self._loaded = False
        self._lock = asyncio.Lock()

    async def _load(self):
        async with self._lock:
            if self._loaded:
                return
            async with async_session() as db:
                result = await db.execute(select(BotSetting))
                rows = result.scalars().all()
                self._cache = {row.key: row.value or "" for row in rows}
                self._loaded = True

    async def get(self, key: str, default: str = "") -> str:
        if not self._loaded:
            await self._load()
        return self._cache.get(key, default)

    async def set(self, key: str, value: str) -> bool:
        async with async_session() as db:
            result = await db.execute(select(BotSetting).where(BotSetting.key == key))
            setting = result.scalar_one_or_none()
            if setting:
                setting.value = value
            else:
                db.add(BotSetting(key=key, value=value))
            await db.commit()
        self._cache[key] = value
        return True

    async def get_all(self) -> Dict[str, str]:
        if not self._loaded:
            await self._load()
        return dict(self._cache)

    def invalidate(self):
        self._loaded = False


settings_cache = SettingsCache()
