#!/bin/bash
# Trae IDE 连接问题诊断和修复脚本

echo "=== Trae IDE 连接诊断工具 ==="
echo ""

# 当前服务器信息
TRAE_VERSION="8fe6088bdb0697eec2662377a7abd7f9791493c6"
SERVER_HOST="127.0.0.1"
SERVER_PORT="45697"
TOKEN="b255e0cf-4fab-489d-9175-412a965ea751"
WORKSPACE="/home/ben/github/liurenchaxin"

echo "📋 当前服务器信息:"
echo "   版本: $TRAE_VERSION"
echo "   地址: $SERVER_HOST:$SERVER_PORT"
echo "   Token: $TOKEN"
echo "   工作区: $WORKSPACE"
echo ""

# 1. 检查服务器状态
echo "🔍 1. 检查服务器进程状态..."
if pgrep -f "stable-$TRAE_VERSION" > /dev/null; then
    echo "   ✅ Trae 服务器正在运行"
    ps aux | grep "stable-$TRAE_VERSION" | grep -v grep
else
    echo "   ❌ Trae 服务器未运行"
fi
echo ""

# 2. 检查端口监听
echo "🔍 2. 检查端口监听状态..."
if ss -tln | grep ":$SERVER_PORT" > /dev/null; then
    echo "   ✅ 端口 $SERVER_PORT 正在监听"
else
    echo "   ❌ 端口 $SERVER_PORT 未监听"
fi
echo ""

# 3. 测试 HTTP 连接
echo "🔍 3. 测试 HTTP 连接..."
if curl -s -I "http://$SERVER_HOST:$SERVER_PORT" | grep -q "405\|200"; then
    echo "   ✅ HTTP 连接正常"
else
    echo "   ❌ HTTP 连接失败"
fi
echo ""

# 4. 检查 SSH 服务
echo "🔍 4. 检查 SSH 服务状态..."
if systemctl is-active ssh > /dev/null 2>&1; then
    echo "   ✅ SSH 服务运行正常"
    echo "   SSH 端口: $(ss -tln | grep ':22 ' | head -1)"
else
    echo "   ❌ SSH 服务未运行"
fi
echo ""

# 5. 检查网络可达性
echo "🔍 5. 检查网络配置..."
echo "   本机 IP 地址:"
ip addr show | grep "inet " | grep -v "127.0.0.1" | head -3
echo ""

# 6. 检查防火墙
echo "🔍 6. 检查防火墙状态..."
if command -v ufw > /dev/null; then
    echo "   UFW 状态: $(ufw status | head -1)"
elif command -v firewall-cmd > /dev/null; then
    echo "   Firewalld 状态: $(systemctl is-active firewalld)"
else
    echo "   未检测到常见防火墙"
fi
echo ""

# 解决方案建议
echo "💡 解决方案建议:"
echo ""
echo "🔧 方案1 - 直接浏览器访问:"
echo "   打开浏览器访问: http://$SERVER_HOST:$SERVER_PORT/?folder=$WORKSPACE"
echo ""
echo "🔧 方案2 - Trae 客户端连接:"
echo "   1. 在 Trae 客户端中选择 'Connect to Server'"
echo "   2. 输入服务器地址: $SERVER_HOST:$SERVER_PORT"
echo "   3. 输入连接 Token: $TOKEN"
echo ""
echo "🔧 方案3 - SSH 连接方式:"
echo "   1. 主机: $(hostname -I | awk '{print $1}')"
echo "   2. 用户: ben"
echo "   3. 确保 SSH 密钥已配置"
echo ""
echo "🔧 方案4 - 重置和重启:"
if [ -f "/home/ben/github/liurenchaxin/reset_trae.sh" ]; then
    echo "   运行: ./reset_trae.sh"
else
    echo "   清理缓存: rm -rf /home/ben/.trae-server/data/User/workspaceStorage"
    echo "   重启服务器: pkill -f trae && ./start_trae_server.sh"
fi
echo ""

# 常见问题排查
echo "❓ 如果仍然连接失败，请检查:"
echo "   1. Trae 客户端版本是否与服务器匹配"
echo "   2. 是否有其他安全软件阻止连接"
echo "   3. 网络是否允许访问该端口"
echo "   4. 是否需要重启 Trae 客户端应用"
echo "   5. 检查客户端错误日志"
echo ""

echo "📝 当前连接 URL:"
echo "   http://$SERVER_HOST:$SERVER_PORT/?folder=$WORKSPACE"
echo "   Token: $TOKEN"