#!/bin/bash
set -e

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

cd "$LOCAL_DEV_DIR"

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[OK]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }

cleanup() {
    info "Stopping background processes..."
    jobs -p | grep -v '^$' | xargs kill 2>/dev/null || true
    wait 2>/dev/null || true
}
trap cleanup EXIT INT TERM

info "Starting local development environment..."
echo ""

if ! docker info >/dev/null 2>&1; then
    echo "ERROR: Docker is not running. Please start Docker first."
    exit 1
fi

info "Killing any existing processes on service ports..."
for port in 10000 10002 18080 19090 19092; do
    lsof -ti:$port | xargs kill -9 2>/dev/null || true
done
sleep 1

info "Step 1/4: Starting infrastructure (MySQL, mock-dpm, Kind, TiDB Operator)..."
make local-up

# Export kind kubeconfig and set context
info "Configuring kubeconfig for kind cluster..."
kind export kubeconfig --name csng-dev
KUBECONFIG_PATH="${HOME}/.kube/config"

# Verify kubectl can connect
if ! kubectl cluster-info >/dev/null 2>&1; then
    echo "ERROR: Cannot connect to kind cluster. Check kubeconfig."
    exit 1
fi
success "kubectl connected to kind cluster"

echo ""
info "Step 2/4: Starting executor in background..."
cd "$REPO_ROOT"
TIINF_POD_NAME=csng-executor-local-0 go run ./cmd/executor server --mock --config hack/local-dev/executor-config.yaml --kubeconfig "$KUBECONFIG_PATH" > /tmp/executor.log 2>&1 &
EXECUTOR_PID=$!
sleep 2

if ! kill -0 $EXECUTOR_PID 2>/dev/null; then
    echo "ERROR: Executor failed to start. Check /tmp/executor.log"
    tail -20 /tmp/executor.log
    exit 1
fi
success "Executor started (PID: $EXECUTOR_PID, log: /tmp/executor.log)"

echo ""
info "Step 3/4: Starting cluster-service in background..."
TIINF_POD_NAME=csng-server-local-0 go run ./cmd/cluster_ng_server server --mock --config hack/local-dev/config.yaml --kubeconfig "$KUBECONFIG_PATH" > /tmp/cluster-service.log 2>&1 &
CLUSTER_SERVICE_PID=$!
sleep 3

if ! kill -0 $CLUSTER_SERVICE_PID 2>/dev/null; then
    echo "ERROR: Cluster service failed to start. Check /tmp/cluster-service.log"
    tail -20 /tmp/cluster-service.log
    exit 1
fi
success "Cluster service started (PID: $CLUSTER_SERVICE_PID, log: /tmp/cluster-service.log)"

echo ""
info "Step 4/4: Waiting for services to be ready..."
sleep 3

for i in {1..30}; do
    if grpcurl -plaintext localhost:10000 list >/dev/null 2>&1; then
        success "Cluster service gRPC is ready!"
        break
    fi
    if [ $i -eq 30 ]; then
        warn "Cluster service may not be fully ready yet"
    fi
    sleep 1
done

echo ""
echo "============================================"
echo -e "${GREEN}Local environment is ready!${NC}"
echo "============================================"
echo ""
echo "Services:"
echo "  - MySQL:            localhost:3306"
echo "  - Mock-DPM:         localhost:10001 (gRPC), localhost:8081 (admin)"
echo "  - Executor:         localhost:10002 (PID: $EXECUTOR_PID)"
echo "  - Cluster Service:  localhost:10000 (PID: $CLUSTER_SERVICE_PID)"
echo "  - Kind K8s:         kubectl configured"
echo "  - TiDB Operator:    v2.1.0-alpha.15"
echo ""
echo "Logs:"
echo "  - Executor:         tail -f /tmp/executor.log"
echo "  - Cluster Service:  tail -f /tmp/cluster-service.log"
echo ""
echo "Test commands:"
echo "  grpcurl -plaintext localhost:10000 list"
echo "  grpcurl -plaintext -d '{}' localhost:10000 cluster_service_ng.v1beta.SharedPoolService/ListSharedPools"
echo ""
echo "Press Ctrl+C to stop all services..."
echo ""

while kill -0 $EXECUTOR_PID 2>/dev/null && kill -0 $CLUSTER_SERVICE_PID 2>/dev/null; do
    sleep 5
done

warn "One of the services exited unexpectedly"
echo "Executor log (last 20 lines):"
tail -20 /tmp/executor.log
echo ""
echo "Cluster service log (last 20 lines):"
tail -20 /tmp/cluster-service.log
