# =============================================================================
# Deploy Prometheus Alert Rules (獨立 workflow)
# 2026-04-05 Claude Code (ADR-039 I3): 從 cd.yaml 分離
# 觸發條件: ops/monitoring/alerts-unified.yml 有變更 或 workflow_dispatch
# 說明: 告警規則部署不依賴應用構建，獨立觸發以加快響應速度
# =============================================================================

name: Deploy Alert Rules

on:
  push:
    branches: [main]
    paths:
      - 'ops/monitoring/alerts-unified.yml'
  workflow_dispatch:

jobs:
  deploy-alerts:
    name: "Deploy Prometheus Alert Rules"
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v4

      - name: Validate alerts YAML
        # 2026-04-08 Claude Sonnet 4.6: pip install pyyaml 確保 runner 有此依賴
        run: |
          pip3 install -q pyyaml 2>/dev/null || pip install -q pyyaml
          python3 -c "import yaml; yaml.safe_load(open('ops/monitoring/alerts-unified.yml')); print('YAML OK')"

      - name: Setup SSH key
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan 192.168.0.110 >> ~/.ssh/known_hosts

      - name: Deploy alerts to Prometheus
        run: bash scripts/ops/deploy-alerts.sh

      - name: Notify deploy result
        if: always()
        run: |
          STATUS="${{ job.status }}"
          EMOJI="✅"
          [ "$STATUS" != "success" ] && EMOJI="❌"
          SHORT_SHA="${{ github.sha }}"
          SHORT_SHA="${SHORT_SHA:0:7}"
          MSG="${EMOJI} Prometheus 告警規則部署 ${STATUS} (${SHORT_SHA})"
          curl -fS -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
            -d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
            --data-urlencode "text=${MSG}" || true
