#!/bin/bash
# 检查最近 CI 运行状态，失败时输出告警
GITEA_API="https://git.xiaoxiajianji.com/api/v1"
TOKEN="${GITEA_API_TOKEN:?Please set GITEA_API_TOKEN environment variable}"
REPO="xiaoxia/xiaoxia-saas"

echo "=== CI Status Check ==="
echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"

# 检查最近的 workflow runs
curl -s -H "Authorization: token $TOKEN" \
  "$GITEA_API/repos/$REPO/actions/runs?limit=5" 2>/dev/null | python3 -c "
import json, sys
try:
    data = json.load(sys.stdin)
    runs = data.get('workflow_runs', [])
    if not runs:
        print('No recent CI runs found')
        sys.exit(0)
    for run in runs[:5]:
        status = run.get('status', 'unknown')
        conclusion = run.get('conclusion', 'pending')
        name = run.get('name', 'unknown')
        created = run.get('created_at', '')
        print(f'  {name}: {status} ({conclusion}) - {created}')
        if conclusion == 'failure':
            print(f'  ⚠️ WARNING: CI failed for {name}')
except:
    print('Could not parse CI status')
" 2>/dev/null || echo "CI status check unavailable"
