#compdef mux

_mux_projects() {
  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))
  _describe 'project' projects
}

_mux() {
  local -a subcommands
  subcommands=(
    'ls:List all desks and windows'
    'new:New window in current desk'
    'rename:Rename current window'
    'close:Park a desk (keeps running)'
    'done:Park a desk with warm goodbye'
    'kill:Destroy a desk (asks first)'
    'status:Show desk status'
    'where:Show current location'
    'note:Manage sticky notes'
    'dx:DX idea capture'
    'split:Split current pane'
    'portal:Toggle spoken name on switch'
    'worktree:Manage git worktrees'
    'setup:First-time setup'
    'help:Show help'
  )

  if (( CURRENT == 2 )); then
    _alternative \
      'subcommands:command:_describe "command" subcommands' \
      'projects:project:_mux_projects'
  elif (( CURRENT == 3 )); then
    case "${words[2]}" in
      kill|close|done|status|note)
        _mux_projects ;;
      worktree)
        local -a wt_actions
        wt_actions=('ls:List worktrees' 'cleanup:Merge or park a worktree' 'remove:Force-remove a worktree')
        _describe 'action' wt_actions ;;
      dx)
        local -a dx_actions
        dx_actions=('done:Clear a DX item' 'list:List DX items')
        _describe 'action' dx_actions ;;
      portal)
        local -a portal_actions
        portal_actions=('on:Enable spoken name' 'off:Disable spoken name')
        _describe 'action' portal_actions ;;
    esac
  elif (( CURRENT == 4 )); then
    case "${words[2]}" in
      worktree)
        if [[ "${words[3]}" == "cleanup" || "${words[3]}" == "remove" ]]; then
          _mux_projects
        fi ;;
      note)
        if [[ "${words[3]}" == "rm" ]]; then
          : # number, no completion
        fi ;;
    esac
  fi
}

_mux "$@"
