#!/usr/bin/env bash
set -euo pipefail

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
source "$repo_root/scripts/lib-hypertwist-gitnexus.sh"
analysis_root="$repo_root/.gitnexus-source-only-root"
analysis_meta_path="$analysis_root/.gitnexus/meta.json"
require_index="${HYPERTWIST_GITNEXUS_STATUS_REQUIRE_INDEX:-0}"

if [[ ! -d "$analysis_root" ]]; then
  message="HyperTwist GitNexus source-only analysis root is currently absent. This is normal after hygiene because .gitnexus-source-only-root is disposable. Run scripts/run-hypertwist-gitnexus-analyze.sh to recreate it before requesting status."
  if [[ "$require_index" == "1" ]]; then
    echo "$message" >&2
    exit 1
  fi

  echo "$message"
  exit 0
fi

if [[ ! -f "$analysis_meta_path" ]]; then
  first_message="HyperTwist GitNexus source-only analysis root exists, but no completed index metadata is available yet."
  second_message="This can happen during an interrupted refresh or immediately after rebuilding the disposable bounded mirror. Rerun scripts/run-hypertwist-gitnexus-analyze.sh to recreate a finished index before requesting status again."
  if [[ "$require_index" == "1" ]]; then
    echo "$first_message" >&2
    echo "$second_message" >&2
    exit 1
  fi

  echo "$first_message"
  echo "$second_message"
  exit 0
fi

cd "$analysis_root"

local_cli_available=0
if local_gitnexus_cli="$(hypertwist_gitnexus_resolve_local_cli "$repo_root")"; then
  local_cli_available=1
fi

if [[ "$local_cli_available" -eq 1 ]]; then
  if [[ "${HYPERTWIST_GITNEXUS_DEBUG_LOCAL:-0}" == "1" ]]; then
    if node "$local_gitnexus_cli" status "$@"; then
      exit 0
    fi
  elif node "$local_gitnexus_cli" status "$@" 2>/dev/null; then
    exit 0
  fi

  echo "Local retained GitNexus CLI status failed after passing the runtime probe. Falling back to npx gitnexus@latest." >&2
fi

exec npx -y gitnexus@latest status "$@" 2>/dev/null
