name: Optimize PNG with Oxipng

on:
  push:
    branches: ["**"]

permissions:
  contents: write
  pull-requests: write

jobs:
  optimize-png:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Install oxipng
        run: cargo install oxipng

      - name: Install GitHub CLI
        run: sudo apt-get install -y gh

      - name: Check if PR is an Optimize PNG PR
        env:
          GH_PAT: ${{ secrets.GH_PAT }}
        run: |
          set -e
          export LANG=C.UTF-8
          gh auth login --with-token <<< "$GH_PAT"
          if [ "${{ github.event_name }}" = "pull_request" ]; then
            PR_TITLE=$(gh pr view ${{ github.event.pull_request.number }} --json title -q .title)
            echo "Current PR title: $PR_TITLE"
            if [[ "$PR_TITLE" == Optimize\ PNG* ]]; then
              echo "Skipping workflow for Optimize PNG PR."
              exit 0
            fi
          fi

      - name: Skip if latest commit is an Oxipng optimization
        run: |
          LAST_COMMIT_MSG=$(git log -1 --pretty=%B)
          echo "Last commit message: $LAST_COMMIT_MSG"
          if [[ "$LAST_COMMIT_MSG" == *oxipng-optimization* ]]; then
            echo "Latest commit is an oxipng-optimization commit, skipping workflow."
            exit 0
          fi

      - name: Prepare diff commits
        run: |
          EVENT_NAME="${{ github.event_name }}"
          if [ "$EVENT_NAME" = "pull_request" ]; then
            BASE_SHA="${{ github.event.pull_request.base.sha }}"
            HEAD_SHA="${{ github.event.pull_request.head.sha }}"
          else
            BASE_SHA="${{ github.event.before }}"
            HEAD_SHA="${{ github.sha }}"
          fi

          git fetch origin "$BASE_SHA" --depth=1 || true
          git fetch origin "$HEAD_SHA" --depth=1 || true

          echo "BASE_SHA=$BASE_SHA" >> $GITHUB_ENV
          echo "HEAD_SHA=$HEAD_SHA" >> $GITHUB_ENV

      - name: Optimize PNG files
        run: |
          export LANG=C.UTF-8
          echo "Base SHA: $BASE_SHA"
          echo "Head SHA: $HEAD_SHA"

          git diff --diff-filter=AMR --name-only -z "$BASE_SHA" "$HEAD_SHA" -- '*.png' > changed_pngs.txt || true

          if [ ! -s changed_pngs.txt ]; then
            echo "No PNG files changed."
            exit 0
          fi

          echo "Optimizing PNGs..."
          while IFS= read -r -d '' file; do
            if [ -f "$file" ]; then
              echo "Optimizing: $file"
              oxipng -o 6 --alpha "$file"
            else
              echo "File not found: $file"
            fi
          done < changed_pngs.txt

      - name: Commit changes to new branch
        run: |
          BRANCH_NAME="oxipng-optimization-${{ github.run_id }}"
          git checkout -b "$BRANCH_NAME"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

          if [ ! -s changed_pngs.txt ]; then
            echo "No PNG files to optimize, skipping."
            exit 0
          fi

          git add -A
          git restore --staged changed_pngs.txt 2>/dev/null || true
          rm -f changed_pngs.txt

          if git diff --cached --quiet; then
            echo "No changes found after optimization."
            exit 0
          fi

          git commit -m "Optimize PNG images with oxipng"
          git push origin "$BRANCH_NAME"

          echo "branch_name=$BRANCH_NAME" >> $GITHUB_ENV

      - name: Create Pull Request
        env:
          GH_PAT: ${{ secrets.GH_PAT }}
        run: |
          set -e
          export LANG=C.UTF-8
          gh auth login --with-token <<< "$GH_PAT"

          EVENT_NAME="${{ github.event_name }}"
          if [ "$EVENT_NAME" = "pull_request" ]; then
            TARGET_LABEL="PR #${{ github.event.pull_request.number }}"
            BASE_BRANCH="${{ github.event.pull_request.base.ref }}"
          else
            TARGET_LABEL="Commit ${{ github.sha }}"
            BASE_BRANCH="${{ github.ref_name }}"
          fi

          git fetch origin
          git checkout "${{ env.branch_name }}" || exit 1
          git push origin "${{ env.branch_name }}" || true

          gh pr create \
            --base "$BASE_BRANCH" \
            --head "${{ env.branch_name }}" \
            --title "Optimize PNG images for $TARGET_LABEL" \
            --body "**Optimized PNG images for $TARGET_LABEL**"
