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

  local subcommands="ls new rename close done kill status where note dx split portal worktree setup help"

  if [[ $COMP_CWORD -eq 1 ]]; then
    local projects
    projects=$(python3 -c "
import json
with open('$HOME/.config/mux/projects.json') as f:
    d = json.load(f)
for name in sorted(d.get('projects', {}).keys()):
    print(name)
" 2>/dev/null)
    COMPREPLY=($(compgen -W "${subcommands} ${projects}" -- "$cur"))
  elif [[ $COMP_CWORD -eq 2 ]]; then
    case "$prev" in
      kill|close|done|status|note)
        local projects
        projects=$(python3 -c "
import json
with open('$HOME/.config/mux/projects.json') as f:
    d = json.load(f)
for name in sorted(d.get('projects', {}).keys()):
    print(name)
" 2>/dev/null)
        COMPREPLY=($(compgen -W "$projects" -- "$cur"))
        ;;
      worktree)
        COMPREPLY=($(compgen -W "ls cleanup remove" -- "$cur"))
        ;;
      dx)
        COMPREPLY=($(compgen -W "done list" -- "$cur"))
        ;;
      portal)
        COMPREPLY=($(compgen -W "on off" -- "$cur"))
        ;;
    esac
  fi
}

complete -F _mux_completions mux
