#!/bin/bash

# PHI|OS Services Update and Runtime Configuration
# Updates docker services and runtime configuration

set -e

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

# Configuration variables with defaults
DOCKER_COMPOSE_FILE="${DOCKER_COMPOSE_FILE:-docker-compose.yml}"
WEBAPP_SERVICE="${WEBAPP_SERVICE:-phi-os-webapp-1}"
API_SERVICE="${API_SERVICE:-hypergraph_api}"
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}[PHI|OS] Updating services and runtime configuration...${NC}"

# Check if docker is available
if ! command -v docker &> /dev/null; then
    echo -e "${RED}[ERROR] Docker is not installed or not available${NC}"
    exit 1
fi

# Check service status
echo -e "${YELLOW}[DOCKER] Checking service status...${NC}"

# Check webapp service
if docker ps --format '{{.Names}}' | grep -q "${WEBAPP_SERVICE}"; then
    echo -e "${GREEN}[DOCKER] Webapp service ${WEBAPP_SERVICE} is running${NC}"
else
    echo -e "${RED}[WARNING] Webapp service ${WEBAPP_SERVICE} is not running${NC}"
fi

# Check API service
if docker ps --format '{{.Names}}' | grep -q "${API_SERVICE}"; then
    echo -e "${GREEN}[DOCKER] API service ${API_SERVICE} is running${NC}"
else
    echo -e "${RED}[WARNING] API service ${API_SERVICE} is not running${NC}"
fi

# Test service connectivity
echo -e "${YELLOW}[SERVICES] Testing service connectivity...${NC}"

# Test webapp
if curl -s -o /dev/null -w "%{http_code}" http://localhost:${WEBAPP_PORT}/ | grep -q "[23]"; then
    echo -e "${GREEN}[SERVICES] Webapp on port ${WEBAPP_PORT} is reachable${NC}"
else
    echo -e "${RED}[WARNING] Webapp on port ${WEBAPP_PORT} is not responding properly${NC}"
fi

# Test API
if curl -s -o /dev/null -w "%{http_code}" http://localhost:${API_PORT}/ | grep -q "[234]"; then
    echo -e "${GREEN}[SERVICES] API on port ${API_PORT} is reachable${NC}"
else
    echo -e "${RED}[WARNING] API on port ${API_PORT} is not responding properly${NC}"
fi

# Update runtime configuration
echo -e "${YELLOW}[CONFIG] Updating runtime configuration...${NC}"

# Create runtime config directory if it doesn't exist
RUNTIME_DIR="/rhiz/PHI|OS/runtime"
mkdir -p "${RUNTIME_DIR}"

# Generate runtime configuration
cat > "${RUNTIME_DIR}/config.json" << EOF
{
  "environment": "${ENVIRONMENT:-production}",
  "services": {
    "webapp": {
      "name": "${WEBAPP_SERVICE}",
      "port": ${WEBAPP_PORT},
      "status": "$(docker ps --format '{{.Names}}' | grep -q "${WEBAPP_SERVICE}" && echo 'running' || echo 'stopped')"
    },
    "api": {
      "name": "${API_SERVICE}",
      "port": ${API_PORT},
      "status": "$(docker ps --format '{{.Names}}' | grep -q "${API_SERVICE}" && echo 'running' || echo 'stopped')"
    }
  },
  "nginx": {
    "domain": "${DOMAIN:-uniphil.ch}",
    "ssl": {
      "enabled": true,
      "cert_path": "${SSL_CERT_PATH:-/etc/letsencrypt/live/${DOMAIN:-uniphil.ch}}"
    }
  },
  "timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
}
EOF

echo -e "${GREEN}[CONFIG] Runtime configuration updated${NC}"

# Check for docker-compose file and restart services if needed
if [ -f "${DOCKER_COMPOSE_FILE}" ]; then
    echo -e "${YELLOW}[DOCKER] Docker compose file found, checking for updates...${NC}"
    
    # Check if services need to be updated
    if [ "${AUTO_UPDATE:-false}" = "true" ]; then
        echo -e "${YELLOW}[DOCKER] Pulling latest images...${NC}"
        docker-compose -f "${DOCKER_COMPOSE_FILE}" pull
        
        echo -e "${YELLOW}[DOCKER] Restarting services...${NC}"
        docker-compose -f "${DOCKER_COMPOSE_FILE}" down
        docker-compose -f "${DOCKER_COMPOSE_FILE}" up -d
        
        echo -e "${GREEN}[DOCKER] Services updated and restarted${NC}"
    else
        echo -e "${YELLOW}[DOCKER] Auto-update disabled, services not restarted${NC}"
    fi
else
    echo -e "${YELLOW}[DOCKER] No docker-compose file found at ${DOCKER_COMPOSE_FILE}${NC}"
fi

echo -e "${GREEN}"
echo -e "╔════════════════════════════════════════════════════════════╗"
echo -e "║        PHI|OS Services Update Complete                   ║"
echo -e "║                                                           ║"
echo -e "║  Webapp Service: ${WEBAPP_SERVICE} (port ${WEBAPP_PORT})        ║"
echo -e "║  API Service: ${API_SERVICE} (port ${API_PORT})              ║"
echo -e "║  Runtime Config: ${RUNTIME_DIR}/config.json              ║"
echo -e "║                                                           ║"
echo -e "║  To apply nginx configuration, run:                      ║"
echo -e "║  sudo /rhiz/PHI|OS/deploy/apply-nginx-config.sh           ║"
echo -e "║                                                           ║"
echo -e "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"

exit 0