name: Enforce Image Standards

on:
  pull_request:
    branches:
      - main
      - beta
      - testing
      - client
      - staging
      - production
    types: [opened, synchronize, reopened]
    paths:
      - '**/*.jpg'
      - '**/*.jpeg'
      - '**/*.png'

  workflow_dispatch:
    inputs:
      target_branch:
        description: "Branch to optimize images on"
        required: false
        default: "main"

jobs:
  optimize:
    runs-on: ubuntu-latest

    # 🚀 Use your internal image (no apt needed)
    container:
      image: git.wdipl.com/wdi-public/image-optimizer:latest
      #credentials:
        #username: ${{ secrets.REGISTRY_USER }}
        #password: ${{ secrets.REGISTRY_PASSWORD }}

    steps:
      # 🔀 Decide branch (PR vs manual)
      - name: Determine Branch
        id: branch
        run: |
          if [ "${{ gitea.event_name }}" = "pull_request" ]; then
            echo "branch=${{ gitea.head_ref }}" >> $GITHUB_OUTPUT
          else
            echo "branch=${{ inputs.target_branch }}" >> $GITHUB_OUTPUT
          fi

      # 📥 Checkout correct branch
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ steps.branch.outputs.branch }}

      # 🖼 Resize images
      - name: Resize Oversized Images
        run: |
          find . -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) \
          -not -path "*/.git/*" \
          -not -path "*/node_modules/*" \
          -exec mogrify -resize 1920x1920\> {} \;

      # 📉 Optimize JPEG
      - name: Optimize JPEG
        run: |
          find . -type f \( -iname "*.jpg" -o -iname "*.jpeg" \) \
          -not -path "*/.git/*" \
          -not -path "*/node_modules/*" \
          -exec jpegoptim --strip-all --max=85 {} \;

      # 📉 Optimize PNG
      - name: Optimize PNG
        run: |
          find . -type f -iname "*.png" \
          -not -path "*/.git/*" \
          -not -path "*/node_modules/*" \
          -exec pngquant --force --ext .png --quality=75-90 {} \;

      # 💾 Commit if changes exist
      - name: Commit changes
        run: |
          git config --global user.name "CI Bot"
          git config --global user.email "ci@local"

          if [ -n "$(git status --porcelain)" ]; then
            git add .
            git commit -m "chore: optimize images via CI"
          else
            echo "No changes to commit"
          fi

      # 🚀 Push back to branch
      - name: Push changes
        run: |
          git push origin HEAD:${{ steps.branch.outputs.branch }}