#!/bin/bash

# Coze AI客服接口测试脚本
# 用于测试前端与后端AI客服系统的跨域通信和接口功能
# 作者: AlchemyStudio
# 创建时间: 2025-09-06

# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 配置变量
BACKEND_URL="http://localhost:5000"
FRONTEND_URL="http://localhost:8000"
API_BASE="${BACKEND_URL}/coze"
AUTH_HEADER="Authorization: Basic aHVpd2luZzo5dm9EOVNSMVNMS3h3SnhNeVFNVQ=="

# 全局变量
SESSION_ID=""
SESSION_STATUS=""
CHAT_ID=""

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# 解码Unicode转义序列为可读文本
decode_unicode() {
    local text="$1"
    # 尝试使用Python解码Unicode，如果失败则返回原文本
    echo "$text" | python3 -c "import sys, json; print(json.loads('\"' + sys.stdin.read().strip() + '\"'))" 2>/dev/null || echo "$text"
}

# 检查服务是否运行
check_services() {
    print_info "检查服务状态..."
    
    # 检查后端服务
    if curl -s "${BACKEND_URL}/coze/health" > /dev/null 2>&1; then
        print_success "后端服务运行正常 (${BACKEND_URL})"
    else
        print_error "后端服务未运行或无法访问 (${BACKEND_URL})"
        return 1
    fi
    
    # 检查前端服务
    if curl -s "${FRONTEND_URL}" > /dev/null 2>&1; then
        print_success "前端服务运行正常 (${FRONTEND_URL})"
    else
        print_warning "前端服务未运行或无法访问 (${FRONTEND_URL})"
    fi
    
    echo
}

# 测试创建会话接口
test_create_session() {
    print_info "测试创建会话接口..."
    
    local response=$(curl -s -X POST "${API_BASE}/sessions" \
        -H "${AUTH_HEADER}" \
        -H 'Content-Type: application/json' \
        -H "Origin: ${FRONTEND_URL}" \
        -H "Referer: ${FRONTEND_URL}/tester/ai-cs" \
        -d '{"user_id": "test_user", "bot_id": "default-bot-id"}')
    
    if echo "$response" | grep -q '"success":true'; then
        # 提取会话ID
        SESSION_ID=$(echo "$response" | grep -o '"session_id":"[^"]*"' | cut -d'"' -f4)
        print_success "会话创建成功，会话ID: ${SESSION_ID}"
        echo "响应: $response" | head -c 200
        echo "..."
        echo
        return 0
    else
        print_error "会话创建失败"
        echo "响应: $response"
        echo
        return 1
    fi
}

# 测试发送消息接口
test_send_message() {
    if [ -z "$SESSION_ID" ]; then
        print_error "没有可用的会话ID，请先创建会话"
        return 1
    fi
    
    print_info "测试发送消息接口..."
    
    local test_message="你好，这是一个测试消息，请问你能帮我做什么？"
    local response=$(curl -s -X POST "${API_BASE}/sessions/${SESSION_ID}/messages" \
        -H "${AUTH_HEADER}" \
        -H 'Content-Type: application/json' \
        -H "Origin: ${FRONTEND_URL}" \
        -H "Referer: ${FRONTEND_URL}/tester/ai-cs" \
        -d "{\"message\": \"${test_message}\"}")
    
    if echo "$response" | grep -q '"success":true'; then
        print_success "消息发送成功"
        
        # 提取聊天ID (从task_result.data中获取，应该是coze_chat_格式)
        local chat_id=$(echo "$response" | grep -o '"chat_id":"coze_chat_[^"]*"' | head -1 | cut -d'"' -f4)
        if [ -z "$chat_id" ]; then
            # 备用：尝试提取任何格式的chat_id
            chat_id=$(echo "$response" | grep -o '"chat_id":"[^"]*"' | head -1 | cut -d'"' -f4)
        fi
        
        if [ ! -z "$chat_id" ]; then
            CHAT_ID="$chat_id"
            print_info "聊天ID: $chat_id"
            
            # 立即开始监控聊天状态，等待completed
            print_info "开始监控聊天状态，等待AI处理完成..."
            if wait_for_chat_completion "$chat_id"; then
                print_success "聊天处理完成！"
                return 0
            else
                print_error "聊天处理失败或超时"
                return 1
            fi
        else
            print_error "未能提取到聊天ID"
            return 1
        fi
    else
        print_error "消息发送失败"
        echo "响应: $response"
        echo
        return 1
    fi
}

# 测试获取会话信息接口
test_get_session() {
    if [ -z "$SESSION_ID" ]; then
        print_error "没有可用的会话ID，请先创建会话"
        return 1
    fi
    
    print_info "测试获取会话信息接口..."
    
    local response=$(curl -s -X GET "${API_BASE}/sessions/${SESSION_ID}" \
        -H "${AUTH_HEADER}" \
        -H "Origin: ${FRONTEND_URL}" \
        -H "Referer: ${FRONTEND_URL}/tester/ai-cs")
    
    if echo "$response" | grep -q '"success":true'; then
        print_success "会话信息获取成功"
        
        # 提取会话状态
        local session_status=$(echo "$response" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
        if [ ! -z "$session_status" ]; then
            print_info "会话状态: $session_status"
            SESSION_STATUS="$session_status"
        fi
        
        echo "响应: $response" | head -c 200
        echo "..."
        echo
        return 0
    else
        print_error "会话信息获取失败"
        echo "响应: $response"
        echo
        return 1
    fi
}

# 测试获取会话聊天记录接口
test_get_session_chats() {
    if [ -z "$SESSION_ID" ]; then
        print_error "没有可用的会话ID，请先创建会话"
        return 1
    fi
    
    print_info "测试获取会话聊天记录接口..."
    
    local response=$(curl -s -X GET "${API_BASE}/sessions/${SESSION_ID}/chats" \
        -H "${AUTH_HEADER}" \
        -H "Origin: ${FRONTEND_URL}" \
        -H "Referer: ${FRONTEND_URL}/tester/ai-cs")
    
    if echo "$response" | grep -q '"success":true'; then
        print_success "会话聊天记录获取成功"
        
        # 提取聊天记录数量
        local chat_count=$(echo "$response" | grep -o '"chat_id"' | wc -l | tr -d ' ')
        print_info "聊天记录数量: $chat_count"
        
        echo "响应: $response" | head -c 300
        echo "..."
        echo
        return 0
    else
        print_error "会话聊天记录获取失败"
        echo "响应: $response"
        echo
        return 1
    fi
}

# 等待聊天完成的函数
wait_for_chat_completion() {
    local chat_id="$1"
    local max_wait_time=120  # 最大等待时间（秒）
    local poll_interval=2    # 轮询间隔（秒）
    local start_time=$(date +%s)
    local attempt_count=0
    local last_status=""
    
    while true; do
        local current_time=$(date +%s)
        local elapsed_time=$((current_time - start_time))
        
        # 检查是否超时
        if [ $elapsed_time -ge $max_wait_time ]; then
            print_warning "聊天状态监控超时 (超过${max_wait_time}秒)"
            return 1
        fi
        
        attempt_count=$((attempt_count + 1))
        
        # 获取聊天结果
        local response=$(curl -s -X GET "${API_BASE}/chats/${chat_id}/result" \
            -H "${AUTH_HEADER}" \
            -H "Origin: ${FRONTEND_URL}" \
            -H "Referer: ${FRONTEND_URL}/tester/ai-cs")
        
        if echo "$response" | grep -q '"success":true'; then
            # 提取当前状态
            local current_status=$(echo "$response" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
            
            # 只在状态变化时或每5次检查时打印进度
            if [ "$current_status" != "$last_status" ] || [ $((attempt_count % 5)) -eq 0 ]; then
                print_info "[${elapsed_time}s] 第${attempt_count}次检查 - 聊天状态: $current_status"
                last_status="$current_status"
            fi
            
            # 检查状态是否为completed
            if [ "$current_status" = "completed" ]; then
                print_success "检测到聊天状态为 completed！"
                return 0
                
            elif [ "$current_status" = "failed" ]; then
                print_error "聊天状态变为 failed (耗时: ${elapsed_time}s)"
                local error_msg=$(echo "$response" | grep -o '"message":"[^"]*"' | cut -d'"' -f4)
                if [ ! -z "$error_msg" ]; then
                    print_error "错误详情: $error_msg"
                fi
                return 1
                
            elif [ "$current_status" = "pending" ] || [ "$current_status" = "processing" ] || [ "$current_status" = "in_progress" ]; then
                # 继续等待，状态正在进行中
                :
            else
                print_warning "未知状态: $current_status"
            fi
        else
            print_warning "第${attempt_count}次尝试获取状态失败，重试中..."
            local error_msg=$(echo "$response" | grep -o '"message":"[^"]*"' | cut -d'"' -f4)
            if [ ! -z "$error_msg" ]; then
                print_warning "错误信息: $error_msg"
            fi
        fi
        
        # 等待后再次检查
        sleep $poll_interval
    done
}

# 测试获取聊天结果接口（获取最终完成的结果）
test_get_chat_result() {
    if [ -z "$CHAT_ID" ]; then
        print_warning "没有可用的聊天ID，跳过聊天结果测试"
        return 0
    fi
    
    print_info "测试获取聊天结果接口..."
    print_info "聊天ID: $CHAT_ID"
    
    # 获取聊天结果
    local response=$(curl -s -X GET "${API_BASE}/chats/${CHAT_ID}/result" \
        -H "${AUTH_HEADER}" \
        -H "Origin: ${FRONTEND_URL}" \
        -H "Referer: ${FRONTEND_URL}/tester/ai-cs")
    
    if echo "$response" | grep -q '"success":true'; then
        local current_status=$(echo "$response" | grep -o '"status":"[^"]*"' | cut -d'"' -f4)
        
        if [ "$current_status" = "completed" ]; then
            print_success "获取完整聊天结果成功！"
            
            # 提取并显示对话内容（解码Unicode转义序列）
            local user_content_raw=$(echo "$response" | grep -o '"user_message":{[^}]*"content":"[^"]*"' | grep -o '"content":"[^"]*"' | cut -d'"' -f4)
            local ai_content_raw=$(echo "$response" | grep -o '"assistant_message":{[^}]*"content":"[^"]*"' | grep -o '"content":"[^"]*"' | cut -d'"' -f4)
            
            local user_content=$(decode_unicode "$user_content_raw")
            local ai_content=$(decode_unicode "$ai_content_raw")
            
            echo
            print_success "完整聊天结果:"
            echo "==========================================="
            if [ ! -z "$user_content" ]; then
                echo "👤 用户: $user_content"
            fi
            if [ ! -z "$ai_content" ]; then
                echo "🤖 AI: $ai_content"
            fi
            echo "==========================================="
            
            print_info "最终状态: $current_status"
            print_info "聊天ID: $CHAT_ID"
            
            echo "完整响应: $response" | head -c 300
            echo "..."
            echo
            return 0
        else
            print_warning "聊天状态不是completed: $current_status"
            return 1
        fi
    else
        print_error "获取聊天结果失败"
        echo "响应: $response"
        echo
        return 1
    fi
}

# 测试健康检查接口
test_health_check() {
    print_info "测试健康检查接口..."
    
    local response=$(curl -s -X GET "${API_BASE}/health" \
        -H "${AUTH_HEADER}" \
        -H "Origin: ${FRONTEND_URL}")
    
    if echo "$response" | grep -q '"success":true'; then
        print_success "健康检查通过"
        echo "响应: $response"
        echo
        return 0
    else
        print_error "健康检查失败"
        echo "响应: $response"
        echo
        return 1
    fi
}

# 主测试流程
main() {
    echo "==========================================="
    echo "        Coze AI客服接口测试脚本"
    echo "==========================================="
    echo
    
    # 检查服务状态
    if ! check_services; then
        print_error "服务检查失败，请确保后端服务正在运行"
        exit 1
    fi
    
    # 执行测试
    local test_count=0
    local success_count=0
    
    # 测试健康检查
    ((test_count++))
    if test_health_check; then
        ((success_count++))
    fi
    
    # 测试创建会话
    ((test_count++))
    if test_create_session; then
        ((success_count++))
        
        # 测试发送消息（依赖会话创建成功，包含等待完成逻辑）
        ((test_count++))
        if test_send_message; then
            ((success_count++))
            
            # 发送消息成功后，测试获取最终聊天结果
            if [ ! -z "$CHAT_ID" ]; then
                ((test_count++))
                if test_get_chat_result; then
                    ((success_count++))
                fi
            fi
        fi
        
        # 测试获取会话信息（依赖会话创建成功）
        ((test_count++))
        if test_get_session; then
            ((success_count++))
            
            # 如果会话状态是completed，获取会话聊天记录
            if [ "$SESSION_STATUS" = "completed" ] || [ "$SESSION_STATUS" = "active" ]; then
                ((test_count++))
                if test_get_session_chats; then
                    ((success_count++))
                fi
            fi
        fi
    fi
    
    # 输出测试结果
    echo "==========================================="
    echo "              测试结果汇总"
    echo "==========================================="
    print_info "总测试数: ${test_count}"
    print_success "成功: ${success_count}"
    
    if [ $success_count -eq $test_count ]; then
        print_success "所有测试通过！🎉"
        exit 0
    else
        local failed_count=$((test_count - success_count))
        print_error "失败: ${failed_count}"
        print_warning "部分测试失败，请检查服务状态和配置"
        exit 1
    fi
}

# 如果直接运行此脚本，执行主函数
if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
    main "$@"
fi