#!/usr/bin/env bash
# Preflight check for E2E tests — validates system dependencies.
# Run before E2E suite to catch missing tools early.

set -euo pipefail

OK=0
WARN=0

check() {
  local name="$1" cmd="$2"
  if eval "$cmd" >/dev/null 2>&1; then
    echo "  ✓ $name"
  else
    echo "  ✗ $name"
    return 1
  fi
}

echo "E2E Preflight Check"
echo "==================="

echo ""
echo "Required:"

if ! check "tauri-driver" "command -v tauri-driver"; then
  echo "    Install: cargo install tauri-driver"
  OK=1
fi

if ! check "debug binary" "test -f target/debug/agent-orchestrator"; then
  echo "    Build: cargo tauri build --debug --no-bundle"
  OK=1
fi

# Display server (Linux only)
if [[ "$(uname)" == "Linux" ]]; then
  if [[ -n "${DISPLAY:-}" ]] || [[ -n "${WAYLAND_DISPLAY:-}" ]]; then
    echo "  ✓ display server (DISPLAY=$DISPLAY)"
  else
    echo "  ✗ display server — no DISPLAY or WAYLAND_DISPLAY set"
    echo "    Use: xvfb-run --auto-servernum npm run test:e2e"
    OK=1
  fi
fi

echo ""
echo "Optional (LLM judge):"

if command -v claude >/dev/null 2>&1; then
  echo "  ✓ Claude CLI ($(which claude))"
elif [[ -n "${ANTHROPIC_API_KEY:-}" ]]; then
  echo "  ✓ ANTHROPIC_API_KEY set"
else
  echo "  ~ Claude CLI not found, ANTHROPIC_API_KEY not set"
  echo "    LLM-judged tests will be skipped"
  WARN=1
fi

echo ""
if [[ $OK -ne 0 ]]; then
  echo "FAILED — missing required dependencies"
  exit 1
elif [[ $WARN -ne 0 ]]; then
  echo "PASSED with warnings"
else
  echo "ALL CHECKS PASSED"
fi
