"""Zsh shell completion handler."""

from typing import List

from .base import CompletionContext, CompletionHandler


class ZshCompletionHandler(CompletionHandler):
  """Zsh-specific completion handler."""

  def generate_script(self, prog_name: str) -> str:
    """Generate zsh completion script."""
    script = f'''#compdef {prog_name}
# Zsh completion for {prog_name}
# Generated by freyja

_{prog_name}_completion() {{
    local curcontext="$curcontext" state line
    typeset -A opt_args

    # Set up completion environment
    export _FREYA_COMPLETE=zsh
    export COMP_WORDS_STR="${{words[@]}}"
    export COMP_CWORD_NUM=${{#words[@]}}

    # Get completions from the program
    local completions
    completions=($({prog_name} --_complete 2>/dev/null))

    if [ $? -eq 0 ]; then
        compadd -a completions
    fi
}}

_{prog_name}_completion "$@"
'''
    return script

  def get_completions(self, context: CompletionContext) -> List[str]:
    """Get zsh-specific completions."""
    # Reuse bash completion logic for now
    from .bash import BashCompletionHandler
    bash_handler = BashCompletionHandler(self.cli)
    return bash_handler._get_generic_completions(context)

  def install_completion(self, prog_name: str) -> bool:
    """Install zsh completion."""
    from .installer import CompletionInstaller
    installer = CompletionInstaller(self, prog_name)
    return installer.install('zsh')
