#compdef plexdo
# SPDX-FileCopyrightText: 2026 SidusNare
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileContributor: Claude Opus 5.5 (AI-generated)
#
# zsh completion for plexdo
#
# Installation:
#   Per user:    cp _plexdo ~/.local/share/zsh/site-functions/
#                (ensure that directory is in $fpath, then: compinit)
#   System-wide: cp _plexdo /usr/local/share/zsh/site-functions/
#
# Completion for user IDs, library IDs, rating keys, playlists, and albums is
# read from the 15-minute cache that the list commands populate, in plex:
# cache_dir or else $XDG_CACHE_HOME/plexdo, by default ~/.cache/plexdo. A
# stale cache is refreshed in the background so completion never blocks; the values shown come from whatever is cached at that moment.

# Some systems ship "python" but not "python3".
_plexdo_python() {
  if (( $+commands[python3] )); then print -r -- python3; else print -r -- python; fi
}

(( $+functions[_plexdo_cache_dir] )) || _plexdo_cache_dir() {
  # Memoised: this reads the config file to honour plex: cache_dir, so it
  # should not run once per completion candidate.
  if [[ -z $_plexdo_cache_resolved ]]; then
    typeset -g _plexdo_cache_resolved
    _plexdo_cache_resolved="$("$(_plexdo_python)" - <<'PYCACHE' 2>/dev/null
import json, os
from pathlib import Path
def xdg(name, fallback):
    value = os.environ.get(name, "")
    if value and Path(value).is_absolute():
        return Path(value)
    return Path(fallback).expanduser()
if os.name == "nt":
    root = os.environ.get("LOCALAPPDATA") or os.environ.get("APPDATA")
    app = Path(root) / "PlexDo" if root else Path.home() / "AppData/Local/PlexDo"
    cfg_path, default = app / "config.yaml", app / "Cache"
else:
    cfg_path = xdg("XDG_CONFIG_HOME", "~/.config") / "plexdo" / "config.yaml"
    default = xdg("XDG_CACHE_HOME", "~/.cache") / "plexdo"
try:
    lines = cfg_path.read_text(encoding="utf-8").splitlines()
except OSError:
    lines = []
# The one value wanted is a scalar directly under plex:, so the file is
# read a line at a time; PyYAML may not be importable from this python.
value, in_plex, dq, sq = "", False, chr(34), chr(39)
for line in lines:
    text = line.strip()
    if not text or text.startswith("#") or text == "---":
        continue
    if line[:1] not in (" ", chr(9)):
        in_plex = text.split(":")[0].strip() == "plex"
        continue
    key, colon, rest = text.partition(":")
    if not (in_plex and colon and key.strip() == "cache_dir"):
        continue
    rest = rest.strip()
    if rest[:1] == dq:
        try:
            rest = json.JSONDecoder().raw_decode(rest)[0]
        except ValueError:
            rest = rest.strip(dq)
    elif rest[:1] == sq and sq in rest[1:]:
        rest = rest[1:rest.rindex(sq)].replace(sq + sq, sq)
    else:
        rest = rest.split(" #")[0].strip()
    value = "" if rest in ("null", "~") else str(rest)
print(Path(os.path.expandvars(value)).expanduser() if value else default)
PYCACHE
)"
  fi
  print -r -- "$_plexdo_cache_resolved"
}

# Return 0 when the cache file exists and is under 15 minutes old.
_plexdo_cache_fresh() {
  local file=$1 now mtime
  [[ -f $file ]] || return 1
  now=$(date +%s)
  mtime=$(stat -c %Y "$file" 2>/dev/null) || mtime=$(stat -f %m "$file" 2>/dev/null) || return 1
  (( now - mtime < 900 ))
}

# Run a plexdo list command in the background purely for its cache side effect.
_plexdo_refresh() {
  local prog=${words[1]:-plexdo}
  ( "$prog" "$@" >/dev/null 2>&1 & ) 2>/dev/null
}

# Emit "value" or "value:description" lines from a JSON cache file.
_plexdo_read_cache() {
  local file=$1 field=$2 desc=$3
  [[ -f $file ]] || return
  python3 - "$file" "$field" "$desc" <<'PY' 2>/dev/null
import json, sys
path, field, desc = sys.argv[1], sys.argv[2], sys.argv[3]
try:
    rows = json.load(open(path, encoding="utf-8"))
except Exception:
    sys.exit(0)
for row in rows:
    value = str(row.get(field, "")).strip()
    if not value:
        continue
    if desc:
        label = str(row.get(desc, "")).strip().replace(":", " ")
        print(f"{value}:{label}" if label else value)
    else:
        print(value)
PY
}

_plexdo_users() {
  local cache="$(_plexdo_cache_dir)/users.json"
  _plexdo_cache_fresh $cache || _plexdo_refresh users-list
  local -a ids titles
  ids=( '0:admin account' ${(f)"$(_plexdo_read_cache $cache id title)"} )
  titles=( ${(f)"$(_plexdo_read_cache $cache title '')"} )
  _describe -t user-ids 'user id' ids
  [[ -n $titles ]] && _describe -t user-titles 'user title' titles
}

_plexdo_libraries() {
  local cache="$(_plexdo_cache_dir)/libraries.json"
  _plexdo_cache_fresh $cache || _plexdo_refresh libraries-list
  local -a libs titles
  libs=( ${(f)"$(_plexdo_read_cache $cache id title)"} )
  titles=( ${(f)"$(_plexdo_read_cache $cache title '')"} )
  _describe -t library-ids 'library id' libs
  [[ -n $titles ]] && _describe -t library-titles 'library title' titles
}

_plexdo_rating_keys() {
  local dir="$(_plexdo_cache_dir)" file lib
  local -a keys
  for file in $dir/titles.*.json(N); do
    if ! _plexdo_cache_fresh $file; then
      lib=${${file:t}#titles.}; lib=${lib%.json}
      _plexdo_refresh library-list $lib
    fi
    keys+=( ${(f)"$(_plexdo_read_cache $file ratingKey title)"} )
  done
  if (( ! ${#keys} )); then
    _plexdo_refresh libraries-list
    _message 'rating key (run library-list <library_id> to populate completion)'
    return
  fi
  _describe -t rating-keys 'rating key' keys
}

# A word typed for a user or library, as the name plexdo files its by-word
# cache under: every character a file name cannot hold replaced by "_", as
# plexdo's cache_key does. plexdo writes that cache for the ID, the title,
# and the word as typed, so whichever is on the command line finds it.
_plexdo_word_key() {
  print -r -- ${1//[\/\\:\*\?\"\<\>\|]/_}
}

# $1 is the user id or title already typed on the command line.
_plexdo_playlists() {
  local user=${(Q)${1:-0}} dir="$(_plexdo_cache_dir)"
  local cache="$dir/playlists-by-word.$(_plexdo_word_key $user).json"
  _plexdo_cache_fresh $cache || _plexdo_refresh playlists-list $user
  local -a names
  names=( ${(f)"$(_plexdo_read_cache $cache title '')"} )
  if (( ${#names} )); then
    _describe -t playlists 'playlist' names
  else
    _message 'playlist title'
  fi
}

# Playlists by title or ratingKey, for playlist-list which accepts either.
_plexdo_playlists_or_keys() {
  local user=${(Q)${1:-0}}
  local cache="$(_plexdo_cache_dir)/playlists-by-word.$(_plexdo_word_key $user).json"
  _plexdo_cache_fresh $cache || _plexdo_refresh playlists-list $user
  local -a names keys
  names=( ${(f)"$(_plexdo_read_cache $cache title '')"} )
  keys=( ${(f)"$(_plexdo_read_cache $cache ratingKey title)"} )
  [[ -n $names ]] && _describe -t playlists 'playlist' names
  [[ -n $keys ]] && _describe -t playlist-keys 'playlist ratingKey' keys
}

# Album names, derived from the "Album - Photo" titles cached for a library.
_plexdo_albums() {
  local lib=${(Q)${1:-}}
  local cache="$(_plexdo_cache_dir)/titles-by-word.$(_plexdo_word_key $lib).json"
  [[ -z $lib ]] && { _message 'album name'; return }
  _plexdo_cache_fresh $cache || _plexdo_refresh library-list $lib
  local -a albums
  albums=( ${(fu)"$(_plexdo_read_cache $cache title '')"} )
  if (( ${#albums} )); then
    _describe -t albums 'album' albums
  else
    _message 'album name'
  fi
}

# Nth (0-based) positional argument after the subcommand, "" when absent.
_plexdo_positional() {
  local want=$1 i=2 skip=0 count=0
  for (( i = 2; i <= $#words - 1; i++ )); do
    if (( skip )); then skip=0; continue; fi
    case ${words[i]} in
      --m3u|--album|--sort|--media-type|--library-id|-l|--library|-t|--title|--type|--path|\
      --filter|--category|--update|\
      -u|--username|-p|--password|-c|--code|-f|--format|--section|-p|--prefix|--throttle|\
      --ratio|--debug-log) skip=1; continue ;;
      -*) continue ;;
    esac
    if (( count == want )); then print -r -- ${words[i]}; return; fi
    (( count++ ))
  done
}

_plexdo_commands() {
  local -a cmds
  cmds=(
    'album-list:Show one album with its played state and progress'
    'find-missing:Find gaps in the episode numbering of a show'
    'libraries-list:List the server'\''s libraries'
    'library-list:List what a library holds, by type or by folder'
    'login:Sign in to plex.tv and save the token'
    'logout:Sign out of plex.tv and remove the saved tokens'
    'metadata:Show or update the metadata of one item'
    'player-remote-play:Tell a player, reached directly, to play an item'
    'playlist-build:Build a playlist, or add items to one'
    'playlist-clean:Remove the watched items from a playlist'
    'playlist-copy:Copy a playlist to one user, or to all of them'
    'playlist-export:Export a playlist to an M3U file'
    'playlist-list:List the items in a playlist'
    'playlist-remove:Delete a playlist'
    'playlists-list:List a user'\''s playlists'
    'read:Stream a media file to stdout'
    'rescan:Rescan libraries, or show the scans under way'
    'search:Search for titles matching a query'
    'set-pin:Save or remove a Plex Home member'\''s PIN'
    'show-list:List a show'\''s episodes'
    'show-watched-cp:Sync watched state and resume points of two users'
    'status:Show the server'\''s sessions, users, scans, and tasks'
    'titles-export:Export a library to an M3U file or photo gallery'
    'users-list:List the server'\''s users'
    'wait:Sleep until a session'\''s current play is over'
    'write-config-example:Write a template configuration file'
    'write-secrets-example:Write an example secrets file, or print it'
  )
  _describe -t commands 'plexdo command' cmds
}

# The mode flag given to playlist-build or playlist-copy; nothing when none
# has been typed yet. The mode decides what each positional argument is.
_plexdo_mode() {
  local word
  for word in ${words[2,-1]}; do
    case $word in
      -I|--interleaved) echo interleaved; return ;;
      -C|--chronological) echo chronological; return ;;
      -R|--randomize) echo randomize; return ;;
      -A|--append|--all) echo all-or-append; return ;;
      -M|--merge) echo merge; return ;;
      -T|--to) echo to; return ;;
    esac
  done
}

_plexdo_global_opts=(
  '--json[Output machine-readable JSON instead of tables]'
  '--verbose[Print high-level progress to stderr]'
  '--debug[Print detailed internal logs to stderr]'
  '--debug-log[Append the debug logs, profiled and timestamped, to a file]:debug log:_files'
  '--dry-run[Show what would happen without mutating Plex]'
  '(-W --wide)'{-W,--wide}'[Do not shrink table columns to the terminal width]'
  '--throttle[Seconds between requests in per-item operations; 0 disables]:seconds:'
  '(-h --help)'{-h,--help}'[Show this help message and exit]'
)

_plexdo_subcommand() {
  local m3u='--m3u[Also export an M3U file using Plex server paths]:m3u path:_files'
  # Arrays, not scalars: only an array assignment expands the braces.
  local -a pfx over target
  pfx=('(-p --prefix)'{-p,--prefix}'[Rewrite exported paths onto this prefix]:prefix:')
  over=('(-o --overwrite)'{-o,--overwrite}'[Replace an existing playlist of the same name]')
  target=(
    '(-u --user -a --all-users)'{-u,--user}'[Create it for this user instead]:user:_plexdo_users'
    '(-u --user -a --all-users)'{-a,--all-users}'[Create it for every user on the server]'
  )
  case ${words[1]} in
    library-list)
      _arguments $_plexdo_global_opts \
        '(-t --type)'{-t,--type}'[What to list]:type:(album artist clip collection episode folder movie photo season show track)' \
        '--path[With --type folder, the folder to list]:path:' \
        '*--filter[List only what matches FIELD=VALUE]:filter (FIELD=VALUE):' \
        '*--category[Short for --filter genre=CATEGORY]:category:' \
        '--list-categories[List the genres of the type listed]' \
        '--album[Photo libraries only: one album and those inside it]:album:{_plexdo_albums $(_plexdo_positional 0)}' \
        '1:library id:_plexdo_libraries'
      ;;
    show-list)
      _arguments $_plexdo_global_opts $pfx $m3u '1:show rating key:_plexdo_rating_keys'
      ;;
    metadata)
      _arguments $_plexdo_global_opts \
        '(-u --update)'{-u,--update}'[Change the item to match a JSON file]:JSON file:_files' \
        '1:rating key:_plexdo_rating_keys'
      ;;
    album-list)
      _arguments $_plexdo_global_opts '1:rating key:_plexdo_rating_keys'
      ;;
    titles-export)
      _arguments $_plexdo_global_opts $pfx \
        '--sort[Sort order]:order:(alpha date random)' \
        '--album[Photo libraries only: restrict to one album]:album:{_plexdo_albums $(_plexdo_positional 0)}' \
        '1:library id:_plexdo_libraries' \
        '2:output path:_files'
      ;;
    search)
      _arguments $_plexdo_global_opts \
        '--media-type[Restrict to one media type]:type:(movie show episode track photo album artist)' \
        '--library-id[Restrict to one library]:library id:_plexdo_libraries' \
        '1:user:_plexdo_users' \
        '2:query:'
      ;;
    status)
      _arguments $_plexdo_global_opts \
        '--section[Show only one section]:section:(server sessions users accounts connections scans activities tasks)'
      ;;
    users-list|libraries-list)
      _arguments $_plexdo_global_opts
      ;;
    write-config-example)
      _arguments $_plexdo_global_opts \
        '(-o --overwrite)'{-o,--overwrite}'[Replace an existing config file]'
      ;;
    write-secrets-example)
      _arguments $_plexdo_global_opts \
        '(-o --overwrite)'{-o,--overwrite}'[Replace an existing secrets file]'
      ;;
    playlists-list)
      _arguments $_plexdo_global_opts '1:user:_plexdo_users'
      ;;
    playlist-list)
      _arguments $_plexdo_global_opts $pfx $m3u \
        '1:user:_plexdo_users' \
        '2:playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}'
      ;;
    playlist-export)
      _arguments $_plexdo_global_opts $pfx \
        '1:user:_plexdo_users' \
        '2:playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}' \
        '3:output path:_files'
      ;;
    wait)
      _arguments $_plexdo_global_opts \
        '(-s --session -a --all)'{-s,--session}'[Follow the session with this sessionKey]:session key:' \
        '(-r --rating-key -a --all)'{-r,--rating-key}'[Wait for this video]:rating key:_plexdo_rating_keys' \
        '(-a --all -s --session -r --rating-key)'{-a,--all}'[Wait for every play by every user]' \
        '(-i --interval)'{-i,--interval}'[Seconds between polls]:seconds:' \
        '--fast-interval[Seconds between polls near the end point]:seconds:' \
        '--no-credits[Ignore the credits marker and wait for the end]' \
        '--offset[Signed seconds: negative ends early, positive sleeps after]:seconds:' \
        '--paused[Count a play as over once paused this many seconds]:seconds:' \
        '--now[With -r: exit at once if the video is not playing]'
      ;;
    player-remote-play)
      _arguments $_plexdo_global_opts \
        '--port[Port the player listens on for remote control]:port:' \
        '--player-user[Account signed in to the player: user id, username, or email]:user:' \
        '--server-url[Server address the player should fetch from]:url:' \
        '1:player host name or address:_hosts' \
        '2:rating key:_plexdo_rating_keys'
      ;;
    playlist-clean)
      _arguments $_plexdo_global_opts \
        '--include-partial[Also remove part-played items]' \
        '1:user:_plexdo_users' \
        '2:playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}'
      ;;
    playlist-remove)
      _arguments $_plexdo_global_opts \
        '1:user:_plexdo_users' \
        '2:playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}'
      ;;
    read)
      _arguments $_plexdo_global_opts '1:rating key:_plexdo_rating_keys'
      ;;
    find-missing)
      _arguments $_plexdo_global_opts \
        '(-l --library)'{-l,--library}'[Library to look in]:library:_plexdo_libraries' \
        '(-A --all)'{-A,--all}'[Check every show]' \
        '(-s --season)'{-s,--season}'[Season number, or several comma separated]:seasons:' \
        '--include-specials[Also check season 0]' \
        '1:show:_plexdo_rating_keys'
      ;;
    rescan)
      _arguments $_plexdo_global_opts \
        '(-a --all)'{-a,--all}'[Rescan every library]' \
        '(-s --status)'{-s,--status}'[Print all active scan jobs]' \
        '(-n --now)'{-n,--now}'[Cancel pending scans before rescanning]' \
        '1:library id:_plexdo_libraries'
      ;;
    playlist-build)
      local modes='(-I --interleaved -C --chronological -R --randomize -A --append -M --merge)'
      local -a how mixing
      how=(
        $modes{-I,--interleaved}'[Take one episode from each show in turn]'
        $modes{-C,--chronological}'[Sort the episodes and movies by air date]'
        $modes{-R,--randomize}'[Shuffle an existing playlist into a new one]'
        $modes{-A,--append}'[Add items to the end of an existing playlist]'
        $modes{-M,--merge}'[Mix two existing playlists into a new one]'
      )
      mixing=(
        '--ratio[Take A items from the first, then B from the second]:ratio (A\:B):'
        '(-s --stop-short)'{-s,--stop-short}'[Stop when either playlist runs out]'
        '(-U --unique)'{-U,--unique}'[Skip an item already taken]'
      )
      case $(_plexdo_mode) in
        interleaved|chronological)
          _arguments $_plexdo_global_opts $how $pfx $m3u $target $over \
            '1:playlist name:' \
            '*:rating key:_plexdo_rating_keys'
          ;;
        randomize)
          _arguments $_plexdo_global_opts $how $pfx $m3u $target $over \
            '1:user:_plexdo_users' \
            '2:source playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}' \
            '3:destination playlist:'
          ;;
        all-or-append)
          _arguments $_plexdo_global_opts $how \
            '1:user:_plexdo_users' \
            '2:playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}' \
            '*:rating key:_plexdo_rating_keys'
          ;;
        merge)
          _arguments $_plexdo_global_opts $how $mixing $pfx $m3u $target $over \
            '1:user:_plexdo_users' \
            '2:new playlist name:' \
            '3:first playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}' \
            '4:second playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}'
          ;;
        *)
          # No mode yet, so nothing says what an argument would be.
          _arguments $_plexdo_global_opts $how $pfx $m3u $target $over
          ;;
      esac
      ;;
    playlist-copy)
      local -a whom
      whom=(
        '(-A --all -T --to)'{-A,--all}'[Copy to every user the server is shared with]'
        '(-A --all -T --to)'{-T,--to}'[Copy to one user, under a title of your choosing]'
        '(-o --overwrite)'{-o,--overwrite}'[Overwrite an existing playlist of the same name]'
      )
      if [[ $(_plexdo_mode) == to ]]; then
        _arguments $_plexdo_global_opts $whom \
          '1:source user:_plexdo_users' \
          '2:source playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}' \
          '3:target user:_plexdo_users' \
          '4:destination playlist:'
      else
        _arguments $_plexdo_global_opts $whom \
          '1:source user:_plexdo_users' \
          '2:source playlist:{_plexdo_playlists_or_keys $(_plexdo_positional 0)}'
      fi
      ;;
    show-watched-cp)
      _arguments $_plexdo_global_opts \
        '(-1 --one-way)'{-1,--one-way}'[Only write to the second user]' \
        '(-l --library)'{-l,--library}'[Restrict to one library]:library id:_plexdo_libraries' \
        '(-t --title)'{-t,--title}'[Restrict to one item]:rating key:_plexdo_rating_keys' \
        '--unwatch[Propagate the unwatched state instead]' \
        '1:first user:_plexdo_users' \
        '2:second user:_plexdo_users'
      ;;
    login)
      _arguments $_plexdo_global_opts \
        '(-u --username)'{-u,--username}'[Plex username or email]:username:' \
        '(-p --password)'{-p,--password}'[Plex password (INSECURE: visible in ps and shell history)]:password:' \
        '--save-password[Also save the password in the system keyring]' \
        '(-c --code)'{-c,--code}'[Two-factor authentication code]:code:' \
        '(-2 --two-factor)'{-2,--two-factor}'[Prompt for a two-factor code]'
      ;;
    logout)
      _arguments $_plexdo_global_opts \
        '(-u --username)'{-u,--username}'[Sign out only this saved name]:username:'
      ;;
    set-pin)
      _arguments $_plexdo_global_opts \
        '--remove[Remove the saved PIN instead of prompting for one]' \
        '1:user:_plexdo_users'
      ;;
    *)
      _arguments $_plexdo_global_opts
      ;;
  esac
}

_plexdo() {
  local curcontext="$curcontext" state line
  typeset -A opt_args
  _arguments -C $_plexdo_global_opts \
    '1:command:_plexdo_commands' \
    '*::command argument:->subcmd'
  [[ $state == subcmd ]] && _plexdo_subcommand
}

_plexdo "$@"
