#!/usr/bin/env bash
# completions.sh — bundled tab completion for `mm-harness` (bash + zsh).
#
# Static parts (commands, positional targets, per-command flags) mirror the
# mm-harness surface. Dynamic parts are sourced live from the hidden
# `mm-harness completion-candidates <actions|recipes>` command (per-checkout cached):
#   call <TAB>   → action names from the adapter manifest
#   run  <TAB>   → recipe files + named recipes from the recipe library
# so completion reflects the installed overlay's real vocabulary. A candidate read
# that fails is silently empty — completion never blocks the shell.
#
# Install: source this file from ~/.zshrc / ~/.bashrc
#   (see: mm-harness completions install).

# Resolve the mm-harness bin: prefer one on PATH, else this checkout's bin.
_mmh_bin() {
  if command -v mm-harness >/dev/null 2>&1; then
    command -v mm-harness
    return 0
  fi
  if [ -n "${BASH_SOURCE[0]:-}" ]; then
    local here
    here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." 2>/dev/null && pwd)" || true
    if [ -n "$here" ] && [ -x "$here/bin/mm-harness" ]; then
      printf '%s\n' "$here/bin/mm-harness"
      return 0
    fi
  fi
  return 1
}

_mmh_commands="launch stop logs debug reload fixtures actions call run doctor check checklist execution-template recipe-quality install verify cleanup completions"

# Per-command flags (static, from the mm-harness surface).
_mmh_flags_for() {
  case "$1" in
    launch)   printf '%s' "--build --watch --verify --sidepanel --fullscreen --runway --device --cdp-port --watcher-port --heal --adapter --target --json" ;;
    stop)     printf '%s' "--port --target --json" ;;
    logs)     printf '%s' "--full --events --source --adapter --target --json" ;;
    debug)    printf '%s' "--worker --dev-menu --adapter --target --json" ;;
    reload)   printf '%s' "--adapter --platform --target --json" ;;
    fixtures) printf '%s' "--from --dev --force --fixture --adapter --target --json" ;;
    checklist) printf '%s' "" ;;
    execution-template) printf '%s' "--dir --domain-dir --project-worker --project-name --package-templates --package-id --flow --run-mode --platform --domain --id --provenance --include-shadowed --no-include-shadowed --title --force --json" ;;
    actions)  printf '%s' "--adapter --action --kind --raw --action-manifest --target --json" ;;
    call)     printf '%s' "--list --arg --adapter --target --artifacts-dir --action-manifest --heal --json" ;;
    run)      printf '%s' "--list --describe --plan --adapter --artifacts-dir --target --library --cdp-port --heal --record-video --json" ;;
    doctor)   printf '%s' "--adapter --target --fix --json" ;;
    install|verify|cleanup) printf '%s' "--adapter --target --json" ;;
    *)        printf '%s' "" ;;
  esac
}

# Dynamic candidates from the DISCOVER layer (silent empty on any failure).
_mmh_actions() { local b; b="$(_mmh_bin)" || return 0; "$b" completion-candidates actions 2>/dev/null; }
_mmh_recipes() { local b; b="$(_mmh_bin)" || return 0; "$b" completion-candidates recipes 2>/dev/null; }

# ── Bash ────────────────────────────────────────────────────────────────
if [ -n "${BASH_VERSION:-}" ]; then
  _mmh_complete_bash() {
    local cur prev words cword
    _get_comp_words_by_ref -n : cur prev words cword 2>/dev/null || {
      cur="${COMP_WORDS[COMP_CWORD]}"
      prev="${COMP_WORDS[COMP_CWORD-1]}"
      words=("${COMP_WORDS[@]}")
      cword=$COMP_CWORD
    }

    if [ "$cword" -eq 1 ]; then
      COMPREPLY=($(compgen -W "$_mmh_commands" -- "$cur"))
      return
    fi

    local cmd="${words[1]}"
    case "$cur" in
      -*) COMPREPLY=($(compgen -W "$(_mmh_flags_for "$cmd")" -- "$cur")); return ;;
    esac

    case "$cmd" in
      launch)      [ "$cword" -eq 2 ] && COMPREPLY=($(compgen -W "ios android" -- "$cur")) ;;
      fixtures)    [ "$cword" -eq 2 ] && COMPREPLY=($(compgen -W "init sync set reset generate finalize" -- "$cur")) ;;
      checklist)   [ "$cword" -eq 2 ] && COMPREPLY=($(compgen -W "mark closeout" -- "$cur")) ;;
      completions) [ "$cword" -eq 2 ] && COMPREPLY=($(compgen -W "install bash zsh status" -- "$cur")) ;;
      call)        [ "$cword" -eq 2 ] && COMPREPLY=($(compgen -W "$(_mmh_actions)" -- "$cur")) ;;
      run)         COMPREPLY=($(compgen -f -- "$cur"; compgen -W "$(_mmh_recipes)" -- "$cur")) ;;
      *)           COMPREPLY=($(compgen -W "$(_mmh_flags_for "$cmd")" -- "$cur")) ;;
    esac
  }
  # mmdev-harness is the documented dev-checkout alias; complete it identically.
  complete -F _mmh_complete_bash mm-harness 2>/dev/null || true
  complete -F _mmh_complete_bash mmdev-harness 2>/dev/null || true
fi

# ── Zsh ─────────────────────────────────────────────────────────────────
if [ -n "${ZSH_VERSION:-}" ]; then
  _mmh_complete_zsh() {
    local -a candidates
    local cmd="${words[2]:-}"

    if (( CURRENT == 2 )); then
      candidates=(${=_mmh_commands})
      compadd -a candidates
      return
    fi

    local cur="${words[CURRENT]}"
    if [[ "$cur" == -* ]]; then
      candidates=(${=$(_mmh_flags_for "$cmd")})
      compadd -a candidates
      return
    fi

    case "$cmd" in
      launch)      (( CURRENT == 3 )) && { candidates=(ios android); compadd -a candidates; } ;;
      fixtures)    (( CURRENT == 3 )) && { candidates=(init sync set reset generate finalize); compadd -a candidates; } ;;
      checklist)   (( CURRENT == 3 )) && { candidates=(mark closeout); compadd -a candidates; } ;;
      completions) (( CURRENT == 3 )) && { candidates=(install bash zsh status); compadd -a candidates; } ;;
      call)        (( CURRENT == 3 )) && { candidates=("${(@f)$(_mmh_actions)}"); compadd -a candidates; } ;;
      run)         candidates=("${(@f)$(_mmh_recipes)}"); compadd -a candidates; _files ;;
      *)           candidates=(${=$(_mmh_flags_for "$cmd")}); compadd -a candidates ;;
    esac
  }

  if (( $+functions[compdef] )); then
    compdef _mmh_complete_zsh mm-harness mmdev-harness
  else
    autoload -Uz compinit 2>/dev/null && compinit -u 2>/dev/null
    (( $+functions[compdef] )) && compdef _mmh_complete_zsh mm-harness mmdev-harness
  fi
fi
