#!/bin/bash
# test_upload.sh - 测试文档上传（支持虚拟环境）

set -e

API_URL=${API_URL:-http://localhost:8000}

echo "========================================"
echo "测试文档上传功能"
echo "========================================"
echo ""

echo "API地址: $API_URL"
echo ""

# 检查健康状态
echo "1. 检查服务健康状态..."
curl -s $API_URL/health | python -m json.tool 2>/dev/null || curl -s $API_URL/health
echo ""

# 检查文件参数
if [ -z "$1" ]; then
    echo "使用方法: ./test_upload.sh <文件路径>"
    echo ""
    echo "示例:"
    echo "  ./test_upload.sh sample.pdf"
    echo "  ./test_upload.sh sample.docx"
    exit 1
fi

FILE_PATH=$1

if [ ! -f "$FILE_PATH" ]; then
    echo "错误: 文件不存在: $FILE_PATH"
    exit 1
fi

FILE_NAME=$(basename "$FILE_PATH")
FILE_EXT="${FILE_NAME##*.}"

echo "文件: $FILE_PATH"
echo "类型: $FILE_EXT"
echo ""

# 上传文档
echo "2. 上传文档..."
echo ""

RESPONSE=$(curl -s -X POST "$API_URL/api/v1/documents/upload" \
    -F "file=@$FILE_PATH" \
    -F "doc_name=$FILE_NAME" \
    -F "regulation_type=测试法规")

echo "$RESPONSE" | python -m json.tool 2>/dev/null || echo "$RESPONSE"
echo ""

# 提取doc_id
DOC_ID=$(echo "$RESPONSE" | python -c "import sys,json; d=json.load(sys.stdin); print(d.get('doc_id',''))" 2>/dev/null)

if [ -n "$DOC_ID" ]; then
    echo "文档ID: $DOC_ID"
    echo ""

    # 测试检索
    echo "3. 测试检索..."
    echo ""

    SEARCH_QUERY="法规安全要求"

    curl -s -X POST "$API_URL/api/v1/knowledge/search" \
        -H "Content-Type: application/json" \
        -d "{\"query\": \"$SEARCH_QUERY\", \"top_k\": 5}" \
        | python -m json.tool 2>/dev/null || cat
else
    echo "上传可能失败，请检查响应内容"
fi