name: Lockfile Maintenance

on:
  workflow_dispatch:

jobs:
  upgrade-lockfile:
    name: "Upgrade Lockfile"
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    env:
      BASE_BRANCH: main
      LOCKFILE_BRANCH: chore/uv-lockfile

    steps:
      - uses: actions/checkout@v6
        with:
          ref: ${{ env.BASE_BRANCH }}
      - name: Install uv
        uses: astral-sh/setup-uv@v7
        with:
          python-version: "3.14"
          enable-cache: true
          cache-dependency-glob: "uv.lock"
      - name: Update uv lockfile
        run: uv lock --upgrade
      - name: Check for changes
        id: check_changes
        run: |
          git fetch origin ${{ env.LOCKFILE_BRANCH }} || true
          if git diff --quiet origin/${{ env.LOCKFILE_BRANCH }} -- uv.lock 2>/dev/null || git diff --quiet uv.lock; then
            echo "changed=false" >> $GITHUB_OUTPUT
          else
            echo "changed=true" >> $GITHUB_OUTPUT
          fi
      - name: Create branch, commit and push changes
        if: steps.check_changes.outputs.changed == 'true'
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git checkout -B ${{ env.LOCKFILE_BRANCH }}
          git add uv.lock
          git commit -m "chore(deps): regenerate uv lockfile"
          git push --force origin ${{ env.LOCKFILE_BRANCH }}
      - name: Create or Update Pull Request
        if: steps.check_changes.outputs.changed == 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          PR_EXISTS=$(gh pr list --head ${{ env.LOCKFILE_BRANCH }} --base ${{ env.BASE_BRANCH }} --json number --jq '.[0].number // empty')

          if [ -z "$PR_EXISTS" ]; then
            gh pr create \
              --title "chore(deps): regenerate uv lockfile" \
              --body "Automated update of uv.lock file generated by lockfile maintenance workflow." \
              --base ${{ env.BASE_BRANCH }} \
              --head ${{ env.LOCKFILE_BRANCH }}
          else
            echo "PR #$PR_EXISTS already exists and has been updated with new commits"
          fi
