#!/bin/bash
# 环境状态检查脚本

echo "=== 考培练系统环境状态检查 ==="
echo "检查时间: $(date)"
echo ""

# 检查前端环境
echo "🌐 前端环境检查:"
if curl -s -f http://localhost:3001 > /dev/null; then
    echo "✅ 前端服务运行正常 (http://localhost:3001)"
    
    # 尝试获取环境信息
    if command -v jq &> /dev/null; then
        echo "📊 前端环境信息:"
        curl -s http://localhost:3001/api/env 2>/dev/null | jq . || echo "无法获取环境信息"
    fi
else
    echo "❌ 前端服务不可访问"
fi
echo ""

# 检查后端环境
echo "🚀 后端环境检查:"
if curl -s -f http://localhost:8000/health > /dev/null; then
    echo "✅ 后端服务运行正常 (http://localhost:8000)"
    
    # 获取健康检查信息
    if command -v jq &> /dev/null; then
        echo "📊 后端环境信息:"
        curl -s http://localhost:8000/health | jq .
    else
        echo "健康检查响应:"
        curl -s http://localhost:8000/health
    fi
else
    echo "❌ 后端服务不可访问"
fi
echo ""

# 检查数据库连接
echo "🗄️  数据库连接检查:"
if curl -s -f http://localhost:8000/health/db > /dev/null 2>&1; then
    echo "✅ 数据库连接正常"
    if command -v jq &> /dev/null; then
        curl -s http://localhost:8000/health/db | jq .
    fi
else
    echo "❌ 数据库连接异常"
fi
echo ""

# 检查Redis连接
echo "🔴 Redis连接检查:"
if curl -s -f http://localhost:8000/health/redis > /dev/null 2>&1; then
    echo "✅ Redis连接正常"
    if command -v jq &> /dev/null; then
        curl -s http://localhost:8000/health/redis | jq .
    fi
else
    echo "❌ Redis连接异常"
fi
echo ""

# 检查Docker容器状态
echo "🐳 Docker容器状态:"
if command -v docker &> /dev/null; then
    echo "开发环境容器:"
    docker-compose -f docker-compose.dev.yml ps 2>/dev/null || echo "无法获取开发环境容器状态"
    echo ""
    echo "生产环境容器:"
    docker-compose ps 2>/dev/null || echo "无法获取生产环境容器状态"
else
    echo "Docker未安装或不可访问"
fi
echo ""

# 检查端口占用
echo "🔌 端口占用检查:"
ports=(3001 8000 3306 6379)
for port in "${ports[@]}"; do
    if lsof -i :$port > /dev/null 2>&1; then
        echo "✅ 端口 $port 已占用"
        lsof -i :$port | head -2 | tail -1 | awk '{print "   进程:", $2, "命令:", $1}'
    else
        echo "❌ 端口 $port 未占用"
    fi
done
echo ""

echo "=== 环境检查完成 ==="