#!/bin/bash
# =============================================================================
# Synor Testnet Deployment Script
# =============================================================================
# Usage:
#   ./scripts/testnet-deploy.sh [command]
#
# Commands:
#   start       - Start all testnet services
#   stop        - Stop all testnet services
#   restart     - Restart all testnet services
#   logs        - View logs from all services
#   status      - Check status of all services
#   clean       - Remove all data (WARNING: destructive)
#   build       - Build Docker images
#   explorer    - Start with block explorer
# =============================================================================

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
COMPOSE_FILE="$PROJECT_DIR/docker-compose.testnet.yml"

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

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_banner() {
    echo -e "${BLUE}"
    cat << 'EOF'
  ███████╗██╗   ██╗███╗   ██╗ ██████╗ ██████╗
  ██╔════╝╚██╗ ██╔╝████╗  ██║██╔═══██╗██╔══██╗
  ███████╗ ╚████╔╝ ██╔██╗ ██║██║   ██║██████╔╝
  ╚════██║  ╚██╔╝  ██║╚██╗██║██║   ██║██╔══██╗
  ███████║   ██║   ██║ ╚████║╚██████╔╝██║  ██║
  ╚══════╝   ╚═╝   ╚═╝  ╚═══╝ ╚═════╝ ╚═╝  ╚═╝
                     TESTNET DEPLOYMENT
EOF
    echo -e "${NC}"
}

check_docker() {
    if ! command -v docker &> /dev/null; then
        log_error "Docker is not installed. Please install Docker first."
        exit 1
    fi

    if ! docker info &> /dev/null; then
        log_error "Docker daemon is not running. Please start Docker."
        exit 1
    fi

    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        log_error "Docker Compose is not installed. Please install Docker Compose."
        exit 1
    fi
}

# Determine docker compose command
get_compose_cmd() {
    if docker compose version &> /dev/null 2>&1; then
        echo "docker compose"
    else
        echo "docker-compose"
    fi
}

cmd_build() {
    log_info "Building Docker images..."
    $(get_compose_cmd) -f "$COMPOSE_FILE" build
    log_success "Build complete!"
}

cmd_start() {
    log_info "Starting Synor testnet..."
    $(get_compose_cmd) -f "$COMPOSE_FILE" up -d seed1 seed2 seed3 faucet

    log_info "Waiting for services to start..."
    sleep 10

    log_success "Testnet started!"
    echo ""
    log_info "Services:"
    echo "  - Seed Node 1: http://localhost:17110 (RPC)"
    echo "  - Seed Node 2: http://localhost:17120 (RPC)"
    echo "  - Seed Node 3: http://localhost:17130 (RPC)"
    echo "  - Faucet:      http://localhost:8080"
    echo ""
    log_info "To view logs: $0 logs"
}

cmd_start_explorer() {
    log_info "Starting Synor testnet with block explorer..."
    $(get_compose_cmd) -f "$COMPOSE_FILE" --profile explorer up -d

    log_info "Waiting for services to start..."
    sleep 15

    log_success "Testnet with explorer started!"
    echo ""
    log_info "Services:"
    echo "  - Seed Node 1:   http://localhost:17110 (RPC)"
    echo "  - Seed Node 2:   http://localhost:17120 (RPC)"
    echo "  - Seed Node 3:   http://localhost:17130 (RPC)"
    echo "  - Faucet:        http://localhost:8080"
    echo "  - Explorer API:  http://localhost:3000"
    echo ""
}

cmd_stop() {
    log_info "Stopping Synor testnet..."
    $(get_compose_cmd) -f "$COMPOSE_FILE" --profile explorer down
    log_success "Testnet stopped!"
}

cmd_restart() {
    cmd_stop
    sleep 2
    cmd_start
}

cmd_logs() {
    $(get_compose_cmd) -f "$COMPOSE_FILE" logs -f "$@"
}

cmd_status() {
    log_info "Testnet Status:"
    echo ""
    $(get_compose_cmd) -f "$COMPOSE_FILE" ps
    echo ""

    # Check RPC endpoints
    log_info "Checking RPC endpoints..."
    for port in 17110 17120 17130; do
        if curl -s "http://localhost:$port/health" > /dev/null 2>&1; then
            echo -e "  Port $port: ${GREEN}HEALTHY${NC}"
        else
            echo -e "  Port $port: ${RED}UNAVAILABLE${NC}"
        fi
    done

    # Check faucet
    if curl -s "http://localhost:8080/health" > /dev/null 2>&1; then
        echo -e "  Faucet:   ${GREEN}HEALTHY${NC}"
    else
        echo -e "  Faucet:   ${RED}UNAVAILABLE${NC}"
    fi
}

cmd_clean() {
    log_warn "This will remove all testnet data!"
    read -p "Are you sure? (y/N) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "Stopping services..."
        $(get_compose_cmd) -f "$COMPOSE_FILE" --profile explorer down -v
        log_success "All data removed!"
    else
        log_info "Cancelled."
    fi
}

cmd_help() {
    echo "Synor Testnet Deployment Script"
    echo ""
    echo "Usage: $0 [command]"
    echo ""
    echo "Commands:"
    echo "  start       Start all testnet services"
    echo "  stop        Stop all testnet services"
    echo "  restart     Restart all testnet services"
    echo "  logs        View logs from all services"
    echo "  status      Check status of all services"
    echo "  clean       Remove all data (WARNING: destructive)"
    echo "  build       Build Docker images"
    echo "  explorer    Start with block explorer"
    echo "  help        Show this help message"
    echo ""
}

# Main
print_banner
check_docker

case "${1:-help}" in
    start)
        cmd_start
        ;;
    stop)
        cmd_stop
        ;;
    restart)
        cmd_restart
        ;;
    logs)
        shift
        cmd_logs "$@"
        ;;
    status)
        cmd_status
        ;;
    clean)
        cmd_clean
        ;;
    build)
        cmd_build
        ;;
    explorer)
        cmd_start_explorer
        ;;
    help|--help|-h)
        cmd_help
        ;;
    *)
        log_error "Unknown command: $1"
        cmd_help
        exit 1
        ;;
esac
