#!/bin/bash
set -e

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

echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║         Dyolink - Deploy Tool         ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"

# Load environment
if [ -f .env ]; then
    source .env
    echo -e "${GREEN}✓ Loaded .env${NC}"
fi

# Check for env files
ENV_FILES=("database.env" "backend.env" "frontend.env")
for env_file in "${ENV_FILES[@]}"; do
    if [ ! -f "$env_file" ]; then
        echo -e "${YELLOW}⚠ $env_file not found, creating from example${NC}"
        if [ -f "${env_file}.example" ]; then
            cp "${env_file}.example" "$env_file"
            echo -e "${RED}❕ Edit $env_file with production values!${NC}"
            read -p "Continue? (y/n): " -n 1 -r
            echo
            if [[ ! $REPLY =~ ^[Yy]$ ]]; then
                exit 1
            fi
        fi
    fi
done

# Create directories
mkdir -p logs/nginx database/backups ssl

# Get version
read -p "Enter version to deploy (default: ${TAG:-latest}): " DEPLOY_TAG
DEPLOY_TAG=${DEPLOY_TAG:-${TAG:-latest}}
export TAG=$DEPLOY_TAG
export DOCKER_USERNAME=${DOCKER_USERNAME:-yourdockerhub}

# Pull images
echo -e "${YELLOW}Pulling images from Docker Hub...${NC}"
docker-compose -f docker-compose.prod.yml pull

# Stop old
echo -e "${YELLOW}Stopping old containers...${NC}"
docker-compose -f docker-compose.prod.yml down

# Start new
echo -e "${YELLOW}Starting containers...${NC}"
docker-compose -f docker-compose.prod.yml up -d

# Wait for health
echo -e "${YELLOW}Waiting for services...${NC}"
sleep 10

# Show status
echo -e "\n${GREEN}=== Status ===${NC}"
docker-compose -f docker-compose.prod.yml ps

echo -e "\n${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║          Deployment Complete!          ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"