#!/bin/bash

# Stock Tool - 健康检查脚本 (PERDAS 增强版)
# 用途：验证开发环境是否正常工作

set -e

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

# 统计变量
PASSED=0
FAILED=0

# 打印函数
print_header() {
    echo -e "\n${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}\n"
}

print_pass() {
    echo -e "${GREEN}✅ $1${NC}"
    ((PASSED++))
}

print_fail() {
    echo -e "${RED}❌ $1${NC}"
    ((FAILED++))
}

print_info() {
    echo -e "${YELLOW}ℹ️  $1${NC}"
}

print_section() {
    echo -e "\n${BLUE}─ $1${NC}\n"
}

# 检查 1: 检查项目文件
print_header "1️⃣ 检查项目文件"

files=(
    "stock-tool-simple"
    "main_simple.go"
    "templates/index.html"
    "feature_list.json"
    "PROGRESS.md"
    "init.sh"
)

for file in "${files[@]}"; do
    if [ -f "$file" ]; then
        print_pass "文件存在: $file"
    else
        print_fail "文件缺失: $file"
    fi
done

# 检查 2: 检查 Go 编译
print_section "2️⃣ 检查 Go 编译"

if command -v go &> /dev/null; then
    print_pass "Go 已安装: $(go version)"
else
    print_fail "Go 未安装"
fi

if [ -f "stock-tool-simple" ]; then
    print_pass "stock-tool-simple 可执行"
    print_info "文件大小: $(du -h stock-tool-simple | cut -f1)"
else
    print_fail "stock-tool-simple 未编译"
fi

# 检查 3: 检查数据库
print_section "3️⃣ 检查数据库"

if [ -f "stock.db" ]; then
    print_pass "数据库文件存在: stock.db"
    
    # 检查数据库表
    tables=$(sqlite3 stock.db ".tables" 2>/dev/null | wc -l)
    if [ "$tables" -ge 4 ]; then
        print_pass "数据库表完整 ($tables 个表)"
    else
        print_fail "数据库表不完整 (仅 $tables 个表)"
    fi
    
    # 检查股票数据
    stock_count=$(sqlite3 stock.db "SELECT COUNT(*) FROM stocks;" 2>/dev/null)
    if [ "$stock_count" -gt 0 ]; then
        print_pass "股票数据: $stock_count 条记录"
    else
        print_info "数据库为空，需要运行 init_data.sh"
    fi
else
    print_fail "数据库文件不存在"
fi

# 检查 4: 检查服务器运行
print_section "4️⃣ 检查服务器运行"

if pgrep -f "stock-tool-simple" > /dev/null; then
    print_pass "服务器正在运行"
    SERVER_PID=$(pgrep -f "stock-tool-simple")
    print_info "服务器 PID: $SERVER_PID"
    
    # 检查端口监听
    if netstat -tuln 2>/dev/null | grep -q ":8080 "; then
        print_pass "端口 8080 正常监听"
    elif ss -tuln 2>/dev/null | grep -q ":8080 "; then
        print_pass "端口 8080 正常监听"
    else
        print_fail "端口 8080 未监听"
    fi
    
    # 检查服务器日志
    if [ -f "logs/server.log" ]; then
        print_pass "服务器日志存在: logs/server.log"
        tail_log=$(tail -5 logs/server.log 2>/dev/null | grep -i "启动\|started" | head -1)
        if [ -n "$tail_log" ]; then
            print_info "最新日志: $tail_log"
        fi
    else
        print_info "日志文件不存在"
    fi
else
    print_fail "服务器未运行"
    print_info "运行 ./init.sh 启动服务器"
fi

# 检查 5: 检查 Web 界面
print_section "5️⃣ 检查 Web 界面"

if pgrep -f "stock-tool-simple" > /dev/null; then
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8080/ 2>/dev/null)
    if [ "$HTTP_CODE" = "200" ]; then
        print_pass "Web 界面响应正常 (HTTP $HTTP_CODE)"
        
        # 检查 HTML 内容
        if curl -s http://localhost:8080/ | grep -q "股票数据分析工具"; then
            print_pass "HTML 内容正确"
        else
            print_fail "HTML 内容异常"
        fi
    else
        print_fail "Web 界面无响应 (HTTP $HTTP_CODE)"
    fi
else
    print_fail "服务器未运行，无法检查 Web 界面"
fi

# 检查 6: 检查功能清单
print_section "6️⃣ 检查功能清单"

if [ -f "feature_list.json" ]; then
    print_pass "feature_list.json 存在"
    
    total=$(jq '.summary.total' feature_list.json 2>/dev/null)
    completed=$(jq '.summary.completed' feature_list.json 2>/dev/null)
    
    print_info "功能进度: $completed/$total"
    
    # 检查格式
    if jq empty feature_list.json 2>/dev/null; then
        print_pass "JSON 格式正确"
    else
        print_fail "JSON 格式错误"
    fi
else
    print_fail "feature_list.json 不存在"
fi

# 检查 7: 检查 Git 仓库
print_section "7️⃣ 检查 Git 仓库"

if git rev-parse --git-dir > /dev/null 2>&1; then
    print_pass "Git 仓库存在"
    
    commits=$(git log --oneline -1 2>/dev/null | wc -l)
    print_info "提交数: $commits"
    
    branch=$(git branch --show-current 2>/dev/null)
    print_info "当前分支: $branch"
else
    print_fail "不是 Git 仓库"
fi

# 检查 8: 检查测试截图目录
print_section "8️⃣ 检查测试截图目录"

mkdir -p tests/screenshots

if [ -d "tests/screenshots" ]; then
    print_pass "测试截图目录存在"
    
    screenshot_count=$(find tests/screenshots -type f 2>/dev/null | wc -l)
    print_info "已保存截图: $screenshot_count 张"
else
    print_fail "测试截图目录不存在"
fi

# 检查 9: 检查 Progres 文件
print_section "9️⃣ 检查进度文件"

if [ -f "PROGRESS.md" ]; then
    print_pass "PROGRESS.md 存在"
    print_info "最后更新: $(grep '最后更新' PROGRESS.md | tail -1 | cut -d: -f2- | xargs)"
else
    print_fail "PROGRESS.md 不存在"
fi

# 检查 10: 检查脚本权限
print_section "🔟 检查脚本权限"

scripts=("init.sh" "install.sh" "init_data.sh")
for script in "${scripts[@]}"; do
    if [ -f "$script" ]; then
        if [ -x "$script" ]; then
            print_pass "脚本可执行: $script"
        else
            print_fail "脚本不可执行: $script"
        fi
    else
        print_fail "脚本不存在: $script"
    fi
done

# 打印总结
print_header "📊 健康检查总结"

echo "通过: ${GREEN}$PASSED${NC}"
echo "失败: ${RED}$FAILED${NC}"
echo "总计: $((PASSED + FAILED))"

# 计算通过率
if [ $((PASSED + FAILED)) -gt 0 ]; then
    pass_rate=$((PASSED * 100 / (PASSED + FAILED)))
    echo -e "通过率: ${PASS_RATE}%"
fi

echo ""

# 判断是否需要修复
if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✨ 所有检查通过！开发环境正常。${NC}"
    echo ""
    echo "💡 下一步:"
    echo "   1. 访问 http://localhost:8080 测试 Web 界面"
    echo "   2. 查看 feature_list.json 了解功能清单"
    echo "   3. 开始开发下一个功能"
    echo ""
    exit 0
else
    echo -e "${YELLOW}⚠️  发现 $FAILED 个问题，请修复后再继续开发${NC}"
    echo ""
    echo "🔧 修复建议:"
    echo "   1. 运行 ./init.sh 启动服务器"
    echo "   2. 运行 ./install.sh 安装依赖"
    echo "   3. 运行 ./init_data.sh 初始化数据"
    echo "   4. 检查 logs/server.log 查看错误日志"
    echo ""
    exit 1
fi
