name: CI Health Daily Report
on:
  schedule:
    - cron: '0 1 * * *'  # UTC 01:00 = 北京时间 09:00
  workflow_dispatch:
permissions:
  contents: read
jobs:
  ci-health-report:
    name: CI健康度每日巡检
    runs-on: ci-l2
    timeout-minutes: 15
    steps:
    - name: Checkout code
      shell: sh
      env:
        GITHUB_TOKEN: ${{ github.token }}
      run: |
        set -eu
        python3 - <<'PY'
        import io, os, tarfile, time, urllib.request, urllib.error
        url = f"{os.environ['GITHUB_API_URL']}/repos/{os.environ['GITHUB_REPOSITORY']}/archive/{os.environ['GITHUB_SHA']}.tar.gz"
        request = urllib.request.Request(url, headers={"Authorization": f"token {os.environ['GITHUB_TOKEN']}"})
        last_err = None
        for attempt in range(5):
            try:
                with urllib.request.urlopen(request, timeout=120) as response:
                    archive = response.read()
                break
            except urllib.error.HTTPError as e:
                last_err = e
                if e.code >= 500 and attempt < 4:
                    wait = 2 ** attempt
                    print(f"Checkout HTTP {e.code}, retrying in {wait}s (attempt {attempt+1}/5)...")
                    time.sleep(wait)
                    continue
                raise
            except Exception as e:
                last_err = e
                if attempt < 4:
                    wait = 2 ** attempt
                    print(f"Checkout error: {e}, retrying in {wait}s (attempt {attempt+1}/5)...")
                    time.sleep(wait)
                    continue
                raise
        else:
            raise last_err
        with tarfile.open(fileobj=io.BytesIO(archive), mode='r:gz') as tar:
            root_prefix = tar.getmembers()[0].name.split('/', 1)[0] + '/'
            for member in tar.getmembers():
                name = member.name
                if name == root_prefix[:-1]:
                    continue
                if name.startswith(root_prefix):
                    member.name = name[len(root_prefix):]
                if member.name:
                    tar.extract(member, '.')
        PY

    - name: Generate CI Dashboard HTML
      shell: sh
      env:
        GITEA_TOKEN: ${{ github.token }}
      run: |
        set +e
        echo "=== 生成 CI 健康度 HTML 看板 ==="
        echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
        echo ""
        python3 scripts/ci/ci_dashboard.py --days 7 --html --html-output ci_dashboard.html
        EXIT_CODE=$?
        if [ $EXIT_CODE -eq 0 ] && [ -f ci_dashboard.html ]; then
            HTML_SIZE=$(wc -c < ci_dashboard.html)
            echo ""
            echo "✅ HTML 看板生成成功 (${HTML_SIZE} bytes)"
            echo "路径: $(pwd)/ci_dashboard.html"
            # 输出文件内容前几行，方便在 Actions 日志中确认
            echo ""
            echo "--- 看板预览 (前 5 行) ---"
            head -5 ci_dashboard.html
            echo "...（完整内容见产物文件）"
        else
            echo "❌ HTML 看板生成失败 (exit code: $EXIT_CODE)"
        fi
        echo ""
        # 永远成功，看板生成失败不影响主流程
        exit 0

    - name: Run CI health check and report
      shell: sh
      env:
        GITEA_TOKEN: ${{ github.token }}
        CI_NOTIFY_WEBHOOK: ${{ secrets.CI_NOTIFY_WEBHOOK }}
      run: |
        set +e
        echo "=== CI健康度每日巡检 ==="
        echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
        echo ""
        python3 scripts/ci/ci_health_report.py --limit 30
        EXIT_CODE=$?
        echo ""
        echo "巡检完成 (exit code: $EXIT_CODE)"
        # 永远成功，不影响CI状态（通知失败不应该标红）
        exit 0
