"""Configuration: plex-reaper.toml plus environment / .env for secrets.""" from __future__ import annotations import os import tomllib from pathlib import Path from typing import Literal from pydantic import BaseModel, Field class PlexConfig(BaseModel): url: str = "http://localhost:32400" token: str = "" libraries: list[int] = Field(default_factory=list) # empty = every movie/show library history_prior: bool = True class TautulliConfig(BaseModel): name: str db: str class ArrConfig(BaseModel): """One Radarr or Sonarr instance. The API key comes from env `_API_KEY` (name upper-cased).""" name: str type: Literal["radarr", "sonarr"] url: str api_key: str = "" libraries: list[int] = Field(default_factory=list) # Plex section ids this instance owns # 'downgrade' moves a title from its current quality profile to the mapped one (or the fallback # `downgrade_profile`). A profile with no mapping maps to itself: downgrade then only enforces the # profile's own resolution ceiling, deleting files above it. Names are case-insensitive. downgrade: dict[str, str] = Field(default_factory=dict) downgrade_profile: str = "" def downgrade_target(self, current_profile: str) -> str: for src, dst in self.downgrade.items(): if src.lower() == current_profile.lower(): return dst return self.downgrade_profile or current_profile @property def env_prefix(self) -> str: return self.name.upper().replace("-", "_") class TmdbConfig(BaseModel): api_key: str = "" # env TMDB_API_KEY region: str = "US" providers: list[str] = Field(default_factory=list) # subscribed streaming providers, e.g. ["Netflix"] class EvidenceConfig(BaseModel): admin_user_ids: list[int] = Field(default_factory=list) # empty = Tautulli's is_admin flag qc_window_days: int = 7 full_threshold: float = 85.0 touch_threshold: float = 15.0 class ProtectConfig(BaseModel): genres: list[str] = Field(default_factory=lambda: ["Sport"]) title_patterns: list[str] = Field(default_factory=list) libraries: list[int] = Field(default_factory=list) class Weights(BaseModel): never: float = 30 ghost: float = 5 abandon: float = 8 abandon_cap: int = 3 age_max: float = 15 age_floor_days: int = 365 age_ceiling_days: int = 1460 size_max: float = 15 bloat: float = 5 bloat_gb_per_hour: float = 8.0 lowrate: float = 5 lowrate_threshold: float = 5.0 verylow: float = 10 verylow_threshold: float = 3.0 watched: float = -40 watched_per_user: float = -10 watched_cap: float = -70 recent: float = -20 recent_days: int = 365 prior: float = -25 sibling: float = -15 stalled: float = 10 class StateConfig(BaseModel): ledger: str = "~/.local/state/plex-reaper/ledger.db" cache: str = "~/.cache/plex-reaper/scan.json" cache_ttl_hours: float = 12 class Config(BaseModel): plex: PlexConfig = Field(default_factory=PlexConfig) tautulli: list[TautulliConfig] = Field(default_factory=list) arr: list[ArrConfig] = Field(default_factory=list) tmdb: TmdbConfig = Field(default_factory=TmdbConfig) evidence: EvidenceConfig = Field(default_factory=EvidenceConfig) protect: ProtectConfig = Field(default_factory=ProtectConfig) weights: Weights = Field(default_factory=Weights) state: StateConfig = Field(default_factory=StateConfig) disk_path: str | None = None @property def ledger_path(self) -> Path: return Path(self.state.ledger).expanduser() @property def cache_path(self) -> Path: return Path(self.state.cache).expanduser() def arr_for_library(self, library_id: int) -> ArrConfig | None: return next((a for a in self.arr if library_id in a.libraries), None) def _read_dotenv(path: Path) -> dict[str, str]: """Minimal KEY=VALUE parser; no dependency on python-dotenv.""" values: dict[str, str] = {} if not path.is_file(): return values for raw in path.read_text(encoding="utf-8").splitlines(): line = raw.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, value = line.partition("=") value = value.strip() if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'": value = value[1:-1] values[key.strip()] = value return values def load_config(path: str | Path | None = None, *, env: dict[str, str] | None = None) -> Config: """Load TOML config, then overlay PLEX_URL / PLEX_TOKEN from .env and the environment.""" config_path = Path(path) if path else Path("plex-reaper.toml") data: dict = {} if config_path.is_file(): data = tomllib.loads(config_path.read_text(encoding="utf-8")) cfg = Config.model_validate(data) merged = _read_dotenv(config_path.parent / ".env") merged.update(env if env is not None else os.environ) if merged.get("PLEX_URL"): cfg.plex.url = merged["PLEX_URL"] if merged.get("PLEX_TOKEN"): cfg.plex.token = merged["PLEX_TOKEN"] for arr in cfg.arr: if merged.get(f"{arr.env_prefix}_API_KEY"): arr.api_key = merged[f"{arr.env_prefix}_API_KEY"] if merged.get(f"{arr.env_prefix}_URL"): arr.url = merged[f"{arr.env_prefix}_URL"] if merged.get("TMDB_API_KEY"): cfg.tmdb.api_key = merged["TMDB_API_KEY"] return cfg