#compdef valley
# zsh completion for valley. The verb list mirrors the case statement in
# bin/valley — update both together.
#
# NEVER fetch from here: completion runs on every <TAB> and must be instant.
# Candidates come from the remote-tracking refs of the last fetch; valley's
# own verbs fetch before acting, so stale candidates cost nothing.

_valley() {
  if (( CURRENT == 2 )); then
    local -a verbs=(
      'pending:list branches on origin not merged into origin/main'
      'review:page through a branch, then ask, reject, or skip'
      'status:read the integration result for a branch from origin'
      'checks:print the checks a change owes under the composed policy'
      'tail:watch bus events scroll by'
      'replay:publish ref-updated events for the current refs of a repo'
      'help:show help'
    )
    _describe -t verbs 'valley verb' verbs
  elif (( CURRENT == 3 )) && [[ ${words[2]} == replay ]]; then
    _files -/
  elif [[ ${words[2]} == checks && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--schema:the policy schema to compose against'
      '--instance:the instance policy layer directory'
      '--project:the project policy layer directory'
    )
    _describe -t options 'valley checks option' opts
  elif (( CURRENT == 3 )) && [[ ${words[2]} == review || ${words[2]} == status ]]; then
    # Cached topic branches on origin. Review filters out merged branches;
    # status needs those too. Silent outside a git repo — no errors
    # mid-typing.
    local -a branches selection
    selection=()
    [[ ${words[2]} == review ]] && selection=(--no-merged=origin/main)
    branches=(${(f)"$(git for-each-ref refs/remotes/origin \
      --format='%(refname)' "${selection[@]}" 2>/dev/null)"})
    branches=(${branches:#refs/remotes/origin/HEAD})
    branches=(${branches:#refs/remotes/origin/main})
    branches=(${branches#refs/remotes/origin/})
    (( ${#branches} )) && compadd -a branches
  fi
}

_valley "$@"
