#!/bin/bash
# Wakelai Production Deployment Script

set -e

echo "=========================================="
echo "Wakelai Production Deployment"
echo "=========================================="
echo ""

PROJECT_DIR="/home/ashraffarid2010/wakelai.com"
cd "$PROJECT_DIR"

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

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}Please run as root (sudo)${NC}"
    exit 1
fi

# Pre-flight checks
echo "Running pre-flight checks..."

if ! command -v docker &> /dev/null; then
    echo -e "${RED}Docker not found. Please install Docker first.${NC}"
    exit 1
fi

# Check for docker-compose or docker compose
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo -e "${RED}Docker Compose not found. Please install Docker Compose first.${NC}"
    exit 1
fi

# Set docker-compose command
if command -v docker-compose &> /dev/null; then
    DOCKER_COMPOSE="docker-compose"
else
    DOCKER_COMPOSE="docker compose"
fi

echo -e "${GREEN}✓ Pre-flight checks complete${NC}"
echo ""

# Check .env file
if [ ! -f .env ]; then
    echo -e "${YELLOW}Warning: .env file not found. Creating from template...${NC}"
    cp .env.example .env
    echo -e "${YELLOW}Please edit .env with your production values before proceeding!${NC}"
    exit 1
fi

# Source .env file
set -a
source .env
set +a

# Check required variables
required_vars=("SECRET_KEY" "DATABASE_URL" "GOOGLE_CLIENT_ID" "GOOGLE_CLIENT_SECRET")
missing_vars=()

for var in "${required_vars[@]}"; do
    if [ -z "${!var}" ] || [[ "${!var}" == *"change"* ]]; then
        missing_vars+=("$var")
    fi
done

if [ ${#missing_vars[@]} -gt 0 ]; then
    echo -e "${RED}Required environment variables not set: ${missing_vars[*]}${NC}"
    echo "Please edit .env with production values"
    exit 1
fi

echo -e "${GREEN}✓ Environment configuration validated${NC}"
echo ""

# Stop existing containers
echo "Stopping existing containers..."
$DOCKER_COMPOSE -f docker-compose.wakelai.yml down 2>/dev/null || true
echo -e "${GREEN}✓ Existing containers stopped${NC}"
echo ""

# Build images
echo "Building Docker images..."
$DOCKER_COMPOSE -f docker-compose.wakelai.yml build
echo -e "${GREEN}✓ Docker images built${NC}"
echo ""

# Start containers
echo "Starting containers..."
$DOCKER_COMPOSE -f docker-compose.wakelai.yml --profile production up -d
echo -e "${GREEN}✓ Containers started${NC}"
echo ""

# Wait for database
echo "Waiting for database to be ready..."
timeout=30
while [ $timeout -gt 0 ]; do
    if docker exec wakelai-postgres pg_isready -U postgres -d wakelai &> /dev/null; then
        echo -e "${GREEN}✓ Database is ready${NC}"
        break
    fi
    sleep 1
    ((timeout--))
done

if [ $timeout -eq 0 ]; then
    echo -e "${RED}Database failed to start${NC}"
    exit 1
fi
echo ""

# Run migrations
echo "Running database migrations..."
docker exec wakelai-postgres psql -U postgres -d wakelai -f /docker-entrypoint-initdb.d/001_init.sql 2>/dev/null || true
echo -e "${GREEN}✓ Migrations complete${NC}"
echo ""

# Check application health
echo "Checking application health..."
timeout=30
while [ $timeout -gt 0 ]; do
    if curl -f http://localhost:4000/health &> /dev/null; then
        echo -e "${GREEN}✓ Application is healthy${NC}"
        break
    fi
    sleep 1
    ((timeout--))
done

if [ $timeout -eq 0 ]; then
    echo -e "${YELLOW}Warning: Application health check timed out${NC}"
fi
echo ""

# Show status
echo "Container status:"
$DOCKER_COMPOSE -f docker-compose.wakelai.yml ps
echo ""

echo "=========================================="
echo -e "${GREEN}Deployment Complete!${NC}"
echo "=========================================="
echo ""
echo "Application URLs:"
echo "  - Main: http://localhost:4000"
echo "  - Health: http://localhost:4000/health"
echo "  - API Stats: http://localhost:4000/api/stats"
echo ""
echo "Logs:"
echo "  $DOCKER_COMPOSE -f docker-compose.wakelai.yml logs -f"
echo ""
echo "To create admin user:"
echo "  docker exec -it wakelai-main python run.py create-admin"
echo ""
