#compdef valley
# zsh completion for valley. The verb list mirrors valley's public verbs
# (helpTopics in status/help.go) — 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 and from
# the handle cache the last valley pending or valley changes wrote; valley's
# own verbs resolve a name against origin before acting, so stale candidates
# cost nothing.

_valley() {
  local -a topics=(
    'pending:list what needs an approval, in landing order, and what moves'
    'changes:print every change, across the host, as valley-changes/v1 JSON'
    'review:page through a change, or a stack bottom-up, then approve, reject, or skip'
    'approve:approve a change without paging it, filing its integration request'
    'rebase:rebase a change and its whole stack onto origin/main'
    'status:read the integration result for a change from origin'
    'ready:mark a head of a branch ready as a new version of its change'
    'unready:make a ready change a draft'
    'withdraw:mark a ready change or a draft withdrawn'
    'knot:read and write the plan graph at refs/the-valley/knots'
    'plan:show the plan graph as a tree, and what waits on you'
    'checks:print the checks the composed policy requires of a change'
    'tail:watch bus events scroll by'
    'replay:publish ref-updated events for the current refs of a repo'
    'self-update:install the tip of a branch of the-valley into your nix profile'
    'telemetry:read a valley host'"'"'s diagnostics over ssh'
  )
  if (( CURRENT == 2 )); then
    local -a verbs=("${topics[@]}" 'help:show help')
    _describe -t verbs 'valley verb' verbs
  elif (( CURRENT == 3 )) && [[ ${words[2]} == replay ]]; then
    _files -/
  elif (( CURRENT == 3 )) && [[ ${words[2]} == help ]]; then
    _describe -t topics 'valley help topic' topics
  elif [[ ${words[2]} == self-update && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--verbose:also say so when valley is up to date'
      '--retry:build the branch'"'"'s tip even if it failed before'
      '--rollback:reinstall the previous valley'
      '--pin:leave the current install alone until --unpin'
      '--unpin:let self-update install the branch'"'"'s tip again'
      '--repo:the repository, in place of valley.selfUpdate.repo'
      '--branch:the branch, in place of valley.selfUpdate.branch'
    )
    _describe -t options 'valley self-update option' opts
  elif (( CURRENT == 3 )) && [[ ${words[2]} == knot ]]; then
    local -a knotverbs=(
      'new:make a knot: new <type> <title>'
      'show:show a knot, its edges both ways and its comments'
      'log:list the commits that touched a knot or its comments'
      'list:list the knots'
      'set:set status, title, source, owner, target or graduated_into'
      'link:add a blocked-by, parent or change edge'
      'unlink:drop a blocked-by, parent or change edge'
      'edit:replace a knot'"'"'s body with stdin'
      'comment:add or edit a comment'
      'claim:claim a knot for a run'
      'unclaim:release a claim'
      'schema:print the types, statuses, fields and edges'
    )
    _describe -t knotverbs 'valley knot verb' knotverbs
  elif (( CURRENT == 4 )) && [[ ${words[2]} == knot && ${words[3]} == new ]]; then
    compadd outcome bug idea question
  elif [[ ${words[2]} == knot && ${words[CURRENT-1]} == --type ]]; then
    compadd outcome bug idea question
  elif [[ ${words[2]} == knot && ${words[CURRENT-1]} == --status ]]; then
    compadd active terminal open in-progress done abandoned closed raw exploring adopted graduated superseded discarded answered dropped
  elif [[ ${words[2]} == knot && ${words[CURRENT]} == -* ]]; then
    local -a opts=('--project:another project on the same host' '--json:print JSON')
    case ${words[3]} in
      new) opts+=('--parent:the outcome it belongs to' '--blocked-by:a knot it waits on' '--owner:the principal it waits on' '--target:the project the work lands in' '--body:read the body from stdin (-)') ;;
      list) opts+=('--type:only this type' '--status:only this status, active or terminal' '--owner:only this owner' '--ready:only the ready knots') ;;
      set) opts+=('--if:require <field>=<value> first' '--force:set it even if another write changed it') ;;
      link | unlink) opts+=('--blocked-by:a knot it waits on' '--parent:the outcome it belongs to' '--change:a change that does the work or records the answer' '--if:require <field>=<value> first') ;;
      edit) opts+=('--body:read the new body from stdin (-)' '--if:require <field>=<value> first') ;;
      show) opts+=('--at:show it as this commit of the graph left it') ;;
      comment) opts+=('-m:the comment' '--body:read the comment from stdin (-)' '--edit:replace the text of the comment with this id') ;;
      claim) opts+=('--run:the run claiming it' '--if:require <field>=<value> first') ;;
      unclaim) opts+=('--if:require <field>=<value> first') ;;
    esac
    _describe -t options 'valley knot option' opts
  elif [[ ${words[2]} == plan && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--project:another project on the same host'
      '--all:every project the serving host publishes'
      '--owner:read this principal as the operator'
      '--json:print valley-plan/v1 JSON'
      '--known-signers:the known-signers file a transfer statement is verified with'
      '--integrator-name:the name the integrator signs transfer statements under'
    )
    _describe -t options 'valley plan option' opts
  elif [[ ${words[2]} == checks && ${words[CURRENT-1]} == --cost ]]; then
    compadd quick slow
  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'
      '--names:print only the required check names, one per line'
      '--cost:with --names, only the quick or the slow checks'
    )
    _describe -t options 'valley checks option' opts
  elif [[ ${words[2]} == ready && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--head:the head to mark ready, already on origin'
      '--change:the change ID to record the version under'
      '--if-active:add the version only while the change is ready at this active head'
      '--stamp:carry the change ID in the head as a Change-Id trailer'
    )
    _describe -t options 'valley ready option' opts
  elif [[ ${words[2]} == ready && ${words[CURRENT-1]} == --(head|change|if-active) ]]; then
    return
  elif [[ ${words[2]} == approve && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--head:the exact head to approve, one of the change'"'"'s version heads'
      '--build-here:build the nix checks origin holds no evidence for on this machine'
      '--verbose:also print the refs, evidence, signers and digest approve read and published'
      '--approval-key:sign the approval with this ed25519 key file'
      '--approval-piv:sign the approval with the key in a YubiKey'"'"'s PIV slot'
    )
    _describe -t options 'valley approve option' opts
  elif [[ ${words[2]} == (approve|review) && ${words[CURRENT-1]} == --approval-key ]]; then
    _files
  elif [[ ${words[2]} == approve && ${words[CURRENT-1]} == --head ]]; then
    return
  elif [[ ${words[2]} == pending && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--all:every project the serving host publishes'
      '--repo:that one project'
      '--checks:the checks each change requires, by cost, and their state'
      '--drafts:list the drafts in full'
      '--branches:list the branches no change is on in full'
      '--json:print valley-pending/v1 JSON'
      '-v:each row in full, and why no change shows a knot'
      '--known-signers:the known-signers file a transfer statement is verified with'
      '--integrator-name:the name the integrator signs transfer statements under'
    )
    _describe -t options 'valley pending option' opts
  elif [[ ${words[2]} == changes && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--json:print valley-changes/v1 JSON'
      '--checks:the state of the checks each ready change requires'
      '--all:every project the serving host publishes'
      '--repo:that one project'
      '-v:say why no change shows a knot'
      '--known-signers:the known-signers file a transfer statement is verified with'
      '--integrator-name:the name the integrator signs transfer statements under'
    )
    _describe -t options 'valley changes option' opts
  elif [[ ${words[2]} == status && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--json:print the status as one valley-status/v1 JSON object'
      '-v:say why the object lists no knot'
      '--known-signers:the known-signers file a transfer statement is verified with'
      '--integrator-name:the name the integrator signs transfer statements under'
    )
    _describe -t options 'valley status option' opts
  elif [[ ${words[2]} == rebase && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '--known-signers:the known-signers file a transfer statement is verified with'
      '--integrator-name:the name the integrator signs transfer statements under'
    )
    _describe -t options 'valley rebase option' opts
  elif [[ ${words[2]} == review && ${words[CURRENT]} == -* ]]; then
    local -a opts=(
      '-v:say why no knot is shown'
      '--build-here:let approve build the nix checks origin holds no evidence for on this machine'
      '--repo:with no change, walk one project'
      '--approval-key:sign each approval with this ed25519 key file'
      '--approval-piv:sign each approval with the key in a YubiKey'"'"'s PIV slot'
    )
    _describe -t options 'valley review option' opts
  elif [[ ${words[2]} == (review|approve|rebase|status|unready|withdraw) ]] \
    && { (( CURRENT == 3 )) || [[ ${words[2]} == (status|approve) ]]; }; then
    _valley_change_names ${words[2]}
  elif [[ ${words[2]} == ready ]]; then
    _valley_branch_names ready
  fi
}

# Cached topic branches on origin. Review, approve, rebase, unready, withdraw
# and ready filter out merged branches; status needs those too. Silent
# outside a git repo — no errors mid-typing.
_valley_branch_names() {
  local -a branches selection
  selection=()
  [[ $1 != status ]] && 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
  return 0
}

# What a verb that takes a change offers: the handles in the cache valley
# pending and valley changes write, each described by its title and ready
# changes first, then the branches. Without the cache, the branches alone.
# The cache is $(git rev-parse --git-common-dir)/valley/handles, one line
# per change: handle, state, branch, title, tab-separated.
_valley_change_names() {
  local dir cache line
  local -a fields described
  dir=$(git rev-parse --git-common-dir 2>/dev/null)
  cache=$dir/valley/handles
  if [[ -n $dir && -r $cache ]]; then
    while IFS= read -r line; do
      fields=("${(@ps:\t:)line}")
      [[ -n ${fields[1]} ]] || continue
      described+=("${fields[1]//:/\\:}:${fields[4]}")
    done < $cache
    (( ${#described} )) && _describe -V -t handles 'change handle' described
  fi
  _valley_branch_names $1
}

_valley "$@"
