#!/bin/bash
set -e

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

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEPLOYMENT_DIR="$(dirname "$SCRIPT_DIR")"
PROJECT_DIR="$(dirname "$DEPLOYMENT_DIR")"

echo -e "${GREEN}=== Agenda Tasks Deployment ===${NC}"

# Check if .env file exists
if [ ! -f "$DEPLOYMENT_DIR/.env" ]; then
    echo -e "${RED}Error: .env file not found!${NC}"
    echo "Please copy .env.example to .env and configure it:"
    echo "  cp $DEPLOYMENT_DIR/.env.example $DEPLOYMENT_DIR/.env"
    exit 1
fi

# Load environment variables
source "$DEPLOYMENT_DIR/.env"

# Validate required variables
required_vars=("DB_PASSWORD" "SECRET_KEY" "DOMAIN" "EMAIL")
for var in "${required_vars[@]}"; do
    if [ -z "${!var}" ]; then
        echo -e "${RED}Error: $var is not set in .env${NC}"
        exit 1
    fi
done

echo -e "${YELLOW}Domain: $DOMAIN${NC}"
echo -e "${YELLOW}Email: $EMAIL${NC}"

# Navigate to docker directory
cd "$DEPLOYMENT_DIR/docker"

# Pull latest images
echo -e "${GREEN}Pulling latest images...${NC}"
docker compose pull

# Build backend
echo -e "${GREEN}Building backend...${NC}"
docker compose build backend

# Stop existing containers
echo -e "${GREEN}Stopping existing containers...${NC}"
docker compose down

# Start services
echo -e "${GREEN}Starting services...${NC}"
docker compose up -d

# Wait for services to be healthy
echo -e "${GREEN}Waiting for services to be healthy...${NC}"
sleep 10

# Check service status
echo -e "${GREEN}Checking service status...${NC}"
docker compose ps

# Check backend health
if docker compose exec -T backend python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/docs')"; then
    echo -e "${GREEN}Backend is healthy!${NC}"
else
    echo -e "${RED}Backend health check failed!${NC}"
    docker compose logs backend
    exit 1
fi

echo -e "${GREEN}=== Deployment complete! ===${NC}"
echo ""
echo "Next steps:"
echo "1. Set up SSL with: ./setup-ssl.sh"
echo "2. Configure your DNS to point to this server"
echo "3. Access the API at: https://$DOMAIN"
