#!/bin/bash

# Health Check Script
# Quick health check for all services

set -e

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

DOMAIN="${DOMAIN:-harkon.co.uk}"

echo -e "${BLUE}AI Tax Agent - Health Check${NC}"
echo -e "${BLUE}============================${NC}"
echo ""

# Function to check endpoint
check_endpoint() {
    local name=$1
    local url=$2
    local expected_code=${3:-200}
    
    echo -n "Checking $name... "
    
    response=$(curl -s -o /dev/null -w "%{http_code}" "$url" 2>/dev/null || echo "000")
    
    if [ "$response" = "$expected_code" ] || [ "$response" = "200" ] || [ "$response" = "302" ]; then
        echo -e "${GREEN}✓ OK ($response)${NC}"
        return 0
    else
        echo -e "${RED}✗ FAILED ($response)${NC}"
        return 1
    fi
}

echo -e "${YELLOW}Infrastructure Services:${NC}"
check_endpoint "Vault" "https://vault.${DOMAIN}/v1/sys/health" "200"
check_endpoint "MinIO Console" "https://minio-console.${DOMAIN}" "200"
check_endpoint "Neo4j" "https://neo4j.${DOMAIN}" "200"
check_endpoint "Qdrant" "https://qdrant.${DOMAIN}" "200"

echo ""
echo -e "${YELLOW}Application Services:${NC}"
check_endpoint "API Health" "https://api.${DOMAIN}/health" "200"
check_endpoint "Ingestion" "https://api.${DOMAIN}/ingestion/health" "200"
check_endpoint "Extract" "https://api.${DOMAIN}/extract/health" "200"
check_endpoint "Knowledge Graph" "https://api.${DOMAIN}/kg/health" "200"
check_endpoint "RAG Retriever" "https://api.${DOMAIN}/rag-retriever/health" "200"
check_endpoint "RAG Indexer" "https://api.${DOMAIN}/rag-indexer/health" "200"
check_endpoint "Forms" "https://api.${DOMAIN}/forms/health" "200"
check_endpoint "HMRC" "https://api.${DOMAIN}/hmrc/health" "200"
check_endpoint "OCR" "https://api.${DOMAIN}/ocr/health" "200"
check_endpoint "RPA" "https://api.${DOMAIN}/rpa/health" "200"
check_endpoint "Normalize Map" "https://api.${DOMAIN}/normalize-map/health" "200"
check_endpoint "Reason" "https://api.${DOMAIN}/reason/health" "200"
check_endpoint "Firm Connectors" "https://api.${DOMAIN}/firm-connectors/health" "200"
check_endpoint "Coverage" "https://api.${DOMAIN}/coverage/health" "200"

echo ""
echo -e "${YELLOW}UI:${NC}"
check_endpoint "Review UI" "https://app.${DOMAIN}" "200"

echo ""
echo -e "${YELLOW}Monitoring:${NC}"
check_endpoint "Prometheus" "https://prometheus.${DOMAIN}/-/healthy" "200"
check_endpoint "Grafana" "https://grafana.${DOMAIN}/api/health" "200"
check_endpoint "Loki" "https://loki.${DOMAIN}/ready" "200"

echo ""
echo -e "${BLUE}Health check complete!${NC}"

