#!/bin/bash

# 课程资料预览功能测试脚本
# 用途：快速测试API接口是否正常

set -e

BASE_URL="http://localhost:8000"
COURSE_ID=1

echo "========================================="
echo "课程资料预览功能测试"
echo "========================================="
echo ""

# 测试1: 检查后端服务是否启动
echo "测试 1/4: 检查后端服务..."
if curl -s "${BASE_URL}/health" > /dev/null 2>&1; then
    echo "✅ 后端服务正常"
else
    echo "❌ 后端服务未启动，请先运行启动脚本"
    exit 1
fi

echo ""

# 测试2: 检查LibreOffice安装
echo "测试 2/4: 检查LibreOffice安装状态..."
CONVERTER_STATUS=$(curl -s "${BASE_URL}/api/v1/preview/check-converter" || echo "{}")
echo "$CONVERTER_STATUS" | python3 -m json.tool 2>/dev/null || echo "$CONVERTER_STATUS"

if echo "$CONVERTER_STATUS" | grep -q '"libreoffice_installed": true'; then
    echo "✅ LibreOffice安装成功"
else
    echo "⚠️  LibreOffice未安装或检测失败"
    echo "   请检查Docker镜像是否正确构建"
fi

echo ""

# 测试3: 获取课程资料列表
echo "测试 3/4: 获取课程资料列表..."
MATERIALS=$(curl -s "${BASE_URL}/api/v1/courses/${COURSE_ID}/materials" || echo "{}")
echo "$MATERIALS" | python3 -m json.tool 2>/dev/null || echo "$MATERIALS"

MATERIAL_COUNT=$(echo "$MATERIALS" | grep -o '"id"' | wc -l)
if [ "$MATERIAL_COUNT" -gt 0 ]; then
    echo "✅ 找到 ${MATERIAL_COUNT} 个资料"
else
    echo "⚠️  该课程暂无资料"
    echo "   请先在课程管理中上传测试文件"
fi

echo ""

# 测试4: 测试预览接口（如果有资料）
if [ "$MATERIAL_COUNT" -gt 0 ]; then
    echo "测试 4/4: 测试资料预览接口..."
    
    # 提取第一个资料的ID
    MATERIAL_ID=$(echo "$MATERIALS" | grep -o '"id": *[0-9]*' | head -1 | grep -o '[0-9]*')
    
    if [ -n "$MATERIAL_ID" ]; then
        echo "   测试资料ID: ${MATERIAL_ID}"
        PREVIEW_INFO=$(curl -s "${BASE_URL}/api/v1/preview/material/${MATERIAL_ID}" || echo "{}")
        echo "$PREVIEW_INFO" | python3 -m json.tool 2>/dev/null || echo "$PREVIEW_INFO"
        
        if echo "$PREVIEW_INFO" | grep -q '"preview_type"'; then
            echo "✅ 预览接口正常"
        else
            echo "❌ 预览接口异常"
        fi
    fi
else
    echo "测试 4/4: 跳过（无资料可测试）"
fi

echo ""
echo "========================================="
echo "测试完成！"
echo "========================================="
echo ""
echo "📝 下一步："
echo "  1. 如果LibreOffice未安装，请重新构建Docker镜像"
echo "  2. 如果无资料，请访问管理后台上传测试文件"
echo "  3. 在浏览器中访问课程详情页进行完整测试"
echo "     http://localhost:3001/trainee/course-detail?id=${COURSE_ID}"
echo ""
echo "📖 详细测试指南："
echo "  kaopeilian-frontend/课程资料预览功能测试指南.md"
echo ""

