#!/bin/bash
# ============================================
# Document Translation API - Deployment Script
# ============================================
# Usage: ./scripts/deploy.sh [environment] [options]
# Example: ./scripts/deploy.sh production --with-ollama

set -e

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

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
ENVIRONMENT="${1:-production}"
COMPOSE_FILE="docker-compose.yml"

# Parse options
PROFILES=""
while [[ $# -gt 1 ]]; do
    case $2 in
        --with-ollama)
            PROFILES="$PROFILES --profile with-ollama"
            shift
            ;;
        --with-cache)
            PROFILES="$PROFILES --profile with-cache"
            shift
            ;;
        --with-monitoring)
            PROFILES="$PROFILES --profile with-monitoring"
            shift
            ;;
        --full)
            PROFILES="--profile with-ollama --profile with-cache --profile with-monitoring"
            shift
            ;;
        *)
            shift
            ;;
    esac
done

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Document Translation API Deployment${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Check prerequisites
echo -e "${YELLOW}Checking prerequisites...${NC}"

if ! command -v docker &> /dev/null; then
    echo -e "${RED}Error: Docker is not installed${NC}"
    exit 1
fi

if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo -e "${RED}Error: Docker Compose is not installed${NC}"
    exit 1
fi

echo -e "${GREEN}✓ Docker and Docker Compose are installed${NC}"

# Check environment file
cd "$PROJECT_ROOT"

if [ "$ENVIRONMENT" == "production" ]; then
    ENV_FILE=".env.production"
else
    ENV_FILE=".env"
fi

if [ ! -f "$ENV_FILE" ]; then
    echo -e "${YELLOW}Creating $ENV_FILE from template...${NC}"
    if [ -f ".env.example" ]; then
        cp .env.example "$ENV_FILE"
        echo -e "${YELLOW}Please edit $ENV_FILE with your configuration${NC}"
    else
        echo -e "${RED}Error: No environment file found${NC}"
        exit 1
    fi
fi

echo -e "${GREEN}✓ Environment file: $ENV_FILE${NC}"

# Load environment
set -a
source "$ENV_FILE"
set +a

# Create SSL directory if needed
if [ ! -d "docker/nginx/ssl" ]; then
    mkdir -p docker/nginx/ssl
    echo -e "${YELLOW}Created SSL directory. Add your certificates:${NC}"
    echo "  - docker/nginx/ssl/fullchain.pem"
    echo "  - docker/nginx/ssl/privkey.pem"
    echo "  - docker/nginx/ssl/chain.pem"
    
    # Generate self-signed cert for testing
    if [ "$ENVIRONMENT" != "production" ]; then
        echo -e "${YELLOW}Generating self-signed certificate for development...${NC}"
        openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
            -keyout docker/nginx/ssl/privkey.pem \
            -out docker/nginx/ssl/fullchain.pem \
            -subj "/C=US/ST=State/L=City/O=Organization/CN=localhost" 2>/dev/null
        cp docker/nginx/ssl/fullchain.pem docker/nginx/ssl/chain.pem
    fi
fi

# Build and deploy
echo ""
echo -e "${YELLOW}Building containers...${NC}"
docker compose --env-file "$ENV_FILE" build

echo ""
echo -e "${YELLOW}Starting services...${NC}"
docker compose --env-file "$ENV_FILE" $PROFILES up -d

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

# Health check
echo ""
echo -e "${YELLOW}Running health checks...${NC}"

BACKEND_HEALTH=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/health 2>/dev/null || echo "000")
if [ "$BACKEND_HEALTH" == "200" ]; then
    echo -e "${GREEN}✓ Backend is healthy${NC}"
else
    echo -e "${RED}✗ Backend health check failed (HTTP $BACKEND_HEALTH)${NC}"
fi

FRONTEND_HEALTH=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000 2>/dev/null || echo "000")
if [ "$FRONTEND_HEALTH" == "200" ]; then
    echo -e "${GREEN}✓ Frontend is healthy${NC}"
else
    echo -e "${RED}✗ Frontend health check failed (HTTP $FRONTEND_HEALTH)${NC}"
fi

# Show status
echo ""
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Deployment Complete!${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""
echo -e "Services running:"
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"

echo ""
echo -e "${GREEN}Access your application:${NC}"
echo -e "  Frontend: http://localhost (or https://localhost)"
echo -e "  API: http://localhost/api"
echo -e "  Admin: http://localhost/admin"
echo -e "  Health: http://localhost/health"

echo ""
echo -e "${YELLOW}Useful commands:${NC}"
echo "  View logs:     docker compose logs -f"
echo "  Stop:          docker compose down"
echo "  Restart:       docker compose restart"
echo "  Update:        ./scripts/deploy.sh $ENVIRONMENT"
