name: 🟩 DurovFlow CI/CD

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
  schedule:
    # Run health check daily at 9 AM UTC
    - cron: '0 9 * * *'

jobs:
  # ─────────────────────────────────────────────────────────
  # 🏥 Health Check Job
  # ─────────────────────────────────────────────────────────
  health-check:
    name: Health Check
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v3

      - name: 🏥 Run health check script
        run: |
          chmod +x health-check-durovflow.sh
          ./health-check-durovflow.sh
          
      - name: 📊 Upload health report
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: health-report
          path: durovflow-reports/*.txt
          retention-days: 30

  # ─────────────────────────────────────────────────────────
  # 🧪 Automated Tests Job
  # ─────────────────────────────────────────────────────────
  test:
    name: Run Tests
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v3

      - name: 🔧 Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'

      - name: 🧪 Validate HTML files
        run: |
          npm install -g html-validator-cli
          html-validator --file=durovflow.html || true
          html-validator --file=durovflow-v2.html || true
          html-validator --file=durovflow-v3.html || true
          
      - name: 📝 Check JavaScript syntax
        run: |
          npm install -g eslint
          # Extract and validate JS from HTML files
          grep -oP '(?<=<script>).*?(?=</script>)' durovflow-v3.html > temp.js || true
          node -c temp.js || echo "JS syntax check skipped"

      - name: ✅ Validate JSON files
        run: |
          python3 -m json.tool durovflow-manifest.json > /dev/null
          echo "✓ durovflow-manifest.json is valid"

  # ─────────────────────────────────────────────────────────
  # 📦 Build & Deploy Job
  # ─────────────────────────────────────────────────────────
  deploy:
    name: Deploy to GitHub Pages
    runs-on: ubuntu-latest
    needs: [health-check, test]
    if: github.ref == 'refs/heads/main'
    
    permissions:
      contents: write
      pages: write
      id-token: write
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v3

      - name: 📂 Setup deployment directory
        run: |
          mkdir -p deploy
          cp durovflow*.html deploy/
          cp durovflow*.json deploy/
          cp durovflow*.js deploy/
          cp *.md deploy/
          cp LICENSE* deploy/
          
      - name: 🚀 Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./deploy
          publish_branch: gh-pages
          user_name: 'github-actions[bot]'
          user_email: 'github-actions[bot]@users.noreply.github.com'
          commit_message: '🚀 Deploy DurovFlow ${{ github.sha }}'

  # ─────────────────────────────────────────────────────────
  # 💾 Backup Job
  # ─────────────────────────────────────────────────────────
  backup:
    name: Create Backup
    runs-on: ubuntu-latest
    if: github.event_name == 'schedule'
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v3

      - name: 💾 Create backup archive
        run: |
          mkdir -p durovflow-backups
          timestamp=$(date +%Y%m%d_%H%M%S)
          tar -czf durovflow-backups/durovflow_backup_$timestamp.tar.gz \
            durovflow*.html \
            durovflow*.json \
            durovflow*.js \
            *.md \
            LICENSE* \
            *.sh
            
      - name: 📤 Upload backup artifact
        uses: actions/upload-artifact@v3
        with:
          name: daily-backup
          path: durovflow-backups/*.tar.gz
          retention-days: 90

  # ─────────────────────────────────────────────────────────
  # 📊 Stats & Metrics Job
  # ─────────────────────────────────────────────────────────
  stats:
    name: Generate Stats
    runs-on: ubuntu-latest
    
    steps:
      - name: 📥 Checkout code
        uses: actions/checkout@v3

      - name: 📊 Calculate project stats
        run: |
          echo "═══════════════════════════════════════"
          echo "🟩 DurovFlow Project Statistics"
          echo "═══════════════════════════════════════"
          echo ""
          echo "📦 Total Files:"
          find . -type f -name "durovflow*" -o -name "*.md" | wc -l
          echo ""
          echo "📝 Total Lines of Code:"
          find . -type f \( -name "*.html" -o -name "*.js" -o -name "*.sh" \) -exec wc -l {} + | tail -1
          echo ""
          echo "💾 Total Size:"
          du -sh .
          echo ""
          echo "═══════════════════════════════════════"

      - name: 📝 Create stats report
        run: |
          mkdir -p durovflow-reports
          cat > durovflow-reports/stats-report.txt <<EOF
          DurovFlow Project Statistics
          Generated: $(date)
          
          Files: $(find . -type f -name "durovflow*" -o -name "*.md" | wc -l)
          Lines: $(find . -type f \( -name "*.html" -o -name "*.js" -o -name "*.sh" \) -exec wc -l {} + | tail -1 | awk '{print $1}')
          Size: $(du -sh . | awk '{print $1}')
          
          Latest Commit: ${{ github.sha }}
          Branch: ${{ github.ref }}
          EOF
          
      - name: 📤 Upload stats report
        uses: actions/upload-artifact@v3
        with:
          name: stats-report
          path: durovflow-reports/stats-report.txt
          retention-days: 30
