#!/bin/bash
# 🔍 Testing-Autonomous 实时监控脚本
# 用法: ./monitor.sh [project_path]

PROJECT_PATH=${1:-.}
LOG_FILE="$PROJECT_PATH/.testing-autonomous/progress.log"
COVERAGE_FILE="$PROJECT_PATH/target/site/jacoco/index.html"

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

echo -e "${BLUE}🔍 Testing-Autonomous 实时监控${NC}"
echo "=================================="
echo "项目路径: $PROJECT_PATH"
echo "=================================="
echo ""

# 检查配置文件
if [ -f "$PROJECT_PATH/.testing-autonomous/config.yml" ]; then
    echo -e "${GREEN}✅ 配置文件存在${NC}"
    TARGET_COVERAGE=$(grep "instruction:" "$PROJECT_PATH/.testing-autonomous/config.yml" | head -1 | awk '{print $2}' | tr -d '%')
    echo "🎯 目标覆盖率: ${TARGET_COVERAGE}%"
else
    echo -e "${YELLOW}⚠️  配置文件不存在，使用默认配置${NC}"
    TARGET_COVERAGE=85
fi

echo ""

# 实时监控函数
monitor_progress() {
    local last_coverage=0
    local round=0
    
    while true; do
        clear
        echo -e "${BLUE}🔍 Testing-Autonomous 实时监控${NC}"
        echo "=================================="
        echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
        echo "=================================="
        echo ""
        
        # 显示进度日志（最近20行）
        if [ -f "$LOG_FILE" ]; then
            echo -e "${BLUE}📊 最新进展:${NC}"
            tail -20 "$LOG_FILE" 2>/dev/null | while read line; do
                if [[ $line == *"ERROR"* ]] || [[ $line == *"失败"* ]]; then
                    echo -e "${RED}$line${NC}"
                elif [[ $line == *"SUCCESS"* ]] || [[ $line == *"成功"* ]]; then
                    echo -e "${GREEN}$line${NC}"
                elif [[ $line == *"WARNING"* ]] || [[ $line == *"警告"* ]]; then
                    echo -e "${YELLOW}$line${NC}"
                else
                    echo "$line"
                fi
            done
            echo ""
        fi
        
        # 解析当前覆盖率
        if [ -f "$COVERAGE_FILE" ]; then
            # 从JaCoCo报告中提取覆盖率
            COVERAGE=$(grep -o 'ctr2>[0-9]*%' "$COVERAGE_FILE" | head -1 | grep -o '[0-9]*')
            if [ ! -z "$COVERAGE" ]; then
                echo -e "${BLUE}📈 覆盖率状态:${NC}"
                echo "当前: ${COVERAGE}%"
                echo "目标: ${TARGET_COVERAGE}%"
                
                # 计算进度条
                PROGRESS=$((COVERAGE * 50 / 100))  # 50字符宽度的进度条
                BAR=$(printf '%*s' "$PROGRESS" | tr ' ' '█')
                REMAINING=$((50 - PROGRESS))
                EMPTY=$(printf '%*s' "$REMAINING" | tr ' ' '░')
                
                if [ $COVERAGE -ge $TARGET_COVERAGE ]; then
                    echo -e "${GREEN}进度: [${BAR}${EMPTY}] ${COVERAGE}% ✅ 已达标${NC}"
                else
                    echo -e "${YELLOW}进度: [${BAR}${EMPTY}] ${COVERAGE}% 🔄 继续优化${NC}"
                fi
                echo ""
                
                # 显示差距
                GAP=$((TARGET_COVERAGE - COVERAGE))
                if [ $GAP -gt 0 ]; then
                    echo -e "${YELLOW}还需提升: ${GAP}%${NC}"
                fi
            fi
        fi
        
        # 检查测试执行状态
        if [ -f "$PROJECT_PATH/target/surefire-reports" ]; then
            TEST_COUNT=$(find "$PROJECT_PATH/target/surefire-reports" -name "*.txt" | wc -l)
            echo -e "${BLUE}🧪 测试统计:${NC}"
            echo "测试文件: $TEST_COUNT 个"
            
            # 统计失败/错误
            FAILURES=$(grep -l "FAILURE\|ERROR" "$PROJECT_PATH/target/surefire-reports"/*.txt 2>/dev/null | wc -l)
            if [ $FAILURES -gt 0 ]; then
                echo -e "${RED}❌ 失败: $FAILURES${NC}"
            else
                echo -e "${GREEN}✅ 全部通过${NC}"
            fi
            echo ""
        fi
        
        # 检查是否有卡住迹象
        if [ -f "$LOG_FILE" ]; then
            LAST_UPDATE=$(stat -c %Y "$LOG_FILE" 2>/dev/null || stat -f %m "$LOG_FILE" 2>/dev/null)
            CURRENT_TIME=$(date +%s)
            TIME_DIFF=$((CURRENT_TIME - LAST_UPDATE))
            
            if [ $TIME_DIFF -gt 300 ]; then  # 5分钟无更新
                echo -e "${RED}⚠️  警告: 已超过5分钟无进展，可能卡住${NC}"
                echo -e "${YELLOW}   自动恢复机制应该已经启动...${NC}"
            fi
        fi
        
        echo ""
        echo -e "${BLUE}==================================${NC}"
        echo "按 Ctrl+C 退出监控"
        echo -e "${BLUE}==================================${NC}"
        
        # 每5秒刷新一次
        sleep 5
    done
}

# 快速统计模式
quick_stats() {
    echo -e "${BLUE}📊 快速统计${NC}"
    echo "=================================="
    
    # 测试数量
    if [ -d "$PROJECT_PATH/src/test/java" ]; then
        TEST_FILES=$(find "$PROJECT_PATH/src/test/java" -name "*Test.java" | wc -l)
        echo -e "测试文件: ${GREEN}$TEST_FILES${NC} 个"
    fi
    
    # 覆盖率
    if [ -f "$COVERAGE_FILE" ]; then
        COVERAGE=$(grep -o 'ctr2>[0-9]*%' "$COVERAGE_FILE" | head -1 | grep -o '[0-9]*')
        if [ ! -z "$COVERAGE" ]; then
            if [ $COVERAGE -ge $TARGET_COVERAGE ]; then
                echo -e "覆盖率: ${GREEN}${COVERAGE}% ✅${NC}"
            else
                echo -e "覆盖率: ${YELLOW}${COVERAGE}% 🔄${NC} (目标: ${TARGET_COVERAGE}%)"
            fi
        fi
    fi
    
    # 配置文件状态
    if [ -f "$PROJECT_PATH/.testing-autonomous/config.yml" ]; then
        echo -e "配置: ${GREEN}✅ 已配置${NC}"
    else
        echo -e "配置: ${RED}❌ 未配置${NC}"
    fi
    
    echo "=================================="
}

# 主逻辑
case "${2:-monitor}" in
    monitor)
        monitor_progress
        ;;
    stats)
        quick_stats
        ;;
    *)
        echo "用法: $0 [project_path] [monitor|stats]"
        echo ""
        echo "示例:"
        echo "  $0 . monitor     # 实时监控当前项目"
        echo "  $0 . stats       # 快速统计"
        echo "  $0 /path/to/project monitor  # 监控指定项目"
        exit 1
        ;;
esac