"""Shared Plex people helpers: parse cast/crew from rich metadata, persist the full cast onto a movie
or show (cast_names + the people_text search blob + the plex_people headshot cache), and prune
orphaned people. Used by BOTH the info-page lazy enrichment (routes.plex) and the background rich
re-sync (plex.sync), so the two paths never diverge."""

from urllib.parse import quote

from sqlalchemy import text
from sqlalchemy.orm import Session

from app.models import PlexPerson

# Cast/crew photos come from Plex's PUBLIC metadata CDN (no token). We proxy them (host-whitelisted)
# so the user's browser makes no third-party request (privacy + self-host CSP friendliness).
PERSON_IMG_HOST = "https://metadata-static.plex.tv/"


def person_thumb_url(thumb: str | None) -> str | None:
    """Proxied /person-image URL for a Plex CDN headshot, or None when it's missing / off-CDN."""
    t = str(thumb or "")
    return f"/api/plex/person-image?u={quote(t, safe='')}" if t.startswith(PERSON_IMG_HOST) else None


def cast_from_meta(meta: dict, limit: int = 24) -> list[dict]:
    """[{name, role, thumb}] for the cast (Role tags) in a full Plex metadata dict — thumb is the
    proxied person-image URL or None. Shared by the info-page response, the lazy enrichment, and the
    re-sync so the parsing lives in one place."""
    out: list[dict] = []
    for role in (meta.get("Role") or [])[:limit]:
        name = role.get("tag")
        if not name:
            continue
        out.append(
            {"name": name, "role": role.get("role"), "thumb": person_thumb_url(role.get("thumb"))}
        )
    return out


def enrich_row_people(db: Session, row, cast: list[dict]) -> bool:
    """Persist the FULLER cast onto the row's `cast_names` + `people_text`, and cache each cast
    member's headshot in plex_people. The cheap section listing that drives the main sync only carries
    the top ~3 cast, so this — run whenever a rich fetch happens (info-page view + the rich re-sync) —
    is what makes the full displayed cast filterable. Returns True if anything was written (the caller
    commits). Best-effort by contract: never the reason a read 500s."""
    names = list(dict.fromkeys(c["name"] for c in cast if c.get("name")))[:24]
    if not names:
        return False
    dirty = False
    # Grow/refresh cast_names only when the rich set adds names the stored (listing top-3) set lacks —
    # avoid churn and never downgrade a fuller set back to the thin listing.
    if set(names) - set(row.cast_names or []):
        row.cast_names = names
        row.people_text = " ".join(dict.fromkeys(list(row.directors or []) + names)) or None
        dirty = True
    # Headshot cache: upsert name -> proxied thumb (a later fetch fills a prior NULL; names without a
    # whitelisted photo still get a row so a card can show a placeholder).
    existing = {p.name: p for p in db.query(PlexPerson).filter(PlexPerson.name.in_(names))}
    for c in cast:
        nm, th = c.get("name"), c.get("thumb")
        if not nm:
            continue
        p = existing.get(nm)
        if p is None:
            p = PlexPerson(name=nm, photo_thumb=th)
            db.add(p)
            existing[nm] = p
            dirty = True
        elif th and not p.photo_thumb:
            p.photo_thumb = th
            dirty = True
    return dirty


# The person names still referenced by ANY movie/show (cast OR directors). plex_people rows outside
# this set are orphans left by a library removal.
_REFERENCED_PEOPLE_SQL = """
    SELECT jsonb_array_elements_text(cast_names) FROM plex_items WHERE jsonb_typeof(cast_names) = 'array'
    UNION SELECT jsonb_array_elements_text(directors) FROM plex_items WHERE jsonb_typeof(directors) = 'array'
    UNION SELECT jsonb_array_elements_text(cast_names) FROM plex_shows WHERE jsonb_typeof(cast_names) = 'array'
    UNION SELECT jsonb_array_elements_text(directors) FROM plex_shows WHERE jsonb_typeof(directors) = 'array'
"""


def prune_orphan_people(db: Session) -> int:
    """Delete plex_people (headshot cache) rows whose name no longer appears in any movie/show cast or
    directors — orphaned by a library removal. Returns the number pruned. Commits its own work."""
    # `WHERE ref IS NOT NULL` matters: a JSON-null array element surfaces as a SQL NULL in the
    # referenced set, and `name NOT IN (…, NULL)` is NULL (never TRUE) for every row — the classic
    # NOT IN trap that would silently prune nothing. Filtering NULLs out keeps the delete correct.
    res = db.execute(
        text(
            "DELETE FROM plex_people WHERE name NOT IN "
            f"(SELECT ref FROM ({_REFERENCED_PEOPLE_SQL}) AS refs(ref) WHERE ref IS NOT NULL)"
        )
    )
    db.commit()
    return res.rowcount or 0
