#!/usr/bin/env bash
# 修复 Nginx /mcp 配置位置错误
# 问题: sed 把 /mcp location 插到了 /wake/ 块内部
# 解决: 用正确的完整配置替换

set -e

CONF="/etc/nginx/sites-enabled/guanghulab"

echo "── 修复 Nginx 配置 ──"

# 先备份
cp "$CONF" "${CONF}.bak.$(date +%Y%m%d%H%M%S)"

# 用 Python 精确修复：删除错误位置的 /mcp 和 /mcp-health 块，然后在正确位置重新插入
python3 << 'PYEOF'
import re, sys

conf_path = "/etc/nginx/sites-enabled/guanghulab"
with open(conf_path, 'r') as f:
    content = f.read()

# 1. 删除之前 sed 错误插入的 /mcp 和 /mcp-health 块（可能在不同位置）
# 匹配从 "# ─── 铸渊 MCP" 到 "}" 的完整块
content = re.sub(
    r'\s*# ─── 铸渊 MCP Server.*?location = /mcp-health \{[^}]*\}',
    '',
    content,
    flags=re.DOTALL
)

# 2. 在 "location /wake/" 之前插入 /mcp 块（在 server 块顶层）
mcp_block = '''

    # ─── 铸渊 MCP Server (/mcp) ───
    # WorkBuddy / CodeBuddy 通过 MCP 协议连接
    location /mcp {
        proxy_pass http://127.0.0.1:8083;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # SSE / 长连接支持
        proxy_set_header Connection '';
        proxy_buffering off;
        proxy_cache off;
        proxy_read_timeout 86400s;
        proxy_send_timeout 86400s;
    }

    # ─── MCP 健康检查 ───
    location = /mcp-health {
        proxy_pass http://127.0.0.1:8083/health;
        access_log off;
    }
'''

# 在 "location /wake/" 之前插入
if 'location /mcp' not in content:
    content = content.replace('location /wake/', mcp_block + '\n    location /wake/')

with open(conf_path, 'w') as f:
    f.write(content)

print("✅ 配置已修复")
PYEOF

# 测试 Nginx 配置
echo "── 测试 Nginx ──"
if nginx -t 2>&1; then
    nginx -s reload
    echo "✅ Nginx 已重载"
else
    echo "❌ Nginx 配置仍有问题，请检查"
    exit 1
fi

# 验证 MCP Server
echo ""
echo "── 验证 ──"
sleep 1

if curl -sf http://127.0.0.1:8083/health > /dev/null 2>&1; then
    echo "✅ MCP Server 本地健康检查通过"
else
    echo "❌ MCP Server 本地健康检查失败"
fi

if curl -sf https://guanghulab.com/mcp-health > /dev/null 2>&1; then
    echo "✅ MCP Server 公网健康检查通过"
else
    echo "⚠️  MCP Server 公网健康检查未通过（可能需要等 DNS 或 SSL）"
fi

# 显示密钥
if [ -f "/data/guanghulab/mcp-server/.access-key" ]; then
    KEY=$(cat /data/guanghulab/mcp-server/.access-key)
    echo ""
    echo "═══════════════════════════════════════"
    echo "  🔑 MCP 连接密钥: $KEY"
    echo "═══════════════════════════════════════"
fi
