#!/bin/bash

# Bash completion for Plex-related scripts
# Author: Peter Wood <peter@peterwood.dev>
#
# This file provides intelligent tab completion for:
# - plex.sh (main Plex management script)
# - scan-plex-libraries.sh (library scanner script)
# - plex-* aliases
#
# Installation:
#   Source this file in your bash/zsh configuration or place it in:
#   ~/.local/share/bash-completion/completions/

# Completion function for plex.sh
_plex_sh_completion() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local prev="${COMP_WORDS[COMP_CWORD-1]}"

    # Available commands for plex.sh
    local commands="start stop restart status scan repair nuclear help"

    # If we're completing the first argument (command)
    if [[ ${COMP_CWORD} -eq 1 ]]; then
        COMPREPLY=($(compgen -W "$commands" -- "$cur"))
        return 0
    fi

    # If previous word was 'scan', complete with scanner options
    if [[ "$prev" == "scan" ]]; then
        local scanner_commands="list scan refresh analyze generate tree interactive"
        local scanner_options="-v --verbose -h --help"
        COMPREPLY=($(compgen -W "$scanner_commands $scanner_options" -- "$cur"))
        return 0
    fi

    # For other commands, no additional completion needed
    return 0
}

# Completion function for scan-plex-libraries.sh
_scan_plex_libraries_completion() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local prev="${COMP_WORDS[COMP_CWORD-1]}"

    # Available commands for scan-plex-libraries.sh
    local commands="list scan refresh analyze generate tree interactive"
    local options="-v --verbose -h --help"

    # If we're completing the first argument
    if [[ ${COMP_CWORD} -eq 1 ]]; then
        # If it starts with -, show options
        if [[ "$cur" == -* ]]; then
            COMPREPLY=($(compgen -W "$options" -- "$cur"))
        else
            COMPREPLY=($(compgen -W "$commands" -- "$cur"))
        fi
        return 0
    fi

    # Handle specific command completions
    case "${COMP_WORDS[1]}" in
        refresh)
            # For refresh command: refresh [section_id] [force]
            if [[ ${COMP_CWORD} -eq 3 ]]; then
                # Third argument can be 'true' or 'false' for force flag
                COMPREPLY=($(compgen -W "true false" -- "$cur"))
            fi
            ;;
        analyze|analyse)
            # For analyze command: analyze [section_id] [deep]
            if [[ ${COMP_CWORD} -eq 3 ]]; then
                # Third argument can be 'true' or 'false' for deep flag
                COMPREPLY=($(compgen -W "true false" -- "$cur"))
            fi
            ;;
        tree)
            # tree command requires section_id but we can't predict them
            # Could potentially call the script to get section IDs but that's expensive
            ;;
    esac

    return 0
}

# Completion function for generic plex aliases that might pass through to plex.sh
_plex_alias_completion() {
    local cur="${COMP_WORDS[COMP_CWORD]}"

    # For plex-scan alias, complete with scanner commands
    if [[ "${COMP_WORDS[0]}" == *"plex-scan"* ]]; then
        local scanner_commands="list scan refresh analyze generate tree interactive"
        local scanner_options="-v --verbose -h --help"

        if [[ ${COMP_CWORD} -eq 1 ]]; then
            if [[ "$cur" == -* ]]; then
                COMPREPLY=($(compgen -W "$scanner_options" -- "$cur"))
            else
                COMPREPLY=($(compgen -W "$scanner_commands" -- "$cur"))
            fi
        elif [[ ${COMP_CWORD} -eq 2 && "${COMP_WORDS[1]}" == "refresh" ]]; then
            COMPREPLY=($(compgen -W "true false" -- "$cur"))
        elif [[ ${COMP_CWORD} -eq 2 && ("${COMP_WORDS[1]}" == "analyze" || "${COMP_WORDS[1]}" == "analyse") ]]; then
            COMPREPLY=($(compgen -W "true false" -- "$cur"))
        fi
        return 0
    fi

    # For plex-scanner alias, use the full scanner completion
    if [[ "${COMP_WORDS[0]}" == *"plex-scanner"* ]]; then
        _scan_plex_libraries_completion
        return 0
    fi

    # For other plex aliases, just complete with main plex.sh commands
    local commands="start stop restart status scan repair nuclear help"
    COMPREPLY=($(compgen -W "$commands" -- "$cur"))
    return 0
}

# Advanced completion function that attempts to get library section IDs
# This is more expensive but provides better completion
_plex_scanner_with_sections() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local prev="${COMP_WORDS[COMP_CWORD-1]}"

    # First try the basic completion
    _scan_plex_libraries_completion

    # If we didn't get any completions and we're looking for a section ID
    if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
        case "${COMP_WORDS[1]}" in
            scan|refresh|analyze|generate|tree)
                # Try to get section IDs if Plex is running
                if [[ ${COMP_CWORD} -eq 2 ]]; then
                    # Attempt to get section IDs from the scanner
                    local script_dir="$(dirname "${COMP_WORDS[0]}")"
                    local scanner_script=""

                    # Try to find the scanner script
                    if [[ -f "$script_dir/scan-plex-libraries.sh" ]]; then
                        scanner_script="$script_dir/scan-plex-libraries.sh"
                    elif [[ -f "/home/acedanger/shell/plex/scan-plex-libraries.sh" ]]; then
                        scanner_script="/home/acedanger/shell/plex/scan-plex-libraries.sh"
                    fi

                    if [[ -n "$scanner_script" ]]; then
                        # Attempt to get section IDs (with timeout to avoid hanging)
                        local section_ids
                        if section_ids=$(timeout 3s "$scanner_script" list 2>/dev/null | grep -oE '^\s*[0-9]+:' | grep -oE '[0-9]+' 2>/dev/null); then
                            COMPREPLY=($(compgen -W "$section_ids" -- "$cur"))
                        fi
                    fi
                fi
                ;;
        esac
    fi

    return 0
}

# Register completion functions for the main scripts
complete -F _plex_sh_completion plex.sh
complete -F _plex_sh_completion ./plex.sh
complete -F _plex_sh_completion /home/acedanger/shell/plex/plex.sh

complete -F _scan_plex_libraries_completion scan-plex-libraries.sh
complete -F _scan_plex_libraries_completion ./scan-plex-libraries.sh
complete -F _scan_plex_libraries_completion /home/acedanger/shell/plex/scan-plex-libraries.sh

# Register completion functions for aliases
# These will be available when the aliases are defined in the shell
complete -F _plex_alias_completion plex
complete -F _plex_alias_completion px
complete -F _plex_alias_completion plex-start
complete -F _plex_alias_completion plex-stop
complete -F _plex_alias_completion plex-restart
complete -F _plex_alias_completion plex-status
complete -F _plex_alias_completion plex-scan
complete -F _scan_plex_libraries_completion plex-scanner

# Optional: Enable advanced completion with section ID lookup for plex-scanner
# Uncomment the following line if you want more intelligent section ID completion
# (Note: This may cause slight delays if Plex is not running)
# complete -F _plex_scanner_with_sections plex-scanner

# Helper function to list available Plex library sections
# This can be called manually: _plex_list_sections
_plex_list_sections() {
    echo "Available Plex library sections:"
    if command -v /home/acedanger/shell/plex/scan-plex-libraries.sh >/dev/null 2>&1; then
        /home/acedanger/shell/plex/scan-plex-libraries.sh list 2>/dev/null || echo "  (Plex Media Server not running)"
    else
        echo "  (Scanner script not found)"
    fi
}

# Completion for special plex commands that might be added in the future
_plex_extended_completion() {
    local cur="${COMP_WORDS[COMP_CWORD]}"
    local cmd="${COMP_WORDS[0]}"

    # This function can be extended for future plex-related commands
    case "$cmd" in
        *plex-backup*)
            # If backup scripts get their own completion, handle here
            ;;
        *plex-restore*)
            # If restore scripts get their own completion, handle here
            ;;
    esac

    return 0
}

# Export functions for manual use (zsh compatible)
if declare -f >/dev/null 2>&1; then
    # In bash, export functions
    export -f _plex_list_sections 2>/dev/null || true
fi
