#!/bin/bash
#
# Warmup Script for Eagle Server
#
# This script warms up the JIT compiler before switching traffic to a new instance.
# It uses the Go warmup tool which:
# 1. Creates a test game via bidirectional streaming
# 2. Posts an Improve command
# 3. Verifies action results and new commands
# 4. Cleans up the test game
#
# Usage: ./warmup-eagle.sh HOST:PORT
#
# Example:
#   ./warmup-eagle.sh localhost:40032
#   ./warmup-eagle.sh localhost:40034
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

HOST="${1:-localhost:40032}"

log_info "Warming up Eagle server at ${HOST}..."

# Try to find the Go warmup tool
WARMUP_TOOL=""

# Check if we're in the project directory with bazel
if [ -f "${PROJECT_ROOT}/WORKSPACE" ] || [ -f "${PROJECT_ROOT}/WORKSPACE.bazel" ]; then
    # Try to find the pre-built binary
    BAZEL_BIN="${PROJECT_ROOT}/bazel-bin/src/main/go/net/eagle0/warmup/warmup_/warmup"
    if [ -x "${BAZEL_BIN}" ]; then
        WARMUP_TOOL="${BAZEL_BIN}"
    fi
fi

# Check for the warmup tool in common locations (for deployed environments)
if [ -z "${WARMUP_TOOL}" ]; then
    for path in \
        "${SCRIPT_DIR}/bin/warmup" \
        "/opt/eagle0/scripts/bin/warmup" \
        "/opt/eagle0/bin/warmup" \
        "/usr/local/bin/eagle-warmup" \
        "${SCRIPT_DIR}/warmup"; do
        if [ -x "${path}" ]; then
            WARMUP_TOOL="${path}"
            break
        fi
    done
fi

# If we found the Go tool, use it
if [ -n "${WARMUP_TOOL}" ]; then
    log_info "Using Go warmup tool: ${WARMUP_TOOL}"
    # Use 5 minute timeout to allow for slow operations on cold JVM
    if "${WARMUP_TOOL}" --address="${HOST}" --timeout=300s; then
        log_info "Warmup complete!"
        exit 0
    else
        log_error "Go warmup tool failed"
        exit 1
    fi
fi

# Fallback to grpcurl-based warmup
log_warn "Go warmup tool not found, falling back to grpcurl"

# Check for grpcurl
if ! command -v grpcurl &> /dev/null; then
    log_error "Neither Go warmup tool nor grpcurl is available"
    log_error "Build the warmup tool with: bazel build //src/main/go/net/eagle0/warmup"
    log_error "Or install grpcurl: brew install grpcurl (macOS)"
    exit 1
fi

# Warmup iterations
WARMUP_ITERATIONS=3

# 1. Call GetRunningGames multiple times - this exercises the gRPC layer and basic game access
log_info "Warming up GetRunningGames..."
for i in $(seq 1 ${WARMUP_ITERATIONS}); do
    RESULT=$(grpcurl -plaintext -d '{}' "${HOST}" net.eagle0.eagle.api.Eagle/GetRunningGames 2>&1) || true
    if echo "$RESULT" | grep -q "games\|{}"; then
        echo -n "."
    else
        log_error "GetRunningGames failed on iteration $i"
        exit 1
    fi
done
echo " done"

# 2. Call GetSettings - exercises settings loading
log_info "Warming up GetSettings..."
for i in $(seq 1 ${WARMUP_ITERATIONS}); do
    if grpcurl -plaintext -d '{}' "${HOST}" net.eagle0.eagle.api.Eagle/GetSettings > /dev/null 2>&1; then
        echo -n "."
    else
        log_warn "GetSettings failed on iteration $i (non-fatal)"
    fi
done
echo " done"

# 3. Call AddSettings with empty list - exercises settings path
log_info "Warming up AddSettings..."
for i in $(seq 1 ${WARMUP_ITERATIONS}); do
    if grpcurl -plaintext -d '{"settings": []}' "${HOST}" net.eagle0.eagle.api.Eagle/AddSettings > /dev/null 2>&1; then
        echo -n "."
    else
        log_warn "AddSettings failed on iteration $i (non-fatal)"
    fi
done
echo " done"

# Final health check
log_info "Verifying server health..."
if grpcurl -plaintext -d '{}' "${HOST}" net.eagle0.eagle.api.Eagle/GetRunningGames > /dev/null 2>&1; then
    log_info "Health check passed"
else
    log_error "Health check failed"
    exit 1
fi

log_info ""
log_info "Warmup complete (basic mode - bidirectional streaming warmup not available)!"
log_info "The JIT should be warmed for:"
log_info "  - gRPC layer and protobuf parsing"
log_info "  - Settings loading and management"
log_info ""
log_warn "Note: For full warmup including game creation and command processing,"
log_warn "      build and use the Go warmup tool: bazel build //src/main/go/net/eagle0/warmup"
