# Shared Completion Functions
# Compatible with both bash and zsh

# Custom completion for 'ta' command
_ta_complete() {
  local cur prev actions layers tf_cmds ansible_cmds
  
  # Get current word and previous word based on shell
  if [[ -n "$ZSH_VERSION" ]]; then
    # Zsh completion
    cur="${words[CURRENT]}"
    prev="${words[CURRENT-1]}"
    local comp_word=$CURRENT
  else
    # Bash completion
    local cur prev
    _get_comp_words_by_ref cur prev
    local comp_word=$COMP_CWORD
  fi
  
  actions="terraform ansible install remove"
  layers="foundation showcase"
  tf_cmds="init plan apply refresh destroy"
  ansible_cmds=""  # Add Ansible-specific commands here if needed

  case $comp_word in
    1)
      if [[ -n "$ZSH_VERSION" ]]; then
        compadd $actions
      else
        COMPREPLY=( $(compgen -W "$actions" -- "$cur") )
      fi
      ;;
    2)
      if [[ "$prev" == "terraform" || "$prev" == "ansible" ]]; then
        if [[ -n "$ZSH_VERSION" ]]; then
          compadd $layers
        else
          COMPREPLY=( $(compgen -W "$layers" -- "$cur") )
        fi
      fi
      ;;
    3)
      if [[ -n "$ZSH_VERSION" ]]; then
        local first_word="${words[2]}"
      else
        local first_word="${COMP_WORDS[1]}"
      fi
      
      if [[ "$first_word" == "terraform" ]]; then
        if [[ -n "$ZSH_VERSION" ]]; then
          compadd $tf_cmds
        else
          COMPREPLY=( $(compgen -W "$tf_cmds" -- "$cur") )
        fi
      elif [[ "$first_word" == "ansible" ]]; then
        if [[ -n "$ZSH_VERSION" ]]; then
          compadd $ansible_cmds
        else
          COMPREPLY=( $(compgen -W "$ansible_cmds" -- "$cur") )
        fi
      fi
      ;;
    *)
      # Fallback to file completions
      if [[ -n "$ZSH_VERSION" ]]; then
        _files
      else
        COMPREPLY=( $(compgen -f -- "$cur") )
      fi
      ;;
  esac
  return 0
}

# Register completion based on shell
if [[ -n "$ZSH_VERSION" ]]; then
  # Zsh completion registration
  compdef _ta_complete ta
else
  # Bash completion registration
  complete -F _ta_complete ta
fi