"""Command-line entry point. Only `execute --no-dry-run` changes anything, and only through Radarr/Sonarr.""" from __future__ import annotations import asyncio import json from pathlib import Path from typing import Annotated import typer from rich.console import Console from rich.table import Table from plexreaper import __version__ from plexreaper.config import Config, load_config from plexreaper.execute import build_plan, close_clients, load_indexes, open_clients, run_plan from plexreaper.ledger import Ledger from plexreaper.models import Candidate, ScanResult from plexreaper.pipeline import disk_usage, scan from plexreaper.sources.arr import ArrClient from plexreaper.sources.plex import PlexClient from plexreaper.sources.tautulli import TautulliDB app = typer.Typer(no_args_is_help=True, add_completion=False, help="Evidence-first Plex library pruning.") console = Console() class Ctx: def __init__(self, cfg: Config) -> None: self.cfg = cfg def ledger(self) -> Ledger: return Ledger(self.cfg.ledger_path) @app.callback() def main( ctx: typer.Context, config: Annotated[Path | None, typer.Option("--config", "-c", help="Path to plex-reaper.toml")] = None, state: Annotated[Path | None, typer.Option(help="Ledger database path (overrides config)")] = None, cache: Annotated[Path | None, typer.Option(help="Inventory cache path (overrides config)")] = None, ) -> None: cfg = load_config(config) if state: cfg.state.ledger = str(state) if cache: cfg.state.cache = str(cache) ctx.obj = Ctx(cfg) @app.command() def version() -> None: console.print(f"plex-reaper {__version__}") @app.command() def check(ctx: typer.Context) -> None: """Test Plex, each Tautulli database, and the disk path.""" cfg: Config = ctx.obj.cfg if cfg.plex.token: try: ident = asyncio.run(_identity(cfg)) console.print(f"[green]plex[/] {cfg.plex.url} version {ident.get('version', '?')}") except Exception as exc: # noqa: BLE001 console.print(f"[red]plex[/] {cfg.plex.url} {exc}") else: console.print("[yellow]plex[/] PLEX_TOKEN not set") for tc in cfg.tautulli: try: info = TautulliDB(tc.name, tc.db).check() console.print( f"[green]tautulli[/] {tc.name} {info['sessions']} sessions {info['first']:%Y-%m-%d} → {info['last']:%Y-%m-%d}" ) except Exception as exc: # noqa: BLE001 console.print(f"[red]tautulli[/] {tc.name} {exc}") for a in cfg.arr: if not a.api_key: console.print(f"[yellow]{a.type}[/] {a.name} {a.env_prefix}_API_KEY not set") continue try: info = asyncio.run(_arr_status(a)) console.print(f"[green]{a.type}[/] {a.name} v{info['version']} profiles: {', '.join(info['profiles'])}") except Exception as exc: # noqa: BLE001 console.print(f"[red]{a.type}[/] {a.name} {exc}") console.print("[green]tmdb[/] key set" if cfg.tmdb.api_key else "[yellow]tmdb[/] TMDB_API_KEY not set (optional)") d = disk_usage(cfg.disk_path) if d: console.print(f"[green]disk[/] {d.path} {d.free_bytes / 1024**4:.2f} TB free of {d.total_bytes / 1024**4:.1f} TB") console.print(f"ledger {cfg.ledger_path}\ncache {cfg.cache_path}") async def _arr_status(a) -> dict: async with ArrClient(a) as client: status = await client.status() profiles = await client.profiles() return {"version": status.get("version", "?"), "profiles": list(profiles.values())} async def _identity(cfg: Config) -> dict: async with PlexClient(cfg.plex.url, cfg.plex.token) as plex: return await plex.identity() @app.command() def libraries(ctx: typer.Context) -> None: """List Plex library sections.""" cfg: Config = ctx.obj.cfg async def go() -> list: async with PlexClient(cfg.plex.url, cfg.plex.token) as plex: return await plex.libraries() t = Table("id", "name", "type") for lib in asyncio.run(go()): t.add_row(str(lib.id), lib.name, lib.type) console.print(t) def _run_scan(ctx: typer.Context, refresh: bool) -> tuple[ScanResult, Ledger]: ledger = ctx.obj.ledger() return scan(ctx.obj.cfg, refresh=refresh, ledger=ledger), ledger def candidate_dict(c: Candidate) -> dict: return { "guid": c.title.guid, "rating_key": c.title.rating_key, "kind": c.title.kind, "title": c.title.title, "year": c.title.year, "library": c.title.library_name, "size_gb": round(c.title.size_gb, 2), "added_at": c.title.added_at.isoformat(), "score": c.score, "why": c.why, "flags": c.breakdown.flags, "protected": c.protected, "decision": c.decision, "external_ids": c.title.external_ids, "signals": [s.model_dump() for s in c.breakdown.signals], "evidence": c.evidence.model_dump(mode="json"), } @app.command("scan") def scan_cmd( ctx: typer.Context, as_json: Annotated[bool, typer.Option("--json", help="Emit JSON instead of a table")] = False, limit: Annotated[int, typer.Option(help="Rows to show (0 = all)")] = 50, min_score: Annotated[int, typer.Option(help="Hide candidates below this score")] = 0, refresh: Annotated[bool, typer.Option(help="Ignore the inventory cache")] = False, include_kept: Annotated[bool, typer.Option("--all", help="Include titles already decided 'keep'")] = False, ) -> None: """Score the library and print the top candidates.""" result, _ = _run_scan(ctx, refresh) rows = [c for c in result.candidates if c.score >= min_score and (include_kept or c.decision != "keep")] if limit: rows = rows[:limit] if as_json: typer.echo(json.dumps({"scanned_at": result.scanned_at.isoformat(), "candidates": [candidate_dict(c) for c in rows]}, indent=1)) return t = Table("score", "size", "age", "kind", "title", "library", "why", "decision") for c in rows: t.add_row( str(c.score), f"{c.title.size_gb:.1f}G", f"{(result.scanned_at - c.title.added_at).days / 365:.1f}y", c.title.kind, f"{c.title.title} ({c.title.year or '?'})", c.title.library_name, c.why, c.decision or "", ) console.print(t) tot = result.totals() console.print(f"{int(tot['titles'])} titles, {tot['gb'] / 1024:.1f} TB scanned; {int(tot['marked'])} marked to reap ({tot['marked_gb']:.0f} GB)") @app.command() def tui( ctx: typer.Context, refresh: Annotated[bool, typer.Option(help="Ignore the inventory cache")] = False, export: Annotated[Path, typer.Option(help="Where the review screen writes marked items")] = Path("reap-list.json"), ) -> None: """Review candidates interactively.""" from plexreaper.tui.app import ReaperApp result, ledger = _run_scan(ctx, refresh) ReaperApp(result, ledger, cfg=ctx.obj.cfg, export_path=export).run() @app.command() def decisions( ctx: typer.Context, action: Annotated[str | None, typer.Option(help="keep | reap | downgrade | protect")] = None, ) -> None: """Show the ledger.""" ledger = ctx.obj.ledger() t = Table("action", "kind", "title", "score", "size", "updated") for r in ledger.rows(action): size = f"{(r['size_bytes'] or 0) / 1024**3:.1f}G" t.add_row(r["action"], r["kind"], r["title"], str(r["score"] or ""), size, r["updated_at"]) console.print(t) @app.command() def export( ctx: typer.Context, out: Annotated[Path, typer.Argument(help="JSON file to write")] = Path("reap-list.json"), ) -> None: """Write every title marked 'reap' or 'downgrade' to a JSON file (phase 2 consumes this).""" result, _ = _run_scan(ctx, refresh=False) marked = [candidate_dict(c) for c in result.candidates if c.decision in ("reap", "downgrade")] out.write_text(json.dumps({"exported_at": result.scanned_at.isoformat(), "items": marked}, indent=1), encoding="utf-8") console.print(f"wrote {len(marked)} items to {out}") async def _plan_and_run(cfg: Config, candidates: list[Candidate], ledger: Ledger, *, dry_run: bool, yes: bool): clients = open_clients(cfg) try: indexes = await load_indexes(clients) plan = await build_plan(cfg, candidates, clients, indexes) t = Table("action", "title", "arr", "files", "size", "plan") for p in plan: t.add_row(p.action, f"{p.title} ({p.year or '?'})", p.arr or "", str(len(p.files)), f"{p.size_gb:.1f}G", p.describe()) console.print(t) doable = [p for p in plan if p.ok] console.print(f"{len(doable)} of {len(plan)} executable; {sum(p.size_gb for p in doable):.1f} GB") if not doable: return [] if dry_run: console.print("[yellow]dry run: nothing changed. Re-run with --no-dry-run to execute.[/yellow]") elif not yes and not typer.confirm(f"Delete files for {len(doable)} title(s) through Radarr/Sonarr?", default=False): console.print("aborted") return [] outcomes = await run_plan(plan, clients, indexes, ledger, dry_run=dry_run) if not dry_run: for o in outcomes: if o.item.ok: console.print(f"[{'green' if o.ok else 'red'}]{'done' if o.ok else 'FAILED'}[/] {o.item.title}: {o.detail}") return outcomes finally: await close_clients(clients) @app.command() def execute( ctx: typer.Context, dry_run: Annotated[bool, typer.Option("--dry-run/--no-dry-run", help="Plan only (default) or act")] = True, yes: Annotated[bool, typer.Option("--yes", help="Skip the confirmation prompt")] = False, only: Annotated[str | None, typer.Option(help="reap | downgrade")] = None, limit: Annotated[int, typer.Option(help="Act on at most this many titles, largest first (0 = all)")] = 0, ) -> None: """Act on every title marked 'reap' or 'downgrade' in the ledger, through Radarr/Sonarr.""" result, ledger = _run_scan(ctx, refresh=False) marked = [c for c in result.candidates if c.decision in ("reap", "downgrade") and (only is None or c.decision == only)] if limit: marked = sorted(marked, key=lambda c: -c.title.size_bytes)[:limit] if not marked: console.print("nothing marked") return asyncio.run(_plan_and_run(ctx.obj.cfg, marked, ledger, dry_run=dry_run, yes=yes)) @app.command() def executions( ctx: typer.Context, all_: Annotated[bool, typer.Option("--all", help="Include dry runs")] = False, ) -> None: """What has actually been executed.""" t = Table("at", "ok", "action", "title", "arr", "size", "detail") for r in ctx.obj.ledger().executions(include_dry_runs=all_): t.add_row( r["at"], "✔" if r["ok"] else "✘", r["action"] + (" (dry)" if r["dry_run"] else ""), r["title"], r["arr"] or "", f"{(r['size_bytes'] or 0) / 1024**3:.1f}G", (r["detail"] or "")[:70], ) console.print(t) @app.command() def retarget( ctx: typer.Context, arr: Annotated[str, typer.Option(help="arr instance name from config")], from_profile: Annotated[str, typer.Option("--from", help="current quality profile name")], to_profile: Annotated[str, typer.Option("--to", help="new quality profile name")], ended_only: Annotated[bool, typer.Option("--ended-only", help="Sonarr: only series with status 'ended'")] = False, dry_run: Annotated[bool, typer.Option("--dry-run/--no-dry-run")] = True, yes: Annotated[bool, typer.Option("--yes")] = False, ) -> None: """Move every title on one quality profile to another. Files are not touched; future grabs follow the new profile.""" cfg: Config = ctx.obj.cfg a = next((x for x in cfg.arr if x.name == arr), None) if a is None: raise typer.BadParameter(f"unknown arr instance {arr!r}") async def go() -> None: async with ArrClient(a) as client: from plexreaper.sources.arr import load_index index = await load_index(client) src, dst = index.profile_id(from_profile), index.profile_id(to_profile) if src is None or dst is None: missing = from_profile if src is None else to_profile raise typer.BadParameter(f"profile {missing!r} not found in {arr}; have: {', '.join(index.profiles.values())}") items = [i for i in index.items if int(i.get("qualityProfileId") or 0) == src] if ended_only: items = [i for i in items if i.get("status") == "ended"] size = sum(int(i.get("sizeOnDisk") or (i.get("statistics") or {}).get("sizeOnDisk") or 0) for i in items) console.print(f"{len(items)} titles on {from_profile!r}{' (ended)' if ended_only else ''}, {size / 1024**4:.1f} TB on disk → {to_profile!r}") if not items: return if dry_run: console.print("[yellow]dry run: nothing changed. Re-run with --no-dry-run to apply.[/yellow]") return if not yes and not typer.confirm("Change the quality profile on all of them? (no files are touched)", default=False): console.print("aborted") return await client.bulk_set_profile([int(i["id"]) for i in items], dst) console.print(f"[green]retargeted {len(items)} titles[/green]") asyncio.run(go()) @app.command("mark-4k") def mark_4k( ctx: typer.Context, arr: Annotated[str, typer.Option(help="arr instance name from config")] = "sonarr", ended_only: Annotated[bool, typer.Option("--ended-only/--all")] = True, min_gb: Annotated[float, typer.Option(help="Only titles holding at least this many GB above 1080p")] = 20.0, limit: Annotated[int, typer.Option(help="Mark at most this many, largest first (0 = all)")] = 0, dry_run: Annotated[bool, typer.Option("--dry-run/--no-dry-run", help="List only, or write 'downgrade' decisions")] = True, ) -> None: """Find titles holding files above 1080p and mark them 'downgrade' in the ledger (execute acts on them).""" cfg: Config = ctx.obj.cfg a = next((x for x in cfg.arr if x.name == arr), None) if a is None: raise typer.BadParameter(f"unknown arr instance {arr!r}") result, ledger = _run_scan(ctx, refresh=False) by_tvdb = {c.title.external_ids.get("tvdb"): c for c in result.candidates if c.title.external_ids.get("tvdb")} by_tmdb = {c.title.external_ids.get("tmdb"): c for c in result.candidates if c.title.external_ids.get("tmdb")} async def go() -> list[tuple[dict, int, int, Candidate | None, str | None, str]]: async with ArrClient(a) as client: from plexreaper.sources.arr import load_index index = await load_index(client) items = [i for i in index.items if not ended_only or a.type == "radarr" or i.get("status") == "ended"] sem = asyncio.Semaphore(8) async def measure(i: dict): async with sem: files = await client.files(i) above = sum(int(f["size"]) for f in files if int(f.get("resolution") or 0) > 1080) return i, above, len(files) rows = [] for i, above, nfiles in await asyncio.gather(*(measure(i) for i in items)): if above < min_gb * 1024**3: continue cand = by_tvdb.get(str(i.get("tvdbId"))) if a.type == "sonarr" else by_tmdb.get(str(i.get("tmdbId"))) why = None prof = index.profiles.get(int(i.get("qualityProfileId") or 0), "?") if cand is None: why = "not in the Plex scan" elif cand.protected: why = f"protected ({cand.protected})" elif index.profile_id(a.downgrade_target(prof)) is None: why = f"downgrade target {a.downgrade_target(prof)!r} not found" rows.append((i, above, nfiles, cand, why, prof)) rows.sort(key=lambda r: -r[1]) return rows[:limit] if limit else rows rows = asyncio.run(go()) t = Table("above 1080p", "files", "status", "title", "profile", "mark") marked = 0 for i, above, nfiles, cand, why, prof_name in rows: mark = why or ("would mark" if dry_run else "marked") if cand is not None and why is None and not dry_run: ledger.set(cand.title.guid, "downgrade", kind=cand.title.kind, title=cand.title.title, score=cand.score, size_bytes=above) marked += 1 t.add_row(f"{above / 1024**3:.0f}G", str(nfiles), str(i.get("status") or ""), f"{i.get('title')} ({i.get('year') or '?'})", prof_name, mark) console.print(t) total = sum(r[1] for r in rows if r[4] is None) console.print(f"{sum(1 for r in rows if r[4] is None)} markable, {total / 1024**4:.2f} TB above 1080p" + ("" if dry_run else f"; marked {marked}")) if dry_run: console.print("[yellow]dry run: run with --no-dry-run to write 'downgrade' decisions, then `execute --only downgrade --limit N`.[/yellow]")