#!/bin/bash

# Hytale F2P Local Development - Start Script
# Usage: ./start.sh

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

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

echo ""
echo -e "${CYAN}========================================"
echo "Hytale F2P Local Dev Environment"
echo -e "========================================${NC}"
echo ""

# Create data directories
mkdir -p "$SCRIPT_DIR/data/auth" "$SCRIPT_DIR/data/kvrocks"

# Start Docker services
echo -e "${GREEN}Building and starting services...${NC}"
cd "$SCRIPT_DIR"

# Stop existing
docker compose down 2>/dev/null || true

# Build and start
docker compose up -d --build

# Wait for ready
echo -n "Waiting for server"
for i in {1..30}; do
    if curl -s http://localhost:3000/health > /dev/null 2>&1; then
        echo ""
        echo -e "${GREEN}Server ready!${NC}"
        break
    fi
    if [ $i -eq 30 ]; then
        echo ""
        echo -e "${RED}Server failed to start! Check logs:${NC}"
        docker compose logs auth-server
        exit 1
    fi
    echo -n "."
    sleep 1
done

echo ""
echo -e "${CYAN}========================================"
echo "Services Running"
echo -e "========================================${NC}"
echo ""
docker compose ps
echo ""
echo -e "${CYAN}Endpoints:${NC}"
echo -e "  Auth Server HTTP:  ${GREEN}http://localhost:3000${NC}"
echo -e "  Auth Server HTTPS: ${GREEN}https://localhost:3443${NC}"
echo -e "  Debug Dashboard:   ${GREEN}http://localhost:3000/debug${NC}"
echo -e "  Admin Dashboard:   ${GREEN}http://localhost:3000/admin${NC} (password: localdev)"
echo -e "  JWKS:              ${GREEN}http://localhost:3000/.well-known/jwks.json${NC}"
echo -e "  Kvrocks:           localhost:6666"
echo ""
echo -e "${CYAN}========================================"
echo "Using with Launcher"
echo -e "========================================${NC}"
echo ""
echo -e "Start launcher with HTTPS (recommended):"
echo -e "  ${GREEN}cd $PROJECT_ROOT${NC}"
echo -e "  ${GREEN}HYTALE_AUTH_DOMAIN=localhost:3443 NODE_TLS_REJECT_UNAUTHORIZED=0 npm start${NC}"
echo ""
echo -e "${YELLOW}First time SSL setup (macOS):${NC}"
echo -e "  Add cert to keychain to avoid NODE_TLS_REJECT_UNAUTHORIZED:"
echo -e "  ${GREEN}sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain data/auth/ssl/server.crt${NC}"
echo ""
echo -e "${CYAN}========================================"
echo "Useful Commands"
echo -e "========================================${NC}"
echo ""
echo -e "View logs:          ${GREEN}docker compose logs -f auth-server${NC}"
echo -e "Stop services:      ${GREEN}docker compose down${NC}"
echo -e "Restart:            ${GREEN}docker compose restart auth-server${NC}"
echo -e "Check request log:  ${GREEN}cat data/auth/debug-requests.jsonl | jq${NC}"
echo ""
