#!/bin/bash

# ============================================
# 初中物理作业批改工作流 - 部署验证脚本
# ============================================

set -e

echo "======================================"
echo "  部署验证测试"
echo "======================================"
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 测试计数
PASS=0
FAIL=0

# 测试函数
test_step() {
    local name=$1
    local command=$2
    
    echo -n "测试: $name ... "
    
    if eval "$command" > /dev/null 2>&1; then
        echo -e "${GREEN}✅ 通过${NC}"
        ((PASS++))
        return 0
    else
        echo -e "${RED}❌ 失败${NC}"
        ((FAIL++))
        return 1
    fi
}

# 1. 环境检查
echo "1. 环境检查"
echo "-----------------------------------"

test_step "Python 版本" "python3 --version"
test_step "虚拟环境" "test -d venv"
test_step "依赖安装" "python3 -c 'import fastapi'"
test_step "依赖安装" "python3 -c 'import langgraph'"
test_step "依赖安装" "python3 -c 'import openai'"
echo ""

# 2. 配置检查
echo "2. 配置检查"
echo "-----------------------------------"

if [ -f ".env" ]; then
    echo -e "${GREEN}✅ .env 文件存在${NC}"
    ((PASS++))
    
    # 检查必需环境变量
    source .env
    
    if [ -n "$LLM_API_KEY" ] && [ "$LLM_API_KEY" != "your-api-key-here" ]; then
        echo -e "${GREEN}✅ LLM_API_KEY 已配置${NC}"
        ((PASS++))
    else
        echo -e "${RED}❌ LLM_API_KEY 未配置${NC}"
        ((FAIL++))
    fi
    
    if [ -n "$LLM_BASE_URL" ]; then
        echo -e "${GREEN}✅ LLM_BASE_URL 已配置${NC}"
        ((PASS++))
    else
        echo -e "${RED}❌ LLM_BASE_URL 未配置${NC}"
        ((FAIL++))
    fi
    
    if [ -n "$LLM_MODEL_NAME" ]; then
        echo -e "${GREEN}✅ LLM_MODEL_NAME 已配置${NC}"
        ((PASS++))
    else
        echo -e "${RED}❌ LLM_MODEL_NAME 未配置${NC}"
        ((FAIL++))
    fi
    
    echo -e "${GREEN}✅ 无需配置对象存储（已优化）${NC}"
    ((PASS++))
else
    echo -e "${RED}❌ .env 文件不存在${NC}"
    ((FAIL++))
fi
echo ""

# 3. 文件完整性检查
echo "3. 文件完整性检查"
echo "-----------------------------------"

test_step "主入口文件" "test -f src/main.py"
test_step "主工作流" "test -f src/graphs/graph.py"
test_step "状态定义" "test -f src/graphs/state.py"
test_step "配置文件目录" "test -d config"
test_step "启动脚本" "test -f scripts/http_run.sh"
echo ""

# 4. 模块导入测试
echo "4. 模块导入测试"
echo "-----------------------------------"

test_step "导入主模块" "python3 -c 'from graphs.state import GlobalState'"
test_step "导入节点模块" "python3 -c 'from graphs.nodes.doc_extract_node import doc_extract_node'"
echo ""

# 5. 服务启动测试（可选）
echo "5. 服务启动测试"
echo "-----------------------------------"

if command -v curl &> /dev/null; then
    # 检查服务是否已启动
    if curl -s http://localhost:8000/health > /dev/null 2>&1; then
        echo -e "${GREEN}✅ 服务已运行在 http://localhost:8000${NC}"
        ((PASS++))
        
        # 测试健康检查
        HEALTH=$(curl -s http://localhost:8000/health)
        if echo "$HEALTH" | grep -q "ok"; then
            echo -e "${GREEN}✅ 健康检查通过${NC}"
            ((PASS++))
        else
            echo -e "${RED}❌ 健康检查失败${NC}"
            ((FAIL++))
        fi
    else
        echo -e "${YELLOW}⚠️  服务未启动，跳过服务测试${NC}"
        echo "   启动服务: bash scripts/http_run.sh -p 8000"
    fi
else
    echo -e "${YELLOW}⚠️  curl 未安装，跳过服务测试${NC}"
fi
echo ""

# 测试总结
echo "======================================"
echo "  测试总结"
echo "======================================"
echo ""
echo -e "${GREEN}通过: $PASS${NC}"
echo -e "${RED}失败: $FAIL${NC}"
echo ""

if [ $FAIL -eq 0 ]; then
    echo -e "${GREEN}✅ 所有测试通过！部署成功！${NC}"
    echo ""
    echo "下一步："
    echo "  1. 启动服务: bash scripts/http_run.sh -p 8000"
    echo "  2. 访问文档: http://localhost:8000/docs"
    echo "  3. 发送测试请求: curl -X POST http://localhost:8000/run -H 'Content-Type: application/json' -d @test_payload.json"
    exit 0
else
    echo -e "${RED}❌ 部分测试失败，请检查配置${NC}"
    echo ""
    echo "常见问题："
    echo "  - 环境变量未配置: 编辑 .env 文件"
    echo "  - 依赖未安装: pip install -r requirements.txt"
    echo "  - 文件缺失: 检查项目完整性"
    exit 1
fi
