"""Mirror a locally-reachable Plex library into Siftlode's own catalog (plex_* tables). Playback is from the local physical file, so this only mirrors METADATA + the physical-media facts (codecs/container/path) needed to browse, search, and later play. It reuses Plex's own codec info (no ffprobe needed) to classify each item's browser playability. Movies + episodes become playable LEAF rows (plex_items); shows/seasons are mirrored for the drill-down + episode ordering. The sync is a full reconcile of the enabled sections (upsert by rating_key) AND prunes rows for titles that disappeared from Plex: each section diffs the rating_keys it just listed against the ones stored, and deletes the stale ones (their watch-state / playlist links cascade). The prune is guarded on a NON-empty listing — a section that returns zero items is left untouched, so a transient Plex glitch that yields an empty page can't wipe a library (the metadata is cheap to re-sync; an accidental mass-delete is the only real risk). Library-level reconcile (dropping a whole removed section, the dead `enabled` column) is a separate follow-up. Cast + intro/credit markers are fetched lazily on the item-detail/player path (P2), not here. """ from datetime import datetime, timezone from sqlalchemy import func, select from sqlalchemy.orm import Session from app import logs, sysconfig from app.models import PlexCollection, PlexItem, PlexLibrary, PlexSeason, PlexShow from app.plex import detail, people from app.plex.client import PlexClient, PlexError, PlexNotConfigured from app.plex.lookups import by_rating_key log = logs.get_logger(__name__) # Codecs/containers a browser can play in a native