#!/bin/bash
# ==============================================================================
# RDM RSP API - Local Development Run Script
# ==============================================================================
# Runs the application locally for testing before deployment
#
# Usage:
#   ./run-local.sh           # Start the application
#   ./run-local.sh --build   # Rebuild and start
#   ./run-local.sh --logs    # Start and follow logs
#   ./run-local.sh --stop    # Stop the application
#   ./run-local.sh --clean   # Stop and remove all data
# ==============================================================================

set -e  # Exit on any error

# ==============================================================================
# Configuration
# ==============================================================================
COMPOSE_PROJECT_NAME="rsp-local"
export COMPOSE_PROJECT_NAME

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

# ==============================================================================
# Functions
# ==============================================================================

print_header() {
    echo -e "${BLUE}"
    echo "=============================================================================="
    echo " RDM RSP API - Local Development"
    echo "=============================================================================="
    echo -e "${NC}"
}

print_step() {
    echo -e "${GREEN}[STEP]${NC} $1"
}

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

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

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

check_prerequisites() {
    print_step "Checking prerequisites..."

    # Check Docker
    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed"
        exit 1
    fi

    # Check Docker Compose
    if ! docker compose version &> /dev/null; then
        print_error "Docker Compose is not available"
        exit 1
    fi

    # Check if Docker daemon is running
    if ! docker info &> /dev/null; then
        print_error "Docker daemon is not running"
        exit 1
    fi

    print_info "Prerequisites check passed"
}

setup_env() {
    print_step "Setting up environment..."

    # Create .env from example if not exists
    if [[ ! -f ".env" ]]; then
        if [[ -f ".env.example" ]]; then
            print_warning ".env file not found, copying from .env.example"
            cp .env.example .env
            print_warning "Please edit .env with your actual configuration values"
            print_warning "Press Enter to continue or Ctrl+C to abort..."
            read -r
        else
            print_error ".env.example not found. Cannot create .env file"
            exit 1
        fi
    fi

    # Create data directories
    print_step "Creating data directories..."
    mkdir -p data/logs

    print_info "Environment setup complete"
}

start_services() {
    local BUILD_FLAG=""

    if [[ "$1" == "--build" ]]; then
        BUILD_FLAG="--build"
        print_step "Building and starting services..."
    else
        print_step "Starting services..."
    fi

    docker compose up -d $BUILD_FLAG

    print_info "Services started"
}

stop_services() {
    print_step "Stopping services..."
    docker compose down
    print_info "Services stopped"
}

clean_all() {
    print_step "Stopping services and cleaning up..."
    docker compose down -v --remove-orphans

    print_warning "Do you want to remove data directories? (y/N)"
    read -r response
    if [[ "$response" =~ ^[Yy]$ ]]; then
        rm -rf data/
        print_info "Data directories removed"
    fi

    print_info "Cleanup complete"
}

show_logs() {
    print_step "Following logs (Ctrl+C to exit)..."
    docker compose logs -f api
}

wait_for_healthy() {
    print_step "Waiting for API to be healthy..."

    local max_attempts=30
    local attempt=1

    while [[ $attempt -le $max_attempts ]]; do
        if curl -sf http://localhost:${API_PORT:-80}/swagger/index.html > /dev/null 2>&1; then
            print_info "API is healthy!"
            return 0
        fi

        echo -n "."
        sleep 2
        ((attempt++))
    done

    echo ""
    print_error "API failed to become healthy after ${max_attempts} attempts"
    print_warning "Check logs with: docker compose logs api"
    return 1
}

test_endpoints() {
    print_step "Testing API endpoints..."

    local base_url="http://localhost:${API_PORT:-80}"

    echo ""
    echo "Swagger UI:"
    if curl -sf "${base_url}/swagger/index.html" > /dev/null 2>&1; then
        echo -e "  ${GREEN}Available${NC}"
    else
        echo -e "  ${RED}Not available${NC}"
    fi

    echo ""
    echo "Swagger UI available at: ${base_url}/swagger"
    echo ""
}

show_status() {
    print_step "Container Status:"
    docker compose ps
    echo ""

    print_step "Container Logs (last 20 lines):"
    docker compose logs --tail=20 api
}

show_usage() {
    echo "Usage: $0 [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  (none)      Start the application"
    echo "  --build     Rebuild and start the application"
    echo "  --logs      Start and follow logs"
    echo "  --stop      Stop the application"
    echo "  --clean     Stop and remove all data"
    echo "  --status    Show current status"
    echo "  --test      Test API endpoints"
    echo "  --help      Show this help message"
}

# ==============================================================================
# Main
# ==============================================================================

print_header

# Parse arguments
case "${1:-}" in
    --stop)
        check_prerequisites
        stop_services
        ;;
    --clean)
        check_prerequisites
        clean_all
        ;;
    --logs)
        check_prerequisites
        setup_env
        start_services
        show_logs
        ;;
    --build)
        check_prerequisites
        setup_env
        start_services --build
        wait_for_healthy
        test_endpoints
        ;;
    --status)
        check_prerequisites
        show_status
        ;;
    --test)
        check_prerequisites
        test_endpoints
        ;;
    --help)
        show_usage
        ;;
    "")
        check_prerequisites
        setup_env
        start_services
        wait_for_healthy
        test_endpoints
        ;;
    *)
        print_error "Unknown option: $1"
        show_usage
        exit 1
        ;;
esac

# ==============================================================================
# Summary
# ==============================================================================

if [[ "${1:-}" != "--stop" && "${1:-}" != "--clean" && "${1:-}" != "--help" && "${1:-}" != "--status" ]]; then
    echo ""
    echo -e "${GREEN}=============================================================================="
    echo " LOCAL ENVIRONMENT READY"
    echo "==============================================================================${NC}"
    echo ""
    echo "API URL:      http://localhost:${API_PORT:-80}"
    echo "Swagger UI:   http://localhost:${API_PORT:-80}/swagger"
    echo ""
    echo "Commands:"
    echo "  View logs:      docker compose logs -f api"
    echo "  Stop:           ./run-local.sh --stop"
    echo "  Restart:        docker compose restart api"
    echo "  Shell access:   docker compose exec api bash"
    echo ""
fi
