#!/bin/bash

# DC-TOM 测试报告统计数据解析脚本
# 从 mochawesome JSON 报告中提取统计信息，生成统计摘要

set -e

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

# 配置
REPORTS_DIR="cypress/reports"
PUBLIC_DIR="public"
STATS_FILE="$PUBLIC_DIR/test-stats.json"

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

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

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

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

# 检查依赖
check_dependencies() {
    if ! command -v jq &> /dev/null; then
        log_warning "jq 未安装，将使用简化的 JSON 解析"
        return 1
    fi
    return 0
}

# 使用 jq 解析统计信息（如果可用）
extract_stats_with_jq() {
    local json_file=$1
    local output_file=$2
    
    if [ ! -f "$json_file" ]; then
        log_error "JSON 文件不存在: $json_file"
        return 1
    fi
    
    log_info "使用 jq 解析统计信息: $json_file"
    
    # 提取基础统计信息
    local stats=$(jq '.stats' "$json_file")
    local start_time=$(jq -r '.stats.start' "$json_file")
    local end_time=$(jq -r '.stats.end' "$json_file")
    
    # 计算成功率和失败率
    local total_tests=$(jq -r '.stats.tests' "$json_file")
    local passes=$(jq -r '.stats.passes' "$json_file")
    local failures=$(jq -r '.stats.failures' "$json_file")
    local pending=$(jq -r '.stats.pending' "$json_file")
    local duration=$(jq -r '.stats.duration' "$json_file")
    
    # 转换时间格式
    local start_formatted=""
    local end_formatted=""
    local duration_formatted=""
    
    if [ "$start_time" != "null" ] && [ -n "$start_time" ]; then
        start_formatted=$(date -j -f "%Y-%m-%dT%H:%M:%S" "${start_time%.*}" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "$start_time")
    fi
    
    if [ "$end_time" != "null" ] && [ -n "$end_time" ]; then
        end_formatted=$(date -j -f "%Y-%m-%dT%H:%M:%S" "${end_time%.*}" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "$end_time")
    fi
    
    if [ "$duration" != "null" ] && [ -n "$duration" ]; then
        # 转换毫秒为秒
        local seconds=$((duration / 1000))
        local minutes=$((seconds / 60))
        local remaining_seconds=$((seconds % 60))
        if [ $minutes -gt 0 ]; then
            duration_formatted="${minutes}分${remaining_seconds}秒"
        else
            duration_formatted="${seconds}秒"
        fi
    fi
    
    # 计算百分比
    local pass_percent=0
    local fail_percent=0
    if [ "$total_tests" -gt 0 ]; then
        pass_percent=$(echo "scale=1; $passes * 100 / $total_tests" | bc 2>/dev/null || echo "0")
        fail_percent=$(echo "scale=1; $failures * 100 / $total_tests" | bc 2>/dev/null || echo "0")
    fi
    
    # 生成统计摘要
    cat > "$output_file" << EOF
{
  "summary": {
    "totalTests": $total_tests,
    "passes": $passes,
    "failures": $failures,
    "pending": $pending,
    "passPercent": $pass_percent,
    "failPercent": $fail_percent,
    "duration": $duration,
    "durationFormatted": "$duration_formatted"
  },
  "timing": {
    "startTime": "$start_time",
    "endTime": "$end_time",
    "startFormatted": "$start_formatted",
    "endFormatted": "$end_formatted"
  },
  "details": $stats,
  "generatedAt": "$(date '+%Y-%m-%d %H:%M:%S')",
  "sourceFile": "$json_file"
}
EOF
    
    return 0
}

# 简化的 JSON 解析（不依赖 jq）
extract_stats_simple() {
    local json_file=$1
    local output_file=$2
    
    if [ ! -f "$json_file" ]; then
        log_error "JSON 文件不存在: $json_file"
        return 1
    fi
    
    log_info "使用简化解析器解析统计信息: $json_file"
    
    # 使用 grep 和 sed 提取基本信息
    local total_tests=$(grep -o '"tests":[[:space:]]*[0-9]*' "$json_file" | head -1 | cut -d':' -f2 | tr -d ' ')
    local passes=$(grep -o '"passes":[[:space:]]*[0-9]*' "$json_file" | head -1 | cut -d':' -f2 | tr -d ' ')
    local failures=$(grep -o '"failures":[[:space:]]*[0-9]*' "$json_file" | head -1 | cut -d':' -f2 | tr -d ' ')
    local pending=$(grep -o '"pending":[[:space:]]*[0-9]*' "$json_file" | head -1 | cut -d':' -f2 | tr -d ' ')
    local duration=$(grep -o '"duration":[[:space:]]*[0-9]*' "$json_file" | head -1 | cut -d':' -f2 | tr -d ' ')
    
    # 设置默认值
    total_tests=${total_tests:-0}
    passes=${passes:-0}
    failures=${failures:-0}
    pending=${pending:-0}
    duration=${duration:-0}
    
    # 计算百分比
    local pass_percent=0
    local fail_percent=0
    if [ "$total_tests" -gt 0 ]; then
        pass_percent=$((passes * 100 / total_tests))
        fail_percent=$((failures * 100 / total_tests))
    fi
    
    # 格式化时间
    local duration_formatted=""
    if [ "$duration" -gt 0 ]; then
        local seconds=$((duration / 1000))
        local minutes=$((seconds / 60))
        local remaining_seconds=$((seconds % 60))
        if [ $minutes -gt 0 ]; then
            duration_formatted="${minutes}分${remaining_seconds}秒"
        else
            duration_formatted="${seconds}秒"
        fi
    fi
    
    # 生成简化的统计摘要
    cat > "$output_file" << EOF
{
  "summary": {
    "totalTests": $total_tests,
    "passes": $passes,
    "failures": $failures,
    "pending": $pending,
    "passPercent": $pass_percent,
    "failPercent": $fail_percent,
    "duration": $duration,
    "durationFormatted": "$duration_formatted"
  },
  "timing": {
    "startTime": "",
    "endTime": "",
    "startFormatted": "",
    "endFormatted": ""
  },
  "generatedAt": "$(date '+%Y-%m-%d %H:%M:%S')",
  "sourceFile": "$json_file",
  "note": "使用简化解析器生成"
}
EOF
    
    return 0
}

# 解析所有报告并生成汇总统计
analyze_all_reports() {
    log_info "分析所有测试报告..."
    
    # 确保输出目录存在
    mkdir -p "$PUBLIC_DIR"
    
    # 查找最新的合并报告
    local merged_report="$PUBLIC_DIR/reports/merged-report.json"
    
    if [ -f "$merged_report" ]; then
        log_info "发现合并报告: $merged_report"
        
        # 尝试使用 jq 解析，失败则使用简化解析
        if check_dependencies; then
            if extract_stats_with_jq "$merged_report" "$STATS_FILE"; then
                log_success "统计信息提取完成（使用 jq）"
            else
                log_warning "jq 解析失败，尝试简化解析"
                extract_stats_simple "$merged_report" "$STATS_FILE"
            fi
        else
            extract_stats_simple "$merged_report" "$STATS_FILE"
        fi
    else
        log_warning "未找到合并报告，查找单个报告文件..."
        
        # 查找最新的单个报告文件
        local latest_report=$(find "$REPORTS_DIR" -name "*.json" -type f | head -1)
        
        if [ -n "$latest_report" ] && [ -f "$latest_report" ]; then
            log_info "发现单个报告: $latest_report"
            
            if check_dependencies; then
                if extract_stats_with_jq "$latest_report" "$STATS_FILE"; then
                    log_success "统计信息提取完成（使用 jq）"
                else
                    extract_stats_simple "$latest_report" "$STATS_FILE"
                fi
            else
                extract_stats_simple "$latest_report" "$STATS_FILE"
            fi
        else
            log_error "未找到任何测试报告文件"
            # 生成空的统计文件
            cat > "$STATS_FILE" << EOF
{
  "summary": {
    "totalTests": 0,
    "passes": 0,
    "failures": 0,
    "pending": 0,
    "passPercent": 0,
    "failPercent": 0,
    "duration": 0,
    "durationFormatted": "0秒"
  },
  "timing": {
    "startTime": "",
    "endTime": "",
    "startFormatted": "",
    "endFormatted": ""
  },
  "generatedAt": "$(date '+%Y-%m-%d %H:%M:%S')",
  "sourceFile": "无",
  "note": "未找到测试报告"
}
EOF
            return 1
        fi
    fi
    
    return 0
}

# 显示统计摘要
show_stats_summary() {
    if [ ! -f "$STATS_FILE" ]; then
        log_error "统计文件不存在: $STATS_FILE"
        return 1
    fi
    
    log_info "测试统计摘要:"
    echo
    
    # 尝试使用 jq 格式化输出
    if check_dependencies; then
        local total=$(jq -r '.summary.totalTests' "$STATS_FILE")
        local passes=$(jq -r '.summary.passes' "$STATS_FILE")
        local failures=$(jq -r '.summary.failures' "$STATS_FILE")
        local pass_percent=$(jq -r '.summary.passPercent' "$STATS_FILE")
        local duration=$(jq -r '.summary.durationFormatted' "$STATS_FILE")
        local generated=$(jq -r '.generatedAt' "$STATS_FILE")
        
        echo "📊 测试概览:"
        echo "  总测试数: $total"
        echo "  通过数量: $passes"
        echo "  失败数量: $failures"
        echo "  成功率: $pass_percent%"
        echo "  执行时间: $duration"
        echo "  生成时间: $generated"
        echo
        
        # 根据成功率显示状态
        local pass_num=$(echo "$pass_percent" | cut -d'.' -f1)
        if [ "$pass_num" -eq 100 ]; then
            echo -e "${GREEN}✅ 所有测试通过！${NC}"
        elif [ "$pass_num" -ge 80 ]; then
            echo -e "${YELLOW}⚠️  大部分测试通过，请关注失败的测试${NC}"
        else
            echo -e "${RED}❌ 测试失败率较高，需要立即处理${NC}"
        fi
    else
        # 简化显示
        echo "📊 测试统计文件已生成: $STATS_FILE"
        echo "请使用支持 JSON 的工具查看详细信息"
    fi
    
    echo
}

# 显示使用说明
show_usage() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  analyze   分析测试报告并生成统计信息（默认）"
    echo "  show      显示统计摘要"
    echo "  help      显示此帮助信息"
    echo ""
    echo "功能:"
    echo "  - 从 mochawesome JSON 报告中提取测试统计信息"
    echo "  - 生成结构化的统计摘要文件"
    echo "  - 支持自动检测和解析最新的测试报告"
    echo "  - 兼容有/无 jq 工具的环境"
    echo ""
    echo "输出文件:"
    echo "  $STATS_FILE"
    echo ""
    echo "示例:"
    echo "  $0 analyze    # 分析并生成统计信息"
    echo "  $0 show       # 显示统计摘要"
}

# 主函数
main() {
    local action=${1:-"analyze"}
    
    echo "========================================"
    echo "  DC-TOM 测试统计分析工具"
    echo "========================================"
    echo
    
    case $action in
        "analyze")
            analyze_all_reports
            show_stats_summary
            ;;
        "show")
            show_stats_summary
            ;;
        "help"|"-h"|"--help")
            show_usage
            ;;
        *)
            log_error "未知操作: $action"
            show_usage
            exit 1
            ;;
    esac
}

# 运行主函数
main "$@"