#!/bin/bash
# ============================================
# Document Translation API - Health Check Script
# ============================================
# Usage: ./scripts/health-check.sh [--verbose]

set -e

VERBOSE=false
if [ "$1" == "--verbose" ]; then
    VERBOSE=true
fi

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

# Configuration
BACKEND_URL="${BACKEND_URL:-http://localhost:8000}"
FRONTEND_URL="${FRONTEND_URL:-http://localhost:3000}"
NGINX_URL="${NGINX_URL:-http://localhost}"

EXIT_CODE=0

check_service() {
    local name=$1
    local url=$2
    local expected=${3:-200}
    
    response=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>/dev/null || echo "000")
    
    if [ "$response" == "$expected" ]; then
        echo -e "${GREEN}✓ $name: OK (HTTP $response)${NC}"
    else
        echo -e "${RED}✗ $name: FAILED (HTTP $response, expected $expected)${NC}"
        EXIT_CODE=1
    fi
    
    if [ "$VERBOSE" == "true" ] && [ "$response" == "200" ]; then
        echo "  Response:"
        curl -s "$url" 2>/dev/null | head -c 500
        echo ""
    fi
}

echo "========================================="
echo "  Health Check - Document Translation API"
echo "========================================="
echo ""

# Check backend
echo "Backend Services:"
check_service "API Health" "$BACKEND_URL/health"
check_service "API Root" "$BACKEND_URL/"

echo ""

# Check frontend
echo "Frontend Services:"
check_service "Frontend" "$FRONTEND_URL"

echo ""

# Check nginx (if running)
echo "Proxy Services:"
check_service "Nginx" "$NGINX_URL/health"

echo ""

# Docker health
if command -v docker &> /dev/null; then
    echo "Docker Container Status:"
    docker compose ps --format "table {{.Name}}\t{{.Status}}" 2>/dev/null || echo "  Docker Compose not running"
fi

echo ""
echo "========================================="

if [ $EXIT_CODE -eq 0 ]; then
    echo -e "${GREEN}All health checks passed!${NC}"
else
    echo -e "${RED}Some health checks failed!${NC}"
fi

exit $EXIT_CODE
