name: Web Quality Schedule

on:
  schedule:
    # Run every Monday at 9 AM UTC
    - cron: '0 9 * * 1'
  workflow_dispatch:

jobs:
  scheduled-quality-check:
    name: Scheduled Web Quality Analysis
    runs-on: ubuntu-latest
    
    permissions:
      contents: write
      issues: write
      pull-requests: write
    
    steps:
      - name: 📥 Checkout Repository
        uses: actions/checkout@v4
      
      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20.x'
          cache: 'npm'
      
      - name: 📦 Install Dependencies
        run: npm ci
      
      - name: 🧪 Run Full Quality Suite
        continue-on-error: true
        run: |
          # Run all quality checks
          make quality-web || true
          
          # Generate detailed report
          ./scripts/web-quality-report.sh > quality-report.txt 2>&1 || true
      
      - name: 📊 Generate Coverage Badge
        if: always()
        run: |
          # Extract coverage percentage
          COVERAGE=$(cat coverage/coverage-summary.json 2>/dev/null | jq '.total.lines.pct' || echo "0")
          
          # Determine badge color
          if (( $(echo "$COVERAGE >= 80" | bc -l) )); then
            COLOR="brightgreen"
          elif (( $(echo "$COVERAGE >= 60" | bc -l) )); then
            COLOR="yellow"
          else
            COLOR="red"
          fi
          
          # Create badge JSON
          echo "{\"schemaVersion\": 1, \"label\": \"web coverage\", \"message\": \"${COVERAGE}%\", \"color\": \"${COLOR}\"}" > web-coverage-badge.json
      
      - name: 📈 Update Coverage History
        if: always()
        run: |
          # Create coverage history file if it doesn't exist
          if [ ! -f .github/coverage-history.json ]; then
            echo "[]" > .github/coverage-history.json
          fi
          
          # Add current coverage to history
          COVERAGE=$(cat coverage/coverage-summary.json 2>/dev/null | jq '.total.lines.pct' || echo "0")
          DATE=$(date -u +"%Y-%m-%d")
          
          jq ". += [{\"date\": \"$DATE\", \"coverage\": $COVERAGE}]" .github/coverage-history.json > temp.json
          mv temp.json .github/coverage-history.json
          
          # Keep only last 52 weeks of data
          jq '.[(-52):]' .github/coverage-history.json > temp.json
          mv temp.json .github/coverage-history.json
      
      - name: 📝 Create Issue if Quality Degraded
        if: failure()
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const date = new Date().toISOString().split('T')[0];
            const title = `Web Quality Alert - ${date}`;
            
            // Check if issue already exists
            const issues = await github.rest.issues.listForRepo({
              owner: context.repo.owner,
              repo: context.repo.repo,
              labels: ['web-quality', 'automated'],
              state: 'open'
            });
            
            const existingIssue = issues.data.find(issue => issue.title === title);
            
            if (!existingIssue) {
              await github.rest.issues.create({
                owner: context.repo.owner,
                repo: context.repo.repo,
                title: title,
                body: `## 🚨 Web Quality Check Failed
                
                The scheduled web quality check has detected issues that need attention.
                
                ### Failed Checks:
                - [ ] Coverage below 80% threshold
                - [ ] Linting errors detected
                - [ ] Accessibility issues found
                
                ### Actions Required:
                1. Run \`make quality-web\` locally to reproduce
                2. Fix identified issues
                3. Ensure coverage meets 80% threshold
                4. Close this issue once resolved
                
                [View Workflow Run](${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId})`,
                labels: ['web-quality', 'automated', 'maintenance']
              });
            }
      
      - name: 💾 Commit Coverage Updates
        if: always()
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          
          # Add coverage history if changed
          if [ -f .github/coverage-history.json ]; then
            git add .github/coverage-history.json
          fi
          
          # Add badge if changed
          if [ -f web-coverage-badge.json ]; then
            git add web-coverage-badge.json
          fi
          
          # Commit if there are changes
          if git diff --staged --quiet; then
            echo "No changes to commit"
          else
            git commit -m "chore: update web coverage metrics [skip ci]"
            git push
          fi