"""中控配置。"""

from __future__ import annotations

from functools import lru_cache
from pathlib import Path

from pydantic_settings import BaseSettings, SettingsConfigDict


def _control_root() -> Path:
    # control/backend/app/config.py -> control/
    return Path(__file__).resolve().parents[2]


def _repo_root() -> Path:
    return Path(__file__).resolve().parents[3]


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

    control_auth_username: str = "admin"
    control_auth_password: str = "admin123"
    control_auth_secret: str = "change-me-control-secret-please"
    control_auth_token_version: int = 1
    control_token_ttl_sec: int = 7 * 24 * 3600
    control_db_path: str = ""
    control_poll_interval_sec: int = 8
    control_sse_interval_sec: float = 1.0
    control_sse_probe_timeout_sec: float = 2.5
    control_http_timeout_sec: float = 12.0
    control_port: int = 5160
    # "1"/"0"：局域网客户端免密登录
    control_lan_auth_bypass: str = "0"

    @property
    def db_path(self) -> Path:
        if self.control_db_path.strip():
            return Path(self.control_db_path)
        return _control_root() / "data" / "control.db"

    @property
    def lan_auth_bypass(self) -> bool:
        return self.control_lan_auth_bypass.strip().lower() in (
            "1",
            "true",
            "yes",
            "on",
        )

    @property
    def is_default_credentials(self) -> bool:
        return (
            self.control_auth_username.strip() == "admin"
            and self.control_auth_password == "admin123"
        )


@lru_cache
def get_control_settings() -> ControlSettings:
    return ControlSettings()
