#!/usr/bin/env bash
###############################################################################
# dry-run-all-examples.sh — Verify All Example Projects Work Correctly
#
# This script runs --dry-run on all example projects to ensure everything
# works without making actual changes. It's a smoke test for the examples.
#
# Usage:
#   bash examples/dry-run-all-examples.sh           # dry-run all examples
#   bash examples/dry-run-all-examples.sh --verbose   # verbose output
#   bash examples/dry-run-all-examples.sh --quick     # skip npm/node checks
#
# Examples tested:
#   1. simple-3-tickets   — Basic 3-ticket workflow
#   2. multi-project      — Multiple projects with sprints
#   3. todo-app-ts       — TypeScript TODO app with build verification
###############################################################################
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROXYM_URL="${PROXYM_URL:-http://localhost:4000}"
VERBOSE=false
QUICK=false
FAILED=0
PASSED=0

# ── Colors ─────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; BOLD='\033[1m'; DIM='\033[2m'; RESET='\033[0m'

_hdr()  { echo -e "\n${BOLD}${CYAN}═══ $1 ═══${RESET}"; }
_ok()   { echo -e "  ${GREEN}✓${RESET} $1"; }
_warn() { echo -e "  ${YELLOW}⚠${RESET} $1"; }
_fail() { echo -e "  ${RED}✗${RESET} $1"; }
_info() { echo -e "  ${DIM}$1${RESET}"; }

# ── Parse arguments ────────────────────────────────────────────────────────

while [[ $# -gt 0 ]]; do
  case "$1" in
    --verbose|-v)  VERBOSE=true; shift ;;
    --quick|-q)    QUICK=true; shift ;;
    --help|-h)
      sed -n '2,/^###/p' "$0" | head -n -1 | sed 's/^# \?//'
      exit 0
      ;;
    *) echo "Unknown option: $1"; exit 1 ;;
  esac
done

# ── Pre-checks ─────────────────────────────────────────────────────────────

_hdr "Pre-Checks"

# Check proxym server
if curl -s "$PROXYM_URL/status" >/dev/null 2>&1 || curl -s "$PROXYM_URL/health" >/dev/null 2>&1; then
  _ok "Proxym server responding at $PROXYM_URL"
else
  _warn "Proxym server not detected at $PROXYM_URL (examples may fail)"
fi

# Check for required tools
if ! command -v proxym &>/dev/null; then
  _fail "'proxym' CLI not found in PATH"
  exit 1
fi
_ok "proxym CLI available"

if ! $QUICK && command -v node &>/dev/null; then
  _ok "Node.js $(node --version)"
fi

# ── Run dry-run on an example ───────────────────────────────────────────────

_run_example() {
  local name="$1"
  local path="$2"
  local extra_args="${3:-}"

  echo ""
  echo -e "${BOLD}${CYAN}▶ $name${RESET}"

  if [[ ! -f "$path" ]]; then
    _fail "Script not found: $path"
    ((FAILED++))
    return 1
  fi

  if $VERBOSE; then
    if bash "$path" --dry-run $extra_args --proxy "$PROXYM_URL" 2>&1; then
      _ok "Dry-run completed successfully"
      ((PASSED++))
      return 0
    else
      _fail "Dry-run failed"
      ((FAILED++))
      return 1
    fi
  else
    local output
    if output=$(bash "$path" --dry-run $extra_args --proxy "$PROXYM_URL" 2>&1); then
      _ok "Dry-run passed"
      if echo "$output" | grep -q "\[dry-run\]"; then
        _info "Dry-run markers found ✓"
      fi
      ((PASSED++))
      return 0
    else
      _fail "Dry-run failed"
      echo "$output" | head -20 | sed 's/^/    /'
      ((FAILED++))
      return 1
    fi
  fi
}

# ── Examples ───────────────────────────────────────────────────────────────

_hdr "Running Example Dry-Runs"

# Example 1: Simple 3-Tickets
_run_example "Simple 3-Tickets" \
  "$SCRIPT_DIR/simple-3-tickets/run.sh" \
  "--project-dir /tmp/test-simple-demo"

# Example 2: Multi-Project
_run_example "Multi-Project (2 projects + sprints)" \
  "$SCRIPT_DIR/multi-project/run.sh"

# Example 3: TypeScript TODO App
_run_example "TypeScript TODO App" \
  "$SCRIPT_DIR/todo-app-ts/run.sh" \
  "--project-dir /tmp/test-todo-app-ts"

# ── Summary ─────────────────────────────────────────────────────────────────

echo ""
echo -e "${BOLD}╔══════════════════════════════════════════════════════════════╗${RESET}"
echo -e "${BOLD}║              Dry-Run Test Summary                           ║${RESET}"
echo -e "${BOLD}╠══════════════════════════════════════════════════════════════╣${RESET}"
echo -e "${BOLD}║${RESET}  Total:   $((PASSED + FAILED)) examples"
echo -e "${BOLD}║${RESET}  ${GREEN}Passed: $PASSED${RESET}"
if [[ $FAILED -gt 0 ]]; then
  echo -e "${BOLD}║${RESET}  ${RED}Failed: $FAILED${RESET}"
fi
echo -e "${BOLD}║${RESET}"
echo -e "${BOLD}║${RESET}  Examples tested:"
echo -e "${BOLD}║${RESET}    • simple-3-tickets  — Basic workflow"
echo -e "${BOLD}║${RESET}    • multi-project      — Multiple projects + sprints"
echo -e "${BOLD}║${RESET}    • todo-app-ts       — TypeScript project"
echo -e "${BOLD}╚══════════════════════════════════════════════════════════════╝${RESET}"

if [[ $FAILED -eq 0 ]]; then
  echo ""
  _ok "All examples passed dry-run! ✓"
  exit 0
else
  echo ""
  _fail "$FAILED example(s) failed dry-run"
  exit 1
fi
