#!/bin/bash
# Theseus E2E 全量测试
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "══════════════════════════════════════"
echo "  Theseus E2E 全量测试"
echo "══════════════════════════════════════"

# 启动服务器
echo ""
echo ">>> 启动服务器..."
pkill -f "theseus serve" 2>/dev/null || true
cd "$PROJECT_DIR"
if [ ! -x target/debug/theseus ]; then
    cargo build
fi
export THESEUS_E2E_RUN_ID="${THESEUS_E2E_RUN_ID:-$(date +%s)-$$}"
nohup target/debug/theseus serve --port 3080 > /tmp/theseus-e2e.log 2>&1 &
SERVER_PID=$!
echo "Server PID: $SERVER_PID"
trap 'kill "$SERVER_PID" 2>/dev/null || true' EXIT

# 等待服务器就绪
READY=0
for i in $(seq 1 30); do
    if curl -s http://127.0.0.1:3080/api/projects > /dev/null 2>&1; then
        echo "✅ 服务器就绪"
        READY=1
        break
    fi
    sleep 0.3
done
if [ "$READY" -ne 1 ]; then
    echo "❌ 服务器启动超时"
    exit 1
fi

# 运行所有测试
TESTS=(
    test_projects.py
    test_nodes.py
    test_edges.py
    test_credentials.py
    test_timeline.py
    test_search.py
    test_evidence.py
    test_import.py
    test_daily_report.py
    test_analysis.py
)

PASS=0
FAIL=0

for test in "${TESTS[@]}"; do
    if [ -f "$SCRIPT_DIR/$test" ]; then
        echo ""
        if python3 "$SCRIPT_DIR/$test"; then
            PASS=$((PASS + 1))
        else
            FAIL=$((FAIL + 1))
        fi
    else
        echo "⚠️  $test 不存在，跳过"
    fi
done

# 停止服务器
echo ""
echo ">>> 停止服务器..."
kill $SERVER_PID 2>/dev/null || true

echo ""
echo "══════════════════════════════════════"
echo "  结果: $PASS 通过, $FAIL 失败"
echo "══════════════════════════════════════"

if [ "$FAIL" -ne 0 ]; then
    exit 1
fi
