# Copy this file to `.github/workflows/gallery-snapshot.yml` in the GitHub repo
# that will hold the snapshots. Add repository secrets CLOUDFLARE_API_TOKEN
# (D1 read permission) and optionally CLOUDFLARE_ACCOUNT_ID.
name: Gallery snapshot

on:
  schedule:
    # 00:20 UTC, after the D1 daily quota reset and the 00:05 cache rebuild.
    - cron: "20 0 * * *"
  workflow_dispatch:

permissions:
  contents: write

jobs:
  export:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - uses: actions/setup-python@v5
        with:
          python-version: "3.11"

      - name: Export D1
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
        run: npx wrangler d1 export pixify-db --remote --output pixify-db.sql

      - name: Build JSON snapshots
        run: python scripts/export_github_snapshot.py --dump pixify-db.sql --out data

      - name: Commit snapshots
        run: |
          git config user.name "pixify-snapshot-bot"
          git config user.email "pixify-snapshot-bot@users.noreply.github.com"
          git add data/gallery.json data/collections.json data/media-index.json
          if git diff --cached --quiet; then
            echo "No snapshot changes"
          else
            git commit -m "chore: refresh gallery snapshot ${{ github.run_number }}"
            git push
          fi
