name: Update UE Submodule and PR

on:
  workflow_dispatch:
  
jobs:
  update-submodule:
    permissions: write-all
    runs-on: ubuntu-latest

    steps:
      - name: Setup github SSH for UEPseudo
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.UEPSEUDO_SSH_KEY }}
          known_hosts: unnecessary
        
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Initialize submodule
        run: |
          git submodule update --init --recursive
      
      - name: Get commits between HEAD and main in the submodule
        id: submodule-commits
        run: |
          cd ./deps/first/Unreal
          git fetch origin main
          
          # Get the remote URL to extract owner/repo
          REMOTE_URL=$(git config --get remote.origin.url)
          # Extract owner/repo from the URL (works for both HTTPS and SSH)
          if [[ $REMOTE_URL == git@github.com:* ]]; then
            REPO_PATH=${REMOTE_URL#git@github.com:}
            REPO_PATH=${REPO_PATH%.git}
          else
            REPO_PATH=${REMOTE_URL#https://github.com/}
            REPO_PATH=${REPO_PATH%.git}
          fi
          
          echo "Submodule repository: $REPO_PATH"
          
          # Generate commit list with proper PR links
          git log HEAD..main --pretty="tformat:* %s (**%an**) _%h_" | \
          sed "s|#\([0-9]\+\)|[#\1](https://github.com/${REPO_PATH}/pull/\1)|g" > submodule-commits.txt
          
          # Read the file content and save to environment variable
          {
            echo 'COMMITS_BODY<<EOF'
            cat submodule-commits.txt
            echo EOF
          } >> $GITHUB_ENV
      
      - name: Update submodule to latest commit on main branch
        run: |
          cd ./deps/first/Unreal
          git checkout main
          git pull origin main     
          
      - name: Create Pull Request
        uses: peter-evans/create-pull-request@v5
        with:
          commit-message: "chore: update UE submodule" 
          committer: GitHub <noreply@github.com>
          author: ${{ github.actor }} <${{ github.actor }}@users.noreply.github.com>
          title: Update UE Submodule
          body: ${{ env.COMMITS_BODY }}
          branch: update-ue-submodule
          base: main
