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

PROXYM_URL="${PROXYM_URL:-http://localhost:4001}"
PYTHON_BIN="${PYTHON_BIN:-.venv/bin/python}"
RUN_LIVE=1
RUN_GUI=1

usage() {
  cat <<'EOF'
Usage: check_dashboard.sh [--url URL] [--skip-live] [--skip-gui]

Checks the dashboard HTML/JSX endpoints and optionally runs the GUI test suite.
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --url)
      PROXYM_URL="${2:-}"
      shift 2
      ;;
    --skip-live)
      RUN_LIVE=0
      shift
      ;;
    --skip-gui)
      RUN_GUI=0
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
PASS=0
FAIL=0

log_pass() {
  printf '  %bPASS%b: %s\n' "$GREEN" "$NC" "$1"
  PASS=$((PASS + 1))
}

log_fail() {
  printf '  %bFAIL%b: %s\n' "$RED" "$NC" "$1" >&2
  FAIL=$((FAIL + 1))
}

log_info() {
  printf '  %bINFO%b: %s\n' "$YELLOW" "$NC" "$1"
}

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Missing required command: $1" >&2
    exit 1
  fi
}

check_contains() {
  local path="$1"
  local needle="$2"
  local label="$3"
  local body

  body="$(curl -fsS "${PROXYM_URL}${path}")"
  if grep -Fq "$needle" <<<"$body"; then
    log_pass "$label"
  else
    log_fail "$label (missing: ${needle})"
  fi
}

check_status() {
  local path="$1"
  local label="$2"
  local code

  code="$(curl -fsS -o /dev/null -w '%{http_code}' "${PROXYM_URL}${path}" || true)"
  if [[ "$code" == "200" ]]; then
    log_pass "$label"
  else
    log_fail "$label (HTTP ${code})"
  fi
}

main() {
  if [[ "$RUN_LIVE" -eq 1 ]]; then
    require_cmd curl
    echo "Checking dashboard at ${PROXYM_URL}"
    check_status "/health" "Health endpoint is reachable"
    check_contains "/dashboard-ui" "/dashboard-tasks.jsx" "Dashboard HTML loads unified tasks bundle"
    check_contains "/dashboard-ui" "/dashboard-system.jsx" "Dashboard HTML loads system bundle"
    check_contains "/dashboard-ui" "/dashboard-setup.jsx" "Dashboard HTML loads setup bundle"
    check_contains "/dashboard-tasks.jsx" "filterAgent" "Tasks panel includes agent filter (human/auto)"
    check_contains "/dashboard-tasks.jsx" "TableExport" "Tasks panel includes table export"
  fi

  if [[ "$RUN_GUI" -eq 1 ]]; then
    require_cmd "$PYTHON_BIN"
    echo "Running GUI tests via ${PYTHON_BIN} -m pytest tests/gui/ -q"
    "$PYTHON_BIN" -m pytest tests/gui/ -q
  fi

  if [[ "$FAIL" -gt 0 ]]; then
    echo "Dashboard checks completed with ${FAIL} failure(s) and ${PASS} pass(es)." >&2
    exit 1
  fi

  if [[ "$RUN_LIVE" -eq 1 ]]; then
    echo "Live dashboard checks passed (${PASS} assertions)."
  fi
}

main "$@"
