#!/bin/bash
echo "=========================================="
echo "  飞书实时监控 · 一键诊断工具"
echo "=========================================="
echo ""

# 1. 检查 server.py 进程
echo "[1/4] 检查服务器进程..."
if pgrep -f "server.py" > /dev/null; then
    echo "✓ server.py 正在运行"
else
    echo "✗ 未找到 server.py 进程"
    echo "  请先运行 bash start.sh"
fi
echo ""

# 2. 检查端口 8080
echo "[2/4] 检查端口 8080..."
if command -v ss &> /dev/null; then
    if ss -tlnp | grep -q ":8080"; then
        echo "✓ 端口 8080 已被占用"
        ss -tlnp | grep ":8080"
    else
        echo "✗ 端口 8080 未被占用，服务器未启动"
    fi
elif command -v netstat &> /dev/null; then
    if netstat -tlnp 2>/dev/null | grep -q ":8080"; then
        echo "✓ 端口 8080 已被占用"
        netstat -tlnp | grep ":8080"
    else
        echo "✗ 端口 8080 未被占用，服务器未启动"
    fi
else
    echo "⚠ 无法检查端口（ss/netstat 不可用）"
fi
echo ""

# 3. 测试 HTTP 连接
echo "[3/4] 测试 HTTP 连接 http://localhost:8080 ..."
if command -v curl &> /dev/null; then
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 http://localhost:8080/ 2>/dev/null)
    if [ -n "$HTTP_CODE" ]; then
        echo "✓ HTTP 连接成功，状态码：$HTTP_CODE"
    else
        echo "✗ HTTP 连接失败"
    fi
else
    echo "⚠ curl 不可用，跳过 HTTP 测试"
fi
echo ""

# 4. 测试 API 接口
echo "[4/4] 测试 API 接口 http://localhost:8080/api/devices ..."
if command -v curl &> /dev/null; then
    API_RESULT=$(curl -s --connect-timeout 5 http://localhost:8080/api/devices 2>/dev/null)
    if [ -n "$API_RESULT" ]; then
        echo "✓ API 返回成功"
        echo "  $API_RESULT"
    else
        echo "✗ API 调用失败"
    fi
else
    echo "⚠ curl 不可用，跳过 API 测试"
fi
echo ""

echo "=========================================="
echo "诊断完成，请根据以上信息排查问题"
echo "=========================================="
