name: Deploy to GitHub Pages

on:
  push:
    branches:
      - main
  workflow_dispatch:
  schedule:
    - cron: '0 */6 * * *'  # Run every 6 hours

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  validate:
    uses: ./.github/workflows/test.yml

  build:
    runs-on: ubuntu-latest
    needs: validate
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Setup Pages
        uses: actions/configure-pages@v5
      
      - name: Install uv with caching
        uses: astral-sh/setup-uv@v5
        with:
          enable-cache: true
          cache-dependency-glob: "pyproject.toml"

      - name: Install dependencies
        run: |
          uv sync --group dev
          
      - name: Setup site structure
        run: |
          mkdir -p pages/registry
          mkdir -p pages/api/servers
          
      - name: Run preparation script
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          chmod +x ./scripts/prepare.sh
          source .venv/bin/activate
          ./scripts/prepare.sh ./pages
        
      
      - name: Build with Jekyll
        uses: actions/jekyll-build-pages@v1
        with:
          source: ./pages
          destination: ./_site
      
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3

  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

  deploy-cloudflare:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        
      - name: Download artifact
        uses: actions/download-artifact@v4
        with:
          name: github-pages
          path: ./dist
      
      - name: Extract artifact
        run: |
          tar -xf ./dist/artifact.tar -C ./dist
          rm ./dist/artifact.tar
      
      - name: Deploy to Cloudflare Pages
        uses: cloudflare/pages-action@v1
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
          projectName: mcpm-sh
          directory: ./dist
