from __future__ import annotations

from functools import lru_cache

from pydantic import field_validator
from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    bot_token: str = ""
    admin_ids: str = ""
    currency: str = "$"
    support_url: str = ""
    channel_url: str = ""
    referral_percent: int = 10
    database_url: str = "sqlite+aiosqlite:///./shop.db"
    # CryptoBot (@CryptoBot) — Crypto Pay API. Leave token empty to disable.
    crypto_pay_token: str = ""
    crypto_pay_asset: str = "USDT"
    crypto_pay_api_url: str = "https://pay.crypt.bot/api"

    model_config = SettingsConfigDict(
        env_file=".env", env_file_encoding="utf-8", extra="ignore"
    )

    @field_validator("admin_ids", mode="before")
    @classmethod
    def _normalize_admin_ids(cls, value: object) -> str:
        if value is None:
            return ""
        if isinstance(value, (list, tuple)):
            return ",".join(str(item) for item in value)
        return str(value)

    @property
    def crypto_enabled(self) -> bool:
        return bool(self.crypto_pay_token.strip())

    @property
    def admin_id_list(self) -> list[int]:
        result: list[int] = []
        for chunk in self.admin_ids.split(","):
            chunk = chunk.strip()
            if chunk.isdigit():
                result.append(int(chunk))
        return result


@lru_cache(maxsize=1)
def get_settings() -> Settings:
    return Settings()
