from __future__ import annotations

from pathlib import Path
from typing import Optional

from pydantic_settings import BaseSettings, SettingsConfigDict

_backend_root = Path(__file__).resolve().parents[2]
_repo_root = _backend_root.parent


class Settings(BaseSettings):
    model_config = SettingsConfigDict(
        env_file=(
            _backend_root / ".env",
            _repo_root / ".env",
        ),
        env_file_encoding="utf-8",
        extra="ignore",
    )

    line_channel_secret: str = ""
    line_channel_access_token: str = ""
    app_base_url: str = ""
    line_default_room_id: str = "demo-room-01"
    join_token_ttl_seconds: int = 60 * 30
    audience_session_ttl_seconds: int = 60 * 60 * 12
    audience_session_active_window_seconds: int = 45
    reset_runtime_state_on_startup: bool = True
    hihaho_api_base: str = ""
    hihaho_api_key: str = ""
    hihaho_branch_path: str = "/interactive/resolution"
    hihaho_player_url: str = (
        "https://player.hihaho.com/embed/899f8135-e718-493e-b96d-516ac57263ae?api=true"
    )
    database_url: str = "sqlite+aiosqlite:///./data.db"
    cors_origins: str = (
        "http://127.0.0.1:8000,http://localhost:8000,"
        "http://127.0.0.1:5500,http://localhost:5500,"
        "http://127.0.0.1:8080,http://localhost:8080"
    )
    static_dir: str = ""
    host_api_key: str = ""

    @property
    def cors_origins_list(self) -> list[str]:
        return [o.strip() for o in self.cors_origins.split(",") if o.strip()]

    @property
    def static_path(self) -> Optional[Path]:
        if not self.static_dir:
            return None
        p = Path(self.static_dir)
        return p if p.is_dir() else None


settings = Settings()
