#!/usr/bin/env python3
"""Resolve Jellyfin audio/music-video items and play them locally with mpv."""

from __future__ import annotations

import argparse
import json
import os
import random
import shlex
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any

ENV_FILE = Path.home() / ".config/openchamber/jellyfin/.env"
IPC_SOCKET = Path("/tmp/opencode-jellyfin-mpv.sock")
PLAYABLE_TYPES = {"Audio", "MusicVideo"}
CONTAINER_TYPES = {"MusicAlbum", "MusicArtist", "Playlist", "CollectionFolder", "Folder"}
PLAYABLE_ITEM_TYPES = ",".join(sorted(PLAYABLE_TYPES))


def load_env() -> dict[str, str]:
    values: dict[str, str] = {}
    for raw in ENV_FILE.read_text().splitlines():
        line = raw.strip()
        if not line or line.startswith("#") or "=" not in line:
            continue
        key, value = line.split("=", 1)
        values[key] = value.strip().strip('"').strip("'")
    for key in ("JELLYFIN_URL", "JELLYFIN_API_KEY"):
        if not values.get(key):
            raise SystemExit(f"Missing {key} in {ENV_FILE}")
    values["JELLYFIN_URL"] = values["JELLYFIN_URL"].rstrip("/")
    return values


def auth_header(values: dict[str, str]) -> str:
    username = values.get("JELLYFIN_USERNAME", "opencode")
    return (
        f'MediaBrowser Token="{values["JELLYFIN_API_KEY"]}", '
        f'Client="OpenCode mpv", Device="{username}-mpv", '
        f'DeviceId="opencode-mpv", Version="1.0"'
    )


def mpv_auth_header(values: dict[str, str]) -> str:
    # mpv splits --http-header-fields on commas, so keep this minimal.
    return f'MediaBrowser Token="{values["JELLYFIN_API_KEY"]}"'


def api_get(values: dict[str, str], path: str, params: dict[str, Any] | None = None) -> Any:
    url = values["JELLYFIN_URL"] + path
    if params:
        url += "?" + urllib.parse.urlencode(params)
    request = urllib.request.Request(
        url,
        headers={
            "Authorization": auth_header(values),
            "Accept": "application/json",
        },
    )
    try:
        with urllib.request.urlopen(request, timeout=20) as response:
            return json.load(response)
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode(errors="replace").strip()
        raise SystemExit(f"Jellyfin API error {exc.code} for {path}: {detail}") from exc
    except urllib.error.URLError as exc:
        raise SystemExit(f"Cannot reach Jellyfin at {values['JELLYFIN_URL']}: {exc.reason}") from exc


def user_id(values: dict[str, str]) -> str:
    users = api_get(values, "/Users")
    wanted = values.get("JELLYFIN_USERNAME", "").lower()
    for user in users:
        if user.get("Name", "").lower() == wanted:
            return user["Id"]
    if len(users) == 1:
        return users[0]["Id"]
    names = ", ".join(user.get("Name", "") for user in users)
    raise SystemExit(f"Could not resolve Jellyfin user '{wanted}'. Available: {names}")


def item_details(values: dict[str, str], item_id: str) -> dict[str, Any] | None:
    try:
        return api_get(
            values,
            f"/Items/{urllib.parse.quote(item_id, safe='')}",
            {"UserId": user_id(values)},
        )
    except SystemExit:
        return None


def playable_children(values: dict[str, str], container_id: str) -> list[dict[str, Any]]:
    items = api_get(
        values,
        "/Items",
        {
            "ParentId": container_id,
            "IncludeItemTypes": PLAYABLE_ITEM_TYPES,
            "Recursive": "true",
            "Fields": "MediaSources",
            "Limit": 1000,
        },
    ).get("Items", [])
    return [item for item in items if item.get("Type") in PLAYABLE_TYPES]


def playlist_items(values: dict[str, str], playlist_id: str) -> list[dict[str, Any]]:
    items = api_get(
        values,
        f"/Playlists/{urllib.parse.quote(playlist_id, safe='')}/Items",
        {
            "UserId": user_id(values),
            "Fields": "MediaSources",
            "Limit": 1000,
        },
    ).get("Items", [])
    return [item for item in items if item.get("Type") in PLAYABLE_TYPES]


def search_media(values: dict[str, str], query: str, limit: int) -> list[dict[str, Any]]:
    items = api_get(
        values,
        "/Items",
        {
            "SearchTerm": query,
            "IncludeItemTypes": PLAYABLE_ITEM_TYPES,
            "Recursive": "true",
            "Fields": "MediaSources",
            "Limit": limit,
        },
    ).get("Items", [])
    return [item for item in items if item.get("Type") in PLAYABLE_TYPES]


def resolve_items(values: dict[str, str], args: argparse.Namespace) -> list[tuple[str, str]]:
    resolved: list[tuple[str, str]] = []

    def add_item(item: dict[str, Any]) -> None:
        item_id = item.get("Id")
        kind = item.get("Type")
        if item_id and kind in PLAYABLE_TYPES:
            resolved.append((item_id, kind))

    for raw in args.items:
        for item_id in raw.split(","):
            item_id = item_id.strip()
            if not item_id:
                continue
            details = item_details(values, item_id)
            kind = details.get("Type") if details else None
            if kind in PLAYABLE_TYPES:
                add_item(details or {})
            elif kind in CONTAINER_TYPES:
                for item in playable_children(values, item_id):
                    add_item(item)
            else:
                raise SystemExit(f"Item {item_id} is {kind or 'unknown'}, not playable audio.")

    if args.album:
        for item in playable_children(values, args.album):
            add_item(item)

    if args.playlist:
        for item in playlist_items(values, args.playlist):
            add_item(item)

    if args.search:
        for item in search_media(values, args.search, args.limit):
            add_item(item)

    unique: list[tuple[str, str]] = []
    seen: set[str] = set()
    for item_id, kind in resolved:
        if item_id not in seen:
            seen.add(item_id)
            unique.append((item_id, kind))
    if not unique:
        raise SystemExit(
            "No playable Jellyfin items resolved. Try a track/video ID, --album, --playlist, or --search."
        )
    return unique


def stream_url(values: dict[str, str], item_id: str, kind: str) -> str:
    quoted = urllib.parse.quote(item_id, safe="")
    endpoint = "Audio" if kind == "Audio" else "Videos"
    return f'{values["JELLYFIN_URL"]}/{endpoint}/{quoted}/stream?Static=true'


def mpv_command(
    values: dict[str, str], items: list[tuple[str, str]], args: argparse.Namespace
) -> list[str]:
    auth = mpv_auth_header(values)
    urls = [stream_url(values, item_id, kind) for item_id, kind in items]
    command = [
        "mpv",
        f"--http-header-fields=Authorization: {auth}",
        f"--input-ipc-server={IPC_SOCKET}",
        "--terminal=yes",
    ]
    if not args.video:
        command.append("--no-video")
    if args.loop:
        command.append("--loop-playlist=inf")
    if args.ao:
        command.append(f"--ao={args.ao}")
    if args.volume is not None:
        command.append(f"--volume={args.volume}")
    if args.pause:
        command.append("--pause")
    command.extend(urls)
    return command


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Play Jellyfin audio or music videos locally with mpv"
    )
    parser.add_argument(
        "items",
        nargs="*",
        help="Audio, MusicVideo, album, artist, playlist, or library folder IDs",
    )
    parser.add_argument("--album", help="MusicAlbum ID")
    parser.add_argument("--playlist", help="Playlist ID")
    parser.add_argument(
        "--search", help="Search Jellyfin audio and music videos and play the results"
    )
    parser.add_argument("--limit", type=int, default=20, help="Search result limit")
    parser.add_argument("--volume", type=int, default=100, help="Initial mpv volume, 0-100")
    parser.add_argument("--ao", help="mpv audio output, e.g. pulse, pipewire, alsa")
    parser.add_argument("--pause", action="store_true", help="Start paused")
    parser.add_argument(
        "--video", action="store_true", help="Show video for MusicVideo items (default: audio only)"
    )
    parser.add_argument(
        "--shuffle", action="store_true", help="Play the resolved items in random order"
    )
    parser.add_argument(
        "--loop", action="store_true", help="Repeat the playlist when it finishes"
    )
    parser.add_argument("--dry-run", action="store_true", help="Resolve items but do not start mpv")
    args = parser.parse_args()

    if not any((args.items, args.album, args.playlist, args.search)):
        parser.error("provide at least one item ID, --album, --playlist, or --search")

    values = load_env()
    items = resolve_items(values, args)
    if args.shuffle:
        random.shuffle(items)
    command = mpv_command(values, items, args)

    kinds = ", ".join(sorted({kind for _, kind in items}))
    order = " (shuffled)" if args.shuffle else ""
    print(f"Resolved {len(items)} playable Jellyfin item(s){order}: {kinds}", flush=True)
    print(f"mpv IPC socket: {IPC_SOCKET}", flush=True)
    if args.dry_run:
        redacted = [
            part.replace(mpv_auth_header(values), 'MediaBrowser Token="[redacted]"')
            for part in command
        ]
        print("Command:", shlex.join(redacted), flush=True)
        return

    try:
        IPC_SOCKET.unlink(missing_ok=True)
    except OSError:
        pass
    os.execvp(command[0], command)


if __name__ == "__main__":
    main()
