#compdef sensei

# Zsh completion for Jobbernaut Sensei CLI
#
# Install (add to ~/.zshrc):
#   fpath=(/path/to/jobbernaut-sensei/src/completions $fpath)
#   autoload -Uz compinit && compinit

# ── helpers ───────────────────────────────────────────────────────────────────

_jobbernaut_repo_root() {
  # Walk up from the completion script's real location to the repo root
  echo "${${(%):-%x}:A:h:h:h}"
}

_jobbernaut_problems() {
  local root
  root="$(_jobbernaut_repo_root)/problems"
  [[ -d "$root" ]] || return

  local -a names numbers
  while IFS= read -r -d '' file; do
    local base stem
    base="${file:t}"          # filename with ext
    stem="${base:r}"          # strip .py
    local parts=("${(@s/-/)stem}")
    if [[ "${parts[1]}" =~ ^[0-9]+$ ]]; then
      numbers+=("${parts[1]}")
      local title="${(j: :)parts[2,-1]:l}"
      names+=("${stem}")
    fi
  done < <(find "$root" -name '*.py' -print0 2>/dev/null)

  # Deduplicate and expose as completions
  compadd -a numbers
  compadd -a names
}

_jobbernaut_categories() {
  local root
  root="$(_jobbernaut_repo_root)/problems"
  [[ -d "$root" ]] || return
  local -a cats
  cats=("${root}"/*(/:t))
  compadd -a cats
}

_jobbernaut_difficulties() {
  compadd easy medium hard
}

# ── sensei subcommands ────────────────────────────────────────────────────────

_sensei_commands() {
  _values "command" \
    "revisit[Run daily review]" \
    "new[Scaffold a new problem]" \
    "open[Open a problem in editor/browser]" \
    "mark[Mark a problem as solved]"
}

_sensei() {
  local curcontext="$curcontext" state line
  typeset -A opt_args

  # Top-level: offer subcommands
  if (( CURRENT == 2 )); then
    _sensei_commands
    return
  fi

  # Delegate to subcommand-specific completions
  local cmd="${words[2]}"
  shift 2 words
  CURRENT=$(( CURRENT - 2 ))

  case "$cmd" in
    mark)
      _arguments \
        '1:problem:_jobbernaut_problems'
      ;;
    open)
      _arguments \
        '--no-browser[skip opening the browser]' \
        '*:problem:_jobbernaut_problems'
      ;;
    new)
      _arguments \
        '1:number:(1 2 3)' \
        '2:slug:' \
        '3:category:_jobbernaut_categories' \
        '(-d --difficulty)'{-d,--difficulty}'[difficulty]:difficulty:_jobbernaut_difficulties' \
        '(-t --tags)'{-t,--tags}'[topic tags]:tag:' \
        '--open[open file in editor after creation]'
      ;;
    revisit)
      _arguments \
        '--all[show all problems including far future]' \
        '--export[export to CSV]' \
        '--export-md[export to Markdown]' \
        '--topic[filter by topic tag]:topic:'
      ;;
  esac
}

_sensei "$@"
