#!/bin/bash

# ASF TestArena Deployment Script
# This script deploys the TestArena application using Docker Compose

set -e  # Exit on error

echo "=========================================="
echo "  ASF TestArena Deployment Script"
echo "=========================================="
echo ""

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

# Function to print colored output
print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

print_info() {
    echo -e "${YELLOW}ℹ $1${NC}"
}

# Check if Docker is installed
echo "Checking prerequisites..."
if ! command -v docker &> /dev/null; then
    print_error "Docker is not installed. Please install Docker first."
    exit 1
fi
print_success "Docker is installed"

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    print_error "Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi
print_success "Docker Compose is installed"

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

echo ""

# Check if .env file exists
if [ ! -f .env ]; then
    print_warning ".env file not found. Creating from .env.example..."
    if [ -f .env.example ]; then
        cp .env.example .env
        print_info "Please edit .env file and update SECRET_KEY and passwords before continuing."
        read -p "Press Enter to continue after editing .env, or Ctrl+C to exit..."
    else
        print_error ".env.example not found. Cannot create .env file."
        exit 1
    fi
fi

echo ""
echo "=========================================="
echo "  Starting Deployment"
echo "=========================================="
echo ""

# Check if caddy_network exists
echo "Checking for Caddy network..."
if docker network inspect caddy_network &> /dev/null; then
    print_success "Caddy network (caddy_network) exists"
else
    print_warning "Caddy network (caddy_network) not found"
    read -p "Do you want to create it? (y/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker network create caddy_network
        print_success "Created caddy_network"
    else
        print_error "Caddy network is required. Exiting."
        exit 1
    fi
fi

echo ""

# Stop existing containers if running
echo "Stopping existing containers (if any)..."
docker-compose down 2>/dev/null || true
print_success "Stopped existing containers"

echo ""

# Build and start containers
echo "Building and starting containers..."
echo "This may take a few minutes on first run..."
echo ""

if docker-compose up -d --build; then
    print_success "Containers built and started successfully"
else
    print_error "Failed to start containers"
    echo ""
    echo "Check logs with: docker-compose logs"
    exit 1
fi

echo ""
echo "Waiting for services to initialize..."
sleep 5

# Check if containers are running
echo ""
echo "Checking container status..."
if docker ps | grep -q testarena_web && docker ps | grep -q testarena_db; then
    print_success "All containers are running"
else
    print_error "Some containers failed to start"
    echo ""
    echo "Container status:"
    docker-compose ps
    echo ""
    echo "Check logs with: docker-compose logs"
    exit 1
fi

echo ""
echo "=========================================="
echo "  Deployment Complete!"
echo "=========================================="
echo ""
print_success "ASF TestArena is now running"
echo ""
echo "Access the application at:"
echo "  • Local: http://localhost:5000"
echo "  • Domain: https://testarena.nabd-co.com"
echo ""
echo "Default credentials:"
echo "  • Username: admin"
echo "  • Password: admin123"
echo ""
print_warning "IMPORTANT: Change the default admin password immediately!"
echo ""
echo "Useful commands:"
echo "  • View logs:    docker-compose logs -f"
echo "  • Stop:         docker-compose down"
echo "  • Restart:      docker-compose restart"
echo "  • Status:       docker-compose ps"
echo ""
echo "For help, see START_HERE.md or INDEX.md"
echo ""
