from functools import lru_cache
from pathlib import Path

import platformdirs
from pydantic import Field, HttpUrl, SecretStr, field_validator
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    port: int = 8000
    host: str = "0.0.0.0"  # noqa: S104

    default_data_path: Path = platformdirs.user_data_path(
        "huesoporro",
        ensure_exists=True,
    )
    static_files_path: Path = Field(
        default_factory=lambda: Path(__file__).parent / "static"
    )
    templates_files_path: Path = Field(
        default_factory=lambda: Path(__file__).parent / "templates"
    )
    tts_cache_path: Path = default_data_path / "tts_files"
    db_filepath: Path = default_data_path / "huesoporro.db"
    twitch_client_id: str
    twitch_client_secret: SecretStr
    jwt_secret: SecretStr
    twitch_scopes: list[str] = Field(
        default_factory=lambda: ["channel:bot", "chat:edit", "chat:read"]
    )
    allowed_users: list[str] | str = Field(default_factory=lambda: ["huesoporro"])
    server_hostname: HttpUrl = "http://localhost:8000"  # type: ignore[assignment]

    @staticmethod
    @lru_cache(maxsize=1)
    def get(**data):
        return Settings(**data)  # type: ignore[call-arg] # pydantic-setting magic

    @field_validator("allowed_users")
    @classmethod
    def validate_allowed_users(cls, value: list[str] | str):
        # Convert string to list if necessary
        if isinstance(value, str):
            value = value.split(",")
        return value

    @field_validator("tts_cache_path")
    @classmethod
    def validate_tts_cache_path(cls, value: Path):
        # create path if it doesn't exist
        value.mkdir(parents=True, exist_ok=True)
        return value
