"""Phase 2 execution: resolve marked titles into Radarr/Sonarr, plan, then act. Dry run by default.""" from __future__ import annotations from pydantic import BaseModel, Field from plexreaper.config import Config from plexreaper.ledger import Ledger from plexreaper.models import Candidate from plexreaper.sources.arr import ArrClient, ArrIndex, load_index EXECUTABLE = ("reap", "downgrade") class PlanItem(BaseModel): guid: str kind: str title: str year: int | None library: str action: str size_bytes: int = 0 arr: str | None = None arr_id: int | None = None files: list[dict] = Field(default_factory=list) profile_from: str | None = None profile_to: str | None = None kept_files: int = 0 # downgrade: files already at or below the target resolution, left alone error: str | None = None @property def ok(self) -> bool: return self.error is None @property def size_gb(self) -> float: return self.size_bytes / 1024**3 def describe(self) -> str: if self.error: return f"skip: {self.error}" n = len(self.files) if self.action == "reap": return f"unmonitor in {self.arr}, delete {n} file(s), {self.size_gb:.1f} GB; entry kept" kept = f", keep {self.kept_files} at/below target" if self.kept_files else "" swap = ( f"enforce profile {self.profile_to} ceiling" if (self.profile_from or "").lower() == (self.profile_to or "").lower() else f"profile {self.profile_from} → {self.profile_to}" ) return f"{self.arr}: {swap}, delete {n} file(s) ({self.size_gb:.1f} GB){kept}, search" class Outcome(BaseModel): item: PlanItem dry_run: bool ok: bool detail: str def open_clients(cfg: Config) -> dict[str, ArrClient]: return {a.name: ArrClient(a) for a in cfg.arr if a.api_key} async def close_clients(clients: dict[str, ArrClient]) -> None: for c in clients.values(): await c.aclose() async def load_indexes(clients: dict[str, ArrClient]) -> dict[str, ArrIndex]: return {name: await load_index(c) for name, c in clients.items()} async def build_plan( cfg: Config, candidates: list[Candidate], clients: dict[str, ArrClient], indexes: dict[str, ArrIndex], ) -> list[PlanItem]: plan: list[PlanItem] = [] for c in candidates: if c.decision not in EXECUTABLE: continue t = c.title item = PlanItem( guid=t.guid, kind=t.kind, title=t.title, year=t.year, library=t.library_name, action=c.decision, size_bytes=t.size_bytes, ) plan.append(item) if c.protected: item.error = f"protected ({c.protected})" continue arr_cfg = cfg.arr_for_library(t.library_id) if arr_cfg is None: item.error = f"no arr instance configured for library {t.library_name!r}" continue if arr_cfg.name not in clients: item.error = f"{arr_cfg.env_prefix}_API_KEY not set" continue if (arr_cfg.type == "radarr") != (t.kind == "movie"): item.error = f"{arr_cfg.name} is {arr_cfg.type} but title is a {t.kind}" continue index = indexes[arr_cfg.name] found = index.resolve(t) if found is None: item.error = f"not found in {arr_cfg.name} (ids {t.external_ids or 'none'})" continue item.arr, item.arr_id = arr_cfg.name, int(found["id"]) item.files = await clients[arr_cfg.name].files(found) item.size_bytes = sum(int(f.get("size") or 0) for f in item.files) or t.size_bytes if c.decision == "downgrade": item.profile_from = index.profiles.get(int(found.get("qualityProfileId") or 0), "?") target = arr_cfg.downgrade_target(item.profile_from) pid = index.profile_id(target) if pid is None: item.error = f"profile {target!r} not found in {arr_cfg.name}" continue item.profile_to = index.profiles[pid] limit = index.max_resolution.get(pid, 0) if not limit and item.profile_from.lower() == item.profile_to.lower(): item.error = f"profile {item.profile_to!r} has no resolution ceiling; nothing to enforce" continue if limit: above = [f for f in item.files if int(f.get("resolution") or 0) > limit] item.kept_files = len(item.files) - len(above) item.files = above item.size_bytes = sum(int(f.get("size") or 0) for f in above) if not above: item.error = f"no files above {limit}p (nothing to downgrade)" continue if not item.files: item.error = "no files on disk (nothing to do)" return plan async def run_plan( plan: list[PlanItem], clients: dict[str, ArrClient], indexes: dict[str, ArrIndex], ledger: Ledger, *, dry_run: bool = True, ) -> list[Outcome]: outcomes: list[Outcome] = [] for p in plan: if not p.ok: outcomes.append(Outcome(item=p, dry_run=dry_run, ok=False, detail=p.error or "skipped")) continue detail = p.describe() ok = True if not dry_run: try: await _act(p, clients[p.arr or ""], indexes[p.arr or ""]) except Exception as exc: # noqa: BLE001 — record, keep going with the rest of the plan ok, detail = False, f"{type(exc).__name__}: {exc}" ledger.record_execution( guid=p.guid, kind=p.kind, title=p.title, action=p.action, arr=p.arr, arr_id=p.arr_id, files=p.files, size_bytes=p.size_bytes, dry_run=dry_run, ok=ok, detail=detail, ) if ok and not dry_run: ledger.clear(p.guid, reason="executed") outcomes.append(Outcome(item=p, dry_run=dry_run, ok=ok, detail=detail)) return outcomes async def _act(p: PlanItem, client: ArrClient, index: ArrIndex) -> None: assert p.arr_id is not None item = {"id": p.arr_id} if p.action == "reap": await client.unmonitor(item) for f in p.files: await client.delete_file(int(f["id"])) return pid = index.profile_id(p.profile_to or "") assert pid is not None await client.set_profile(item, pid) for f in p.files: await client.delete_file(int(f["id"])) await client.search(p.arr_id)