"""
Shell Completions - Generate shell completion scripts for spectra.

Supports Bash, Zsh, and Fish shells.
"""

# Embedded completion scripts (for dynamic generation)
BASH_COMPLETION = """#!/bin/bash
# Bash completion script for spectra
# Generated by: spectra --completions bash

_spectra_completions() {
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    # All available options
    opts="--input -f --input-dir -d --epic -e --execute -x --dry-run -n --no-confirm --phase --story --config -c --jira-url --project --verbose -v --quiet -q --output -o --no-color --export --validate --interactive -i --resume --resume-session --list-sessions --update-source --list-files --version --help -h --completions"

    # Phase choices
    phases="all descriptions subtasks comments statuses"

    # Handle option-specific completions
    case "${prev}" in
        --input|-f)
            COMPREPLY=( $(compgen -f -X '!*.md' -- "${cur}") )
            COMPREPLY+=( $(compgen -d -- "${cur}") )
            return 0
            ;;
        --input-dir|-d)
            COMPREPLY=( $(compgen -d -- "${cur}") )
            return 0
            ;;
        --config|-c)
            COMPREPLY=( $(compgen -f -X '!*.yaml' -- "${cur}") )
            COMPREPLY+=( $(compgen -f -X '!*.yml' -- "${cur}") )
            COMPREPLY+=( $(compgen -f -X '!*.toml' -- "${cur}") )
            COMPREPLY+=( $(compgen -d -- "${cur}") )
            return 0
            ;;
        --export)
            COMPREPLY=( $(compgen -f -X '!*.json' -- "${cur}") )
            COMPREPLY+=( $(compgen -d -- "${cur}") )
            return 0
            ;;
        --phase)
            COMPREPLY=( $(compgen -W "${phases}" -- "${cur}") )
            return 0
            ;;
        --completions)
            COMPREPLY=( $(compgen -W "bash zsh fish powershell" -- "${cur}") )
            return 0
            ;;
        --output|-o)
            COMPREPLY=( $(compgen -W "text json" -- "${cur}") )
            return 0
            ;;
        --epic|-e|--story|--jira-url|--project)
            return 0
            ;;
    esac

    if [[ "${cur}" == -* ]]; then
        COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
        return 0
    fi

    COMPREPLY=( $(compgen -f -- "${cur}") )
}

complete -F _spectra_completions spectra
"""

ZSH_COMPLETION = """#compdef spectra
# Zsh completion script for spectra
# Generated by: spectra --completions zsh

_spectra() {
    local curcontext="$curcontext" state line
    typeset -A opt_args

    local -a phases
    phases=(
        'all:Run all sync phases'
        'descriptions:Sync story descriptions only'
        'subtasks:Sync subtasks only'
        'comments:Sync comments only'
        'statuses:Sync statuses only'
    )

    local -a shells
    shells=(
        'bash:Generate Bash completion script'
        'zsh:Generate Zsh completion script'
        'fish:Generate Fish completion script'
        'powershell:Generate PowerShell completion script'
    )

    _arguments -C \\
        '(-f --input)'{-f,--input}'[Path to input file (markdown, yaml, json, etc.)]:input file:_files -g "*.md"' \\
        '(-d --input-dir)'{-d,--input-dir}'[Path to directory containing story files]:directory:_files -/' \\
        '(-e --epic)'{-e,--epic}'[Jira epic key (e.g., PROJ-123)]:epic key:' \\
        '(-x --execute)'{-x,--execute}'[Execute changes (default is dry-run)]' \\
        '(-n --dry-run)'{-n,--dry-run}'[Preview changes without executing]' \\
        '--no-confirm[Skip confirmation prompts]' \\
        '--phase[Which phase to run]:phase:->phases' \\
        '--story[Filter to specific story ID]:story id:' \\
        '(-c --config)'{-c,--config}'[Path to config file]:config file:_files -g "*.{yaml,yml,toml}"' \\
        '--jira-url[Override Jira URL]:url:_urls' \\
        '--project[Override Jira project key]:project key:' \\
        '(-v --verbose)'{-v,--verbose}'[Verbose output]' \\
        '(-q --quiet)'{-q,--quiet}'[Quiet mode - only show errors and summary]' \\
        '(-o --output)'{-o,--output}'[Output format]:format:(text json)' \\
        '--no-color[Disable colored output]' \\
        '--export[Export analysis to JSON file]:json file:_files -g "*.json"' \\
        '--validate[Validate markdown file format]' \\
        '(-i --interactive)'{-i,--interactive}'[Interactive mode with step-by-step guided sync]' \\
        '--resume[Resume an interrupted sync session]' \\
        '--resume-session[Resume a specific sync session by ID]:session id:' \\
        '--list-sessions[List all resumable sync sessions]' \\
        '--update-source[Write tracker info back to source file after sync]' \\
        '--list-files[List which files would be processed from --input-dir]' \\
        '--version[Show version and exit]' \\
        '--completions[Generate shell completion script]:shell:->shells' \\
        '(-h --help)'{-h,--help}'[Show help message]' \\
        '*:markdown file:_files -g "*.md"'

    case "$state" in
        phases)
            _describe -t phases 'sync phase' phases
            ;;
        shells)
            _describe -t shells 'shell type' shells
            ;;
    esac
}

_spectra "$@"
"""

FISH_COMPLETION = """# Fish completion script for spectra
# Generated by: spectra --completions fish

complete -c spectra -f

# Input arguments
complete -c spectra -s f -l input -d 'Path to input file (markdown, yaml, json, etc.)' -r -F -a '*.md'
complete -c spectra -s d -l input-dir -d 'Path to directory containing story files' -r -a '(__fish_complete_directories)'
complete -c spectra -s e -l epic -d 'Jira epic key (e.g., PROJ-123)' -x

# Execution mode
complete -c spectra -s x -l execute -d 'Execute changes (default is dry-run)'
complete -c spectra -s n -l dry-run -d 'Preview changes without executing'
complete -c spectra -l no-confirm -d 'Skip confirmation prompts'
complete -c spectra -l update-source -d 'Write tracker info back to source file after sync'
complete -c spectra -l list-files -d 'List which files would be processed from --input-dir'

# Phase control
complete -c spectra -l phase -d 'Which phase to run' -x -a '
    all\\t"Run all sync phases"
    descriptions\\t"Sync story descriptions only"
    subtasks\\t"Sync subtasks only"
    comments\\t"Sync comments only"
    statuses\\t"Sync statuses only"
'

# Filters
complete -c spectra -l story -d 'Filter to specific story ID (e.g., STORY-001, PROJ-123)' -x

# Configuration
complete -c spectra -s c -l config -d 'Path to config file' -r -F -a '*.yaml *.yml *.toml'
complete -c spectra -l jira-url -d 'Override Jira URL' -x
complete -c spectra -l project -d 'Override Jira project key' -x

# Output options
complete -c spectra -s v -l verbose -d 'Verbose output'
complete -c spectra -s q -l quiet -d 'Quiet mode - only show errors and summary'
complete -c spectra -s o -l output -d 'Output format' -x -a 'text json'
complete -c spectra -l no-color -d 'Disable colored output'
complete -c spectra -l export -d 'Export analysis to JSON file' -r -F -a '*.json'

# Special modes
complete -c spectra -l validate -d 'Validate markdown file format'
complete -c spectra -s i -l interactive -d 'Interactive mode with step-by-step guided sync'
complete -c spectra -l resume -d 'Resume an interrupted sync session'
complete -c spectra -l resume-session -d 'Resume a specific sync session by ID' -x
complete -c spectra -l list-sessions -d 'List all resumable sync sessions'
complete -c spectra -l version -d 'Show version and exit'
complete -c spectra -s h -l help -d 'Show help message'

# Shell completions
complete -c spectra -l completions -d 'Generate shell completion script' -x -a '
    bash\\t"Generate Bash completion script"
    zsh\\t"Generate Zsh completion script"
    fish\\t"Generate Fish completion script"
    powershell\\t"Generate PowerShell completion script"
'
"""

POWERSHELL_COMPLETION = """# PowerShell completion script for spectra
# Generated by: spectra --completions powershell
# Installation: Add to your $PROFILE or run: spectra --completions powershell | Out-File -Append $PROFILE

using namespace System.Management.Automation
using namespace System.Management.Automation.Language

Register-ArgumentCompleter -Native -CommandName spectra -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)

    # All available options with descriptions
    $options = @(
        @{ Name = '--input'; Short = '-f'; Description = 'Path to input file (markdown, yaml, json, etc.)'; Type = 'File' }
        @{ Name = '--input-dir'; Short = '-d'; Description = 'Path to directory containing story files'; Type = 'Directory' }
        @{ Name = '--epic'; Short = '-e'; Description = 'Jira epic key (e.g., PROJ-123)'; Type = 'String' }
        @{ Name = '--execute'; Short = '-x'; Description = 'Execute changes (default is dry-run)'; Type = 'Switch' }
        @{ Name = '--dry-run'; Short = '-n'; Description = 'Preview changes without executing'; Type = 'Switch' }
        @{ Name = '--no-confirm'; Description = 'Skip confirmation prompts'; Type = 'Switch' }
        @{ Name = '--incremental'; Description = 'Only sync changed stories'; Type = 'Switch' }
        @{ Name = '--force-full-sync'; Description = 'Force full sync even when --incremental is set'; Type = 'Switch' }
        @{ Name = '--update-source'; Description = 'Write tracker info back to source file after sync'; Type = 'Switch' }
        @{ Name = '--phase'; Description = 'Which phase to run'; Type = 'Enum'; Values = @('all', 'descriptions', 'subtasks', 'comments', 'statuses') }
        @{ Name = '--story'; Description = 'Filter to specific story ID'; Type = 'String' }
        @{ Name = '--config'; Short = '-c'; Description = 'Path to config file'; Type = 'File' }
        @{ Name = '--jira-url'; Description = 'Override Jira URL'; Type = 'String' }
        @{ Name = '--project'; Description = 'Override Jira project key'; Type = 'String' }
        @{ Name = '--verbose'; Short = '-v'; Description = 'Verbose output'; Type = 'Switch' }
        @{ Name = '--quiet'; Short = '-q'; Description = 'Quiet mode - only show errors and summary'; Type = 'Switch' }
        @{ Name = '--output'; Short = '-o'; Description = 'Output format'; Type = 'Enum'; Values = @('text', 'json', 'yaml', 'markdown') }
        @{ Name = '--no-color'; Description = 'Disable colored output'; Type = 'Switch' }
        @{ Name = '--no-emoji'; Description = 'Disable emojis in output'; Type = 'Switch' }
        @{ Name = '--theme'; Description = 'Color theme for output'; Type = 'Enum'; Values = @('default', 'dark', 'light', 'monokai', 'solarized', 'nord', 'dracula', 'gruvbox', 'ocean', 'minimal') }
        @{ Name = '--list-themes'; Description = 'List available color themes'; Type = 'Switch' }
        @{ Name = '--export'; Description = 'Export analysis to JSON file'; Type = 'File' }
        @{ Name = '--validate'; Description = 'Validate markdown file format'; Type = 'Switch' }
        @{ Name = '--interactive'; Short = '-i'; Description = 'Interactive mode with step-by-step guided sync'; Type = 'Switch' }
        @{ Name = '--resume'; Description = 'Resume an interrupted sync session'; Type = 'Switch' }
        @{ Name = '--resume-session'; Description = 'Resume a specific sync session by ID'; Type = 'String' }
        @{ Name = '--list-sessions'; Description = 'List all resumable sync sessions'; Type = 'Switch' }
        @{ Name = '--list-files'; Description = 'List which files would be processed'; Type = 'Switch' }
        @{ Name = '--version'; Description = 'Show version and exit'; Type = 'Switch' }
        @{ Name = '--help'; Short = '-h'; Description = 'Show help message'; Type = 'Switch' }
        @{ Name = '--completions'; Description = 'Generate shell completion script'; Type = 'Enum'; Values = @('bash', 'zsh', 'fish', 'powershell') }
        @{ Name = '--init'; Description = 'Run interactive setup wizard'; Type = 'Switch' }
        @{ Name = '--doctor'; Description = 'Run diagnostic checks'; Type = 'Switch' }
        @{ Name = '--stats'; Description = 'Show story statistics'; Type = 'Switch' }
        @{ Name = '--diff'; Description = 'Show differences between local and remote'; Type = 'Switch' }
        @{ Name = '--tui'; Description = 'Launch interactive TUI dashboard'; Type = 'Switch' }
    )

    # Get the previous token to determine context
    $tokens = $commandAst.CommandElements
    $previousToken = $null
    for ($i = 0; $i -lt $tokens.Count; $i++) {
        if ($tokens[$i].Extent.EndOffset -ge $cursorPosition) {
            if ($i -gt 0) {
                $previousToken = $tokens[$i - 1].Extent.Text
            }
            break
        }
        $previousToken = $tokens[$i].Extent.Text
    }

    # Handle value completion for options that take values
    if ($previousToken) {
        $prevOpt = $options | Where-Object { $_.Name -eq $previousToken -or $_.Short -eq $previousToken }
        if ($prevOpt) {
            switch ($prevOpt.Type) {
                'File' {
                    # Complete file paths
                    Get-ChildItem -Path "$wordToComplete*" -File -ErrorAction SilentlyContinue | ForEach-Object {
                        [CompletionResult]::new($_.FullName, $_.Name, 'ParameterValue', $_.Name)
                    }
                    return
                }
                'Directory' {
                    # Complete directory paths
                    Get-ChildItem -Path "$wordToComplete*" -Directory -ErrorAction SilentlyContinue | ForEach-Object {
                        [CompletionResult]::new($_.FullName, $_.Name, 'ParameterValue', $_.Name)
                    }
                    return
                }
                'Enum' {
                    # Complete enum values
                    $prevOpt.Values | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
                        [CompletionResult]::new($_, $_, 'ParameterValue', $_)
                    }
                    return
                }
            }
        }
    }

    # Complete options
    if ($wordToComplete -like '-*' -or $wordToComplete -eq '') {
        $options | ForEach-Object {
            if ($_.Name -like "$wordToComplete*") {
                [CompletionResult]::new($_.Name, $_.Name, 'ParameterName', $_.Description)
            }
            if ($_.Short -and $_.Short -like "$wordToComplete*") {
                [CompletionResult]::new($_.Short, $_.Short, 'ParameterName', $_.Description)
            }
        }
        return
    }

    # Default: complete file paths for markdown files
    Get-ChildItem -Path "$wordToComplete*" -Include @('*.md', '*.yaml', '*.yml', '*.json') -File -ErrorAction SilentlyContinue | ForEach-Object {
        [CompletionResult]::new($_.FullName, $_.Name, 'ParameterValue', $_.Name)
    }
    Get-ChildItem -Path "$wordToComplete*" -Directory -ErrorAction SilentlyContinue | ForEach-Object {
        [CompletionResult]::new($_.FullName, $_.Name, 'ParameterValue', "Directory: $($_.Name)")
    }
}

# Alias support (if spectra has aliases)
# Register-ArgumentCompleter -Native -CommandName sp -ScriptBlock $Function:TabExpansion
"""


def get_completion_script(shell: str) -> str | None:
    """
    Get the completion script for a specific shell.

    Args:
        shell: Shell type ('bash', 'zsh', 'fish', or 'powershell').

    Returns:
        The completion script as a string, or None if shell is not supported.
    """
    scripts = {
        "bash": BASH_COMPLETION,
        "zsh": ZSH_COMPLETION,
        "fish": FISH_COMPLETION,
        "powershell": POWERSHELL_COMPLETION,
        "pwsh": POWERSHELL_COMPLETION,  # Alias for PowerShell Core
    }
    return scripts.get(shell.lower())


def get_installation_instructions(shell: str) -> str:
    """
    Get installation instructions for a specific shell.

    Args:
        shell: Shell type ('bash', 'zsh', or 'fish').

    Returns:
        Installation instructions as a string.
    """
    shell = shell.lower()

    if shell == "bash":
        return """
# Bash Completion Installation

Option 1: Add to ~/.bashrc
  echo 'eval "$(spectra --completions bash)"' >> ~/.bashrc
  source ~/.bashrc

Option 2: Save to file and source
  spectra --completions bash > ~/.local/share/bash-completion/completions/spectra

Option 3: System-wide (requires sudo)
  sudo spectra --completions bash > /etc/bash_completion.d/spectra
"""

    if shell == "zsh":
        return """
# Zsh Completion Installation

Option 1: Add to ~/.zshrc
  echo 'eval "$(spectra --completions zsh)"' >> ~/.zshrc
  source ~/.zshrc

Option 2: Save to completions directory
  mkdir -p ~/.zsh/completions
  spectra --completions zsh > ~/.zsh/completions/_spectra
  # Add to ~/.zshrc: fpath=(~/.zsh/completions $fpath)
  # Then run: autoload -Uz compinit && compinit
"""

    if shell == "fish":
        return """
# Fish Completion Installation

Option 1: Add to config.fish
  echo 'spectra --completions fish | source' >> ~/.config/fish/config.fish

Option 2: Save to completions directory
  spectra --completions fish > ~/.config/fish/completions/spectra.fish
"""

    if shell in ("powershell", "pwsh"):
        return """
# PowerShell Completion Installation

Option 1: Add to your PowerShell profile (recommended)
  spectra --completions powershell >> $PROFILE
  . $PROFILE

Option 2: Save to file and dot-source
  spectra --completions powershell > ~\\spectra-completion.ps1
  # Add to $PROFILE: . ~\\spectra-completion.ps1

Option 3: One-time session load
  spectra --completions powershell | Invoke-Expression

Note: Works with both Windows PowerShell and PowerShell Core (pwsh).
To find your profile location: echo $PROFILE
"""

    return f"Unknown shell: {shell}. Supported shells: bash, zsh, fish, powershell"


def print_completion(shell: str) -> bool:
    """
    Print the completion script for a specific shell.

    Args:
        shell: Shell type ('bash', 'zsh', 'fish', or 'powershell').

    Returns:
        True if script was printed, False if shell is not supported.
    """
    script = get_completion_script(shell)
    if script:
        print(script)
        return True

    print(f"Error: Unknown shell '{shell}'. Supported shells: bash, zsh, fish, powershell")
    return False


SUPPORTED_SHELLS = ["bash", "zsh", "fish", "powershell"]
