#!/bin/bash
# post-deploy-check.sh — 部署后验证：K 测试无意外失败才算部署完成
#
# 用法: bash deploy/linux/post-deploy-check.sh
# 依赖: sync-venv.sh 先执行完毕, dashboard 已在运行
#
# 退出码:
#   0 = 验证通过（所有失败项均为 expected）
#   1 = 发现意外失败（需回滚或手动处理）

set -e

DASHBOARD_URL="http://127.0.0.1:5803"
TIMEOUT=10

echo "=== post-deploy-check: $(date) ==="

# 1. 等待 dashboard 就绪
echo "--- 等待 dashboard 就绪 ---"
for i in $(seq 1 6); do
    if curl -s -o /dev/null -w "" --max-time 3 "$DASHBOARD_URL/" 2>/dev/null; then
        echo "dashboard 已就绪 (尝试 $i)"
        break
    fi
    if [ "$i" -eq 6 ]; then
        echo "ERROR: dashboard 未能启动"
        exit 1
    fi
    sleep 2
done

# 2. 获取 K 测试结果
echo "--- 获取 K 测试结果 ---"
TESTS_JSON=$(curl -s --max-time "$TIMEOUT" "$DASHBOARD_URL/api/tests" 2>/dev/null)

if [ -z "$TESTS_JSON" ]; then
    echo "ERROR: /api/tests 无响应"
    exit 1
fi

# 3. 解析并验证
# 使用 python3 解析 JSON，提取未预期的失败
REPORT=$(python3 -c "
import json, sys

data = json.loads('$TESTS_JSON')
if not isinstance(data, dict):
    # 可能是列表格式
    tests = data if isinstance(data, list) else []
    summary = {}
else:
    tests = data.get('tests', [])
    summary = data.get('summary', {})

total = len(tests)
passed = sum(1 for t in tests if t.get('ok'))
failed = [t for t in tests if not t.get('ok')]
expected = [t for t in failed if t.get('expected')]
unexpected = [t for t in failed if not t.get('expected')]

print(f'TOTAL: {total}')
print(f'PASS:  {passed}')
print(f'FAIL:  {len(failed)} (expected: {len(expected)}, UNEXPECTED: {len(unexpected)})')
print('---')
for t in unexpected:
    print(f'UNEXPECTED_FAIL: {t.get(\"name\",\"?\")} | {t.get(\"detail\",\"\")}')
for t in expected:
    print(f'EXPECTED_FAIL:   {t.get(\"name\",\"?\")} | {t.get(\"detail\",\"\")}')

sys.exit(1 if unexpected else 0)
")

echo "$REPORT"

# 提取退出码
EXIT_CODE=$?
if [ "$EXIT_CODE" -ne 0 ]; then
    echo ""
    echo "!!! 部署后验证失败：发现意外失败的测试项 !!!"
    echo "运行以下命令查看详情："
    echo "  curl -s $DASHBOARD_URL/api/tests | python3 -m json.tool"
    exit 1
fi

echo ""
echo "=== post-deploy-check: 验证通过 ==="
exit 0
