#!/bin/bash
# =============================================================================
# MOMO Pro System - 服務健康檢查腳本
# 用途：變更前/後快速驗證所有服務狀態
# 使用：./scripts/health-check.sh [pre|post]
# =============================================================================

set -e

MODE=${1:-check}
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
LOG_FILE="/tmp/health_check_$(date '+%Y%m%d_%H%M%S').log"

# 顏色定義
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo -e "${BLUE}╔════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║        MOMO Pro System 服務健康檢查 - $TIMESTAMP       ║${NC}"
echo -e "${BLUE}╠════════════════════════════════════════════════════════════════╣${NC}"

check_service() {
    local name=$1
    local url=$2
    local expected_code=${3:-200}

    response=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "$url" 2>/dev/null || echo "000")

    if [ "$response" = "$expected_code" ] || [ "$response" = "302" ]; then
        echo -e "  ${GREEN}✅${NC} $name: $response"
        return 0
    else
        echo -e "  ${RED}❌${NC} $name: $response (expected $expected_code)"
        return 1
    fi
}

check_docker() {
    echo -e "\n${YELLOW}📦 Docker 容器狀態:${NC}"
    ssh wooo@192.168.0.110 "docker ps --format 'table {{.Names}}\t{{.Status}}' | grep -E '(superset|gitlab|n8n|registry)' | head -10" 2>/dev/null || echo "  無法連接"
}

check_k8s() {
    echo -e "\n${YELLOW}🌐 K8s Pods:${NC}"
    ssh wooo@192.168.0.110 "kubectl get pods -n momo --no-headers 2>/dev/null" || echo "  無法取得 K8s 狀態"
}

# 主要健康檢查
echo -e "\n${YELLOW}🔍 服務健康檢查:${NC}"
FAILED=0

check_service "mo.wooo.work" "https://mo.wooo.work/health" || ((FAILED++))
check_service "Superset 登入" "https://monitor.wooo.work/superset/login/" || ((FAILED++))
check_service "GitLab" "http://192.168.0.110:8929/" "302" || ((FAILED++))
check_service "n8n" "http://192.168.0.110:5678/" || ((FAILED++))
check_service "Registry" "https://registry.wooo.work/v2/" "401" || ((FAILED++))
check_service "CI/CD Dashboard" "https://mo.wooo.work/cicd" || ((FAILED++))
check_service "Monitor 首頁" "https://monitor.wooo.work/" || ((FAILED++))

# Docker 容器
check_docker

# K8s Pods
check_k8s

# 結果摘要
echo -e "\n${BLUE}╠════════════════════════════════════════════════════════════════╣${NC}"
if [ $FAILED -eq 0 ]; then
    echo -e "${BLUE}║${NC}  ${GREEN}✅ 所有服務正常${NC}"
else
    echo -e "${BLUE}║${NC}  ${RED}⚠️ $FAILED 個服務異常${NC}"
fi
echo -e "${BLUE}╚════════════════════════════════════════════════════════════════╝${NC}"

# 保存結果
if [ "$MODE" = "pre" ]; then
    echo "$TIMESTAMP - PRE-CHANGE" > /tmp/last_health_check.txt
    echo "Failed: $FAILED" >> /tmp/last_health_check.txt
    echo -e "\n${YELLOW}📝 變更前快照已保存${NC}"
elif [ "$MODE" = "post" ]; then
    echo "$TIMESTAMP - POST-CHANGE" >> /tmp/last_health_check.txt
    echo "Failed: $FAILED" >> /tmp/last_health_check.txt
    echo -e "\n${YELLOW}📝 變更後檢查完成${NC}"
fi

exit $FAILED
