"""Configuration loading from a .env file or the environment.""" from __future__ import annotations import os from dataclasses import dataclass from pathlib import Path DEFAULT_ENV_FILE = Path(__file__).resolve().parent / ".env" DEFAULT_POLL_INTERVAL_SECONDS = 15 * 60 HTTP_TIMEOUT_SECONDS = 20.0 MEETINGS_PAGE_LIMIT = 200 DEFAULT_STATE_FILE = "state.json" class ConfigError(Exception): """Raised when required configuration is missing or invalid.""" def _unquote(value: str) -> str: if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'): return value[1:-1] return value def _load_env_file(path: Path) -> None: """Load KEY=VALUE pairs; real environment variables take precedence.""" if not path.is_file(): return try: with path.open("r", encoding="utf-8") as fh: for raw in fh: line = raw.strip() if not line or line.startswith("#"): continue key, sep, value = line.partition("=") if not sep: continue key = key.strip() if not key or key in os.environ: continue os.environ[key] = _unquote(value.strip()) except OSError: return def _env_str(name: str, *, required: bool = False, default: str = "") -> str: value = os.getenv(name) if value is None or value.strip() == "": if required: raise ConfigError(f"environment variable {name} is required") return default return value.strip() def _env_int(name: str, default: int) -> int: raw = os.getenv(name) if raw is None or raw.strip() == "": return default try: return int(raw.strip()) except ValueError as exc: raise ConfigError(f"environment variable {name} must be an integer, got {raw!r}") from exc def _ensure_socks_support() -> None: try: import socks # noqa: F401 except ImportError as exc: raise ConfigError( "SOCKS5_PROXY is set but PySocks is not installed; " "install it with `pip install requests[socks]`" ) from exc @dataclass(frozen=True) class Config: api_base_url: str api_login: str api_password: str bot_token: str chat_id: str poll_interval_seconds: int = DEFAULT_POLL_INTERVAL_SECONDS state_file: str = DEFAULT_STATE_FILE socks5_proxy: str = "" def load_config(env_file: Path | None = None) -> Config: _load_env_file(env_file or DEFAULT_ENV_FILE) poll_interval = _env_int("BOT_POLL_INTERVAL_SECONDS", DEFAULT_POLL_INTERVAL_SECONDS) if poll_interval <= 0: raise ConfigError("BOT_POLL_INTERVAL_SECONDS must be greater than zero") socks5_proxy = _env_str("SOCKS5_PROXY") if socks5_proxy: _ensure_socks_support() return Config( api_base_url=_env_str("API_BASE_URL", required=True).rstrip("/"), api_login=_env_str("API_LOGIN", required=True), api_password=_env_str("API_PASSWORD", required=True), bot_token=_env_str("TELEGRAM_BOT_TOKEN", required=True), chat_id=_env_str("TELEGRAM_CHAT_ID", required=True), poll_interval_seconds=poll_interval, state_file=_env_str("BOT_STATE_FILE", default=DEFAULT_STATE_FILE), socks5_proxy=socks5_proxy, )