#!/bin/bash

# HTTP服务器测试脚本

BASE_URL="http://localhost:8080"

echo "=========================================="
echo "RTSP视频流管理HTTP服务器 API测试"
echo "=========================================="
echo ""

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

# 测试函数
test_api() {
    local method=$1
    local endpoint=$2
    local description=$3
    
    echo -e "${YELLOW}测试: ${description}${NC}"
    echo "请求: ${method} ${endpoint}"
    echo "响应:"
    
    if [ "$method" == "GET" ]; then
        curl -s -w "\nHTTP状态码: %{http_code}\n" "${BASE_URL}${endpoint}" | jq . 2>/dev/null || curl -s -w "\nHTTP状态码: %{http_code}\n" "${BASE_URL}${endpoint}"
    elif [ "$method" == "DELETE" ]; then
        curl -s -X DELETE -w "\nHTTP状态码: %{http_code}\n" "${BASE_URL}${endpoint}" | jq . 2>/dev/null || curl -s -X DELETE -w "\nHTTP状态码: %{http_code}\n" "${BASE_URL}${endpoint}"
    fi
    
    echo ""
    echo "----------------------------------------"
    echo ""
}

# 检查服务器是否运行
echo "检查服务器状态..."
if ! curl -s "${BASE_URL}/api/timestamps" > /dev/null 2>&1; then
    echo -e "${RED}错误: HTTP服务器未运行或无法连接${NC}"
    echo "请先启动服务器: ./cmake-build-debug/jtjai_http_server"
    exit 1
fi

echo -e "${GREEN}服务器已就绪${NC}"
echo ""

# 1. 列出所有时间戳目录
test_api "GET" "/api/timestamps" "列出所有时间戳目录"

# 2. 列出所有视频
test_api "GET" "/api/videos" "列出所有视频"

# 3. 列出指定时间戳的视频（需要根据实际情况修改）
# 先获取第一个时间戳
FIRST_TIMESTAMP=$(curl -s "${BASE_URL}/api/timestamps" | jq -r '.timestamps[0].timestamp' 2>/dev/null)

if [ ! -z "$FIRST_TIMESTAMP" ] && [ "$FIRST_TIMESTAMP" != "null" ]; then
    echo -e "${YELLOW}找到时间戳: ${FIRST_TIMESTAMP}${NC}"
    test_api "GET" "/api/videos/${FIRST_TIMESTAMP}" "列出时间戳 ${FIRST_TIMESTAMP} 的视频"
    test_api "GET" "/api/videos?timestamp=${FIRST_TIMESTAMP}" "列出时间戳 ${FIRST_TIMESTAMP} 的视频（查询参数方式）"
fi

echo ""
echo -e "${GREEN}测试完成！${NC}"
echo ""
echo "删除操作测试（注释掉以避免误删）："
echo "# 删除单个视频:"
echo "# curl -X DELETE \"${BASE_URL}/api/video?path=./output/TIMESTAMP/filename.mp4\""
echo ""
echo "# 删除整个时间戳目录:"
echo "# curl -X DELETE \"${BASE_URL}/api/timestamp/TIMESTAMP\""
echo ""
