#!/usr/bin/env bash
# harness — Harness Engineering CLI (STORY-014 T-PKG-002).
#
# Usage: harness <command> [args]
#
# Commands:
#   init     Bootstrap harness in the current repo (detect, config, workspace)
#   run      Run the orchestrator loop (all flags pass through, e.g. --dry-run)
#   story    Story tooling: new | list | status | manifest | close | start | ...
#   queue    Queue helpers: add <STORY-ID> | resolve <TASK-ID> done|requeue | bug
#   status   Generated status report (queue, stories, bugs, QA health, blockers)
#   cancel   Stop one in-flight task (lane) without stopping the run
#   evidence Read a task's evidence bundle: show <TASK-ID> (ACs + evidence items)
#   baseline Record every gate's result on the default branch (show | status | --report)
#   config   Project config helpers: sync
#   doctor   Environment + config preflight (pass/fail report)
#   profile  Repository/stack profile: detect (propose one from repo facts)
#   create   Scaffold extension | skill | domain
#   upgrade  Pull the vendored engine to its pinned channel (+ --config migrations)
#   version  Print engine version and supported config schema
#
# `harness <command> --help` prints the subcommand's own help.
# Unknown commands print this help and exit 2.
set -euo pipefail

# bash 3.2 (macOS /bin/bash) refused up front, before any bash-4 syntax runs
# (T-PB-332d). Found without realpath when possible (old macOS lacks it); a
# symlinked `harness` on PATH falls back to it.
_guard_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
[ -f "${_guard_dir}/../core/orchestrator/lib/bash-guard.sh" ] || _guard_dir="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"
# shellcheck source=../core/orchestrator/lib/bash-guard.sh
source "${_guard_dir}/../core/orchestrator/lib/bash-guard.sh"
harness_require_bash4 "${BASH_VERSINFO[0]}" || exit 2

CLI_DIR="$(cd "$(dirname "$(realpath "${BASH_SOURCE[0]}")")" && pwd)"
# shellcheck source=_prelude.sh
source "${CLI_DIR}/_prelude.sh"

cmd="${1:-}"
[[ $# -gt 0 ]] && shift

case "$cmd" in
  ""|-h|--help|help)
    cli_help "${BASH_SOURCE[0]}"
    exit 0
    ;;
  init|run|story|queue|status|cancel|evidence|baseline|config|doctor|profile|create|upgrade|version)
    exec bash "${CLI_DIR}/cmd-${cmd}.sh" "$@"
    ;;
  *)
    echo "harness: unknown command '${cmd}'" >&2
    cli_help "${BASH_SOURCE[0]}" >&2
    exit 2
    ;;
esac
