"""Configuration management: settings from .env / environment variables. Standard library only (no python-dotenv). Known keys: - ``LIMESURVEY_BASE_URL`` — e.g. https://example.com/index.php?r=admin/remotecontrol - ``LIMESURVEY_USERNAME`` — RemoteControl user - ``LIMESURVEY_PASSWORD`` — password (or API token) - ``LIMESURVEY_TIMEOUT_SECONDS`` — optional, default 30 - ``LIMESURVEY_OWNER_ID`` — optional, filter by owner - ``LIMESURVEY_GROUP_ID`` — optional, filter by group - ``LIMESURVEY_VERIFY_SSL`` — optional, default true; ``false`` ONLY for test instances with a wrong/self-signed certificate (never production) Precedence (highest first): explicit parameters > environment variables > .env file. Usage: >>> cfg = LsConfig.from_dotenv(".env") # from .env + os.environ >>> cfg = LsConfig.from_env() # environment only >>> cfg = LsConfig.from_dotenv(".env", timeout=60) # parameter wins >>> cfg = LsConfig(base_url=..., username=..., password=...) # direct """ from __future__ import annotations import os from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path from typing import Any # LsConfig field name -> environment variable _ENV_KEYS: dict[str, str] = { "base_url": "LIMESURVEY_BASE_URL", "username": "LIMESURVEY_USERNAME", "password": "LIMESURVEY_PASSWORD", "timeout": "LIMESURVEY_TIMEOUT_SECONDS", "owner_id": "LIMESURVEY_OWNER_ID", "group_id": "LIMESURVEY_GROUP_ID", "verify_ssl": "LIMESURVEY_VERIFY_SSL", } _REQUIRED_FIELDS: tuple[str, ...] = ("base_url", "username", "password") DEFAULT_TIMEOUT = 30 def _strip_quotes(value: str) -> str: """Strip a pair of surrounding single or double quotes.""" if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'): return value[1:-1] return value def parse_dotenv(path: str | Path) -> dict[str, str]: """Parse a .env file into a ``dict``. Rules: ``KEY=value`` (split on the first ``=``). Empty lines and lines starting with ``#`` are ignored. Surrounding quotes around the value are removed. """ values: dict[str, str] = {} for raw_line in Path(path).read_text(encoding="utf-8").splitlines(): line = raw_line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) key = key.strip() if not key: continue values[key] = _strip_quotes(value.strip()) return values def load_dotenv(path: str | Path, *, override: bool = False) -> dict[str, str]: """Load a .env file into ``os.environ``. By default an already-set environment variable wins (``setdefault``); with ``override=True`` the file wins. Returns the loaded pairs. """ loaded = parse_dotenv(path) for key, value in loaded.items(): if override: os.environ[key] = value else: os.environ.setdefault(key, value) return loaded def _to_int(value: Any) -> int | None: """Safe conversion to int; ``None`` for empty/invalid values.""" if value is None: return None text = str(value).strip() if not text: return None try: return int(text) except ValueError: return None def _collect(environ: Mapping[str, str], file_values: Mapping[str, str]) -> dict[str, Any]: """Map environment variables (these win) and .env values to field names.""" merged: dict[str, Any] = {} for field, env_key in _ENV_KEYS.items(): if env_key in environ: merged[field] = environ[env_key] elif env_key in file_values: merged[field] = file_values[env_key] return merged @dataclass(frozen=True) class LsConfig: """Configuration for the LimeSurvey RemoteControl API. Required: ``base_url``, ``username``, ``password``. Optional: ``timeout`` (seconds, default 30), ``owner_id``, ``group_id``, ``verify_ssl`` (default True). """ base_url: str username: str password: str timeout: int = DEFAULT_TIMEOUT owner_id: int | None = None group_id: int | None = None verify_ssl: bool = True @classmethod def from_env(cls, environ: Mapping[str, str] | None = None, **overrides: Any) -> LsConfig: """Build an ``LsConfig`` from environment variables (default ``os.environ``).""" if environ is None: environ = os.environ return cls._build(_collect(environ, {}), overrides) @classmethod def from_dotenv( cls, path: str | Path = ".env", environ: Mapping[str, str] | None = None, **overrides: Any, ) -> LsConfig: """Build an ``LsConfig`` from a .env file. Precedence: explicit parameters > environment variables > .env file. Raises ``FileNotFoundError`` if ``path`` does not exist, and ``ValueError`` if ``BASE_URL`` or credentials are missing. """ env_path = Path(path) if not env_path.is_file(): raise FileNotFoundError(f".env file not found: {env_path}") if environ is None: environ = os.environ return cls._build(_collect(environ, parse_dotenv(env_path)), overrides) @classmethod def _build(cls, values: Mapping[str, Any], overrides: Mapping[str, Any]) -> LsConfig: unknown = sorted(set(overrides) - set(_ENV_KEYS)) if unknown: raise TypeError(f"Unknown LsConfig parameter(s): {', '.join(unknown)}") merged: dict[str, Any] = dict(values) for field, value in overrides.items(): if value is not None: merged[field] = value missing = [_ENV_KEYS[field] for field in _REQUIRED_FIELDS if not str(merged.get(field, "")).strip()] if missing: raise ValueError( "Missing required LimeSurvey configuration: " + ", ".join(missing) + " — set these in the .env file, as environment variables, " "or pass them as parameters." ) base_url = str(merged["base_url"]).strip() if not base_url.startswith(("http://", "https://")): raise ValueError( f"LIMESURVEY_BASE_URL must start with http:// or https://, got: {base_url!r}" ) timeout_raw = str(merged.get("timeout", "")).strip() if timeout_raw: timeout = _to_int(timeout_raw) if timeout is None or timeout <= 0: raise ValueError( f"LIMESURVEY_TIMEOUT_SECONDS must be a positive integer, got: {timeout_raw!r}" ) else: timeout = DEFAULT_TIMEOUT owner_raw = str(merged.get("owner_id", "")).strip() group_raw = str(merged.get("group_id", "")).strip() owner_id = _to_int(owner_raw) if owner_raw else None group_id = _to_int(group_raw) if group_raw else None if owner_raw and owner_id is None: raise ValueError(f"LIMESURVEY_OWNER_ID must be an integer, got: {owner_raw!r}") if group_raw and group_id is None: raise ValueError(f"LIMESURVEY_GROUP_ID must be an integer, got: {group_raw!r}") verify_raw = str(merged.get("verify_ssl", "")).strip().lower() if verify_raw in ("", "1", "true", "yes", "on"): verify_ssl = True elif verify_raw in ("0", "false", "no", "off"): verify_ssl = False else: raise ValueError(f"LIMESURVEY_VERIFY_SSL must be true/false, got: {verify_raw!r}") return cls( base_url=base_url, username=str(merged["username"]).strip(), password=str(merged["password"]), timeout=timeout, owner_id=owner_id, group_id=group_id, verify_ssl=verify_ssl, )