#!/bin/bash

# Docker网络连接测试脚本
# 用于测试容器间的网络连接和服务可用性

set -e

echo "==================================="
echo "Docker网络连接测试"
echo "==================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 测试计数
TEST_COUNT=0
PASS_COUNT=0
FAIL_COUNT=0

# 测试函数
test_connection() {
    local test_name=$1
    local container=$2
    local target=$3
    local port=$4
    local timeout=${5:-5}
    
    ((TEST_COUNT++))
    echo -n "测试 $test_name: "
    
    if docker exec "$container" timeout "$timeout" bash -c "echo > /dev/tcp/$target/$port" 2>/dev/null; then
        echo -e "${GREEN}✓ 通过${NC}"
        ((PASS_COUNT++))
    else
        echo -e "${RED}✗ 失败${NC}"
        ((FAIL_COUNT++))
    fi
}

# 测试HTTP连接
test_http() {
    local test_name=$1
    local container=$2
    local url=$3
    local expected_code=${4:-200}
    
    ((TEST_COUNT++))
    echo -n "测试 $test_name: "
    
    if docker exec "$container" curl -s -o /dev/null -w "%{http_code}" "$url" | grep -q "$expected_code"; then
        echo -e "${GREEN}✓ 通过${NC}"
        ((PASS_COUNT++))
    else
        echo -e "${RED}✗ 失败${NC}"
        ((FAIL_COUNT++))
    fi
}

# 检查容器是否运行
check_container() {
    local container=$1
    if ! docker ps --format "table {{.Names}}" | grep -q "^$container$"; then
        echo -e "${RED}错误: 容器 $container 未运行${NC}"
        return 1
    fi
    return 0
}

echo "检查容器状态..."
echo "-----------------------------------"

# 定义容器名称
APP_CONTAINER="knowledge_base_app"
MYSQL_CONTAINER="knowledge_base_mysql"
REDIS_CONTAINER="knowledge_base_redis"
MEILISEARCH_CONTAINER="knowledge_base_meilisearch"
QUEUE_CONTAINER="knowledge_base_queue"

# 检查所有容器是否运行
containers=("$APP_CONTAINER" "$MYSQL_CONTAINER" "$REDIS_CONTAINER" "$MEILISEARCH_CONTAINER" "$QUEUE_CONTAINER")
all_running=true

for container in "${containers[@]}"; do
    if check_container "$container"; then
        echo -e "${GREEN}✓ $container 正在运行${NC}"
    else
        echo -e "${RED}✗ $container 未运行${NC}"
        all_running=false
    fi
done

if [ "$all_running" = false ]; then
    echo -e "${RED}部分容器未运行，请先启动所有服务${NC}"
    exit 1
fi

echo ""
echo "测试网络连接..."
echo "-----------------------------------"

# 测试应用容器到数据库的连接
test_connection "应用->MySQL" "$APP_CONTAINER" "mysql" "3306"

# 测试应用容器到Redis的连接
test_connection "应用->Redis" "$APP_CONTAINER" "redis" "6379"

# 测试应用容器到Meilisearch的连接
test_connection "应用->Meilisearch" "$APP_CONTAINER" "meilisearch" "7700"

# 测试队列容器到数据库的连接
test_connection "队列->MySQL" "$QUEUE_CONTAINER" "mysql" "3306"

# 测试队列容器到Redis的连接
test_connection "队列->Redis" "$QUEUE_CONTAINER" "redis" "6379"

echo ""
echo "测试HTTP服务..."
echo "-----------------------------------"

# 测试Meilisearch HTTP API
test_http "Meilisearch健康检查" "$APP_CONTAINER" "http://meilisearch:7700/health"

# 测试应用HTTP服务（如果有健康检查端点）
if docker exec "$APP_CONTAINER" curl -s -f "http://localhost/health" >/dev/null 2>&1; then
    test_http "应用健康检查" "$APP_CONTAINER" "http://localhost/health"
else
    echo "应用健康检查端点不可用，跳过测试"
fi

echo ""
echo "测试服务功能..."
echo "-----------------------------------"

# 测试MySQL连接
((TEST_COUNT++))
echo -n "测试MySQL数据库连接: "
if docker exec "$MYSQL_CONTAINER" mysql -u root -p"${DB_PASSWORD:-secure_root_password}" -e "SELECT 1;" >/dev/null 2>&1; then
    echo -e "${GREEN}✓ 通过${NC}"
    ((PASS_COUNT++))
else
    echo -e "${RED}✗ 失败${NC}"
    ((FAIL_COUNT++))
fi

# 测试Redis连接
((TEST_COUNT++))
echo -n "测试Redis连接: "
if docker exec "$REDIS_CONTAINER" redis-cli ping | grep -q "PONG"; then
    echo -e "${GREEN}✓ 通过${NC}"
    ((PASS_COUNT++))
else
    echo -e "${RED}✗ 失败${NC}"
    ((FAIL_COUNT++))
fi

# 测试Laravel数据库连接
((TEST_COUNT++))
echo -n "测试Laravel数据库连接: "
if docker exec "$APP_CONTAINER" php artisan tinker --execute="echo DB::connection()->getPdo() ? 'OK' : 'FAIL';" 2>/dev/null | grep -q "OK"; then
    echo -e "${GREEN}✓ 通过${NC}"
    ((PASS_COUNT++))
else
    echo -e "${RED}✗ 失败${NC}"
    ((FAIL_COUNT++))
fi

# 测试Laravel Redis连接
((TEST_COUNT++))
echo -n "测试Laravel Redis连接: "
if docker exec "$APP_CONTAINER" php artisan tinker --execute="echo Redis::ping() ? 'OK' : 'FAIL';" 2>/dev/null | grep -q "OK"; then
    echo -e "${GREEN}✓ 通过${NC}"
    ((PASS_COUNT++))
else
    echo -e "${RED}✗ 失败${NC}"
    ((FAIL_COUNT++))
fi

echo ""
echo "测试网络信息..."
echo "-----------------------------------"

# 显示网络信息
echo "Docker网络信息:"
docker network ls | grep knowledge_base

echo ""
echo "容器IP地址:"
for container in "${containers[@]}"; do
    if check_container "$container" >/dev/null 2>&1; then
        ip=$(docker inspect "$container" --format='{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}')
        echo "$container: $ip"
    fi
done

echo ""
echo "==================================="
echo "测试结果汇总"
echo "==================================="

echo "总测试数: $TEST_COUNT"
echo -e "通过: ${GREEN}$PASS_COUNT${NC}"
echo -e "失败: ${RED}$FAIL_COUNT${NC}"

if [ $FAIL_COUNT -eq 0 ]; then
    echo -e "${GREEN}✓ 所有网络测试通过！${NC}"
    echo "Docker网络配置正常，服务间通信正常。"
    exit 0
else
    echo -e "${RED}✗ 有 $FAIL_COUNT 个测试失败${NC}"
    echo "请检查网络配置和服务状态。"
    exit 1
fi