#!/bin/bash

# PHI|OS Complete Deployment Automation
# Automates the full deployment process including nginx, services, and runtime config

set -e

# Load environment variables
if [ -f ".env" ]; then
    source .env
fi

# Configuration variables with defaults
DOMAIN="${DOMAIN:-uniphil.ch}"
WEBAPP_PORT="${WEBAPP_PORT:-3300}"
API_PORT="${API_PORT:-3001}"

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

echo -e "${YELLOW}"
echo -e "╔════════════════════════════════════════════════════════════╗"
echo -e "║          PHI|OS Complete Deployment Automation            ║"
echo -e "║                                                           ║"
echo -e "║  Domain: ${DOMAIN}                                        ║"
echo -e "║  Webapp Port: ${WEBAPP_PORT}                               ║"
echo -e "║  API Port: ${API_PORT}                                     ║"
echo -e "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

# Check if running as root
if [ "$(id -u)" -ne 0 ]; then
    echo -e "${RED}[ERROR] This script must be run as root${NC}"
    exit 1
fi

# Step 1: Update services and runtime configuration
echo -e "${YELLOW}[STEP 1/3] Updating services and runtime configuration...${NC}"
bash "$(dirname "$0")/update-services.sh"
echo -e "${GREEN}[STEP 1/3] Services update completed${NC}"

# Step 2: Apply nginx configuration
echo -e "${YELLOW}[STEP 2/3] Applying nginx configuration...${NC}"
bash "$(dirname "$0")/apply-nginx-config.sh"
echo -e "${GREEN}[STEP 2/3] Nginx configuration applied${NC}"

# Step 3: Verify deployment
echo -e "${YELLOW}[STEP 3/3] Verifying deployment...${NC}"

# Test HTTPS connectivity
if command -v curl &> /dev/null; then
    echo -e "${YELLOW}[VERIFY] Testing HTTPS connectivity...${NC}"
    if curl -s -o /dev/null -w "%{http_code}" https://${DOMAIN}/ | grep -q "[23]"; then
        echo -e "${GREEN}[VERIFY] HTTPS endpoint is working (https://${DOMAIN}/)${NC}"
    else
        echo -e "${RED}[WARNING] HTTPS endpoint not responding properly${NC}"
    fi
    
    # Test API endpoint
    if curl -s -o /dev/null -w "%{http_code}" https://${DOMAIN}/api/ | grep -q "[234]"; then
        echo -e "${GREEN}[VERIFY] API endpoint is working (https://${DOMAIN}/api/)${NC}"
    else
        echo -e "${RED}[WARNING] API endpoint not responding properly${NC}"
    fi
else
    echo -e "${YELLOW}[VERIFY] curl not available, skipping HTTP tests${NC}"
fi

# Check nginx status
if systemctl is-active --quiet nginx; then
    echo -e "${GREEN}[VERIFY] Nginx is running${NC}"
else
    echo -e "${RED}[ERROR] Nginx is not running${NC}"
fi

# Check docker services
if command -v docker &> /dev/null; then
    if docker ps --format '{{.Names}}' | grep -q "phi-os-webapp-1"; then
        echo -e "${GREEN}[VERIFY] Webapp container is running${NC}"
    else
        echo -e "${RED}[WARNING] Webapp container is not running${NC}"
    fi
    
    if docker ps --format '{{.Names}}' | grep -q "hypergraph_api"; then
        echo -e "${GREEN}[VERIFY] API container is running${NC}"
    else
        echo -e "${RED}[WARNING] API container is not running${NC}"
    fi
else
    echo -e "${YELLOW}[VERIFY] Docker not available, skipping container checks${NC}"
fi

echo -e "${GREEN}[STEP 3/3] Verification completed${NC}"

echo -e "${GREEN}"
echo -e "╔════════════════════════════════════════════════════════════╗"
echo -e "║          PHI|OS Deployment Completed Successfully          ║"
echo -e "║                                                           ║"
echo -e "║  🌐 Web Interface: https://${DOMAIN}                      ║"
echo -e "║  🔗 API Endpoint:   https://${DOMAIN}/api/                 ║"
echo -e "║  🔄 WebSocket:      wss://${DOMAIN}/ws/                   ║"
echo -e "║                                                           ║"
echo -e "║  📁 Runtime Config: /rhiz/PHI|OS/runtime/config.json     ║"
echo -e "║  📄 Nginx Config:   /etc/nginx/sites-available/${DOMAIN}.conf ║"
echo -e "║                                                           ║"
echo -e "║  Container Services:                                      ║"
echo -e "║  - Webapp: phi-os-webapp-1 (port ${WEBAPP_PORT})           ║"
echo -e "║  - API:    hypergraph_api (port ${API_PORT})              ║"
echo -e "║                                                           ║"
echo -e "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

exit 0