name: 🔧 Self-Healing

on:
  schedule:
    - cron: '*/30 * * * *'  # Every 30 minutes
  workflow_dispatch:
  workflow_run:
    workflows: ["🚀 Auto Deploy"]
    types: [completed]

jobs:
  monitor:
    name: Monitor Deployments
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout
        uses: actions/checkout@v6
      
      - name: Check Health
        id: health
        run: |
          if [ ! -z "${{ secrets.DEPLOY_URL }}" ]; then
            STATUS=$(curl -s -o /dev/null -w "%{http_code}" ${{ secrets.DEPLOY_URL }}/api/health || echo "000")
            echo "status=$STATUS" >> $GITHUB_OUTPUT
          else
            echo "status=skip" >> $GITHUB_OUTPUT
          fi
      
      - name: Auto-Rollback
        if: steps.health.outputs.status != '200' && steps.health.outputs.status != 'skip'
        run: |
          echo "🚨 Health check failed (Status: ${{ steps.health.outputs.status }})"
          echo "Triggering rollback..."
          gh workflow run auto-deploy.yml --ref $(git rev-parse HEAD~1)
        env:
          GH_TOKEN: ${{ github.token }}
      
      - name: Attempt Auto-Fix
        if: steps.health.outputs.status != '200' && steps.health.outputs.status != 'skip'
        run: |
          echo "🔧 Attempting automatic fixes..."
          # Check for common issues
          if [ -f "package.json" ]; then
            npm ci || true
            npm run build || true
          fi
      
      - name: Create Issue on Failure
        if: failure()
        uses: actions/github-script@v8
        with:
          script: |
            github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: '🚨 Self-Healing: Deployment Health Check Failed',
              body: `Deployment health check failed.\n\nStatus: ${{ steps.health.outputs.status }}\nWorkflow: ${context.workflow}\nRun: ${context.runId}`,
              labels: ['bug', 'deployment', 'auto-generated']
            })

  dependency-updates:
    name: Auto Update Dependencies
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout
        uses: actions/checkout@v6
      
      - name: Setup Node
        if: hashFiles('package.json') != ''
        uses: actions/setup-node@v6
        with:
          node-version: '20'
      
      - name: Update npm dependencies
        if: hashFiles('package.json') != ''
        run: |
          npm update
          if [ -n "$(git status --porcelain)" ]; then
            git config user.name "BlackRoad Bot"
            git config user.email "bot@blackroad.io"
            git add package*.json
            git commit -m "chore: auto-update dependencies"
            git push
          fi
