name: Build Minecraft Mod

on:
  push:
    branches: [ main ]
  release:
    types: [ published ]

jobs:
  build:
    name: Build Mod
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: 21

      - name: Set up Gradle
        uses: gradle/gradle-build-action@v2
        with:
          gradle-version: 9.2.1  # or whatever version your mod uses

      - name: Build mod
        run: gradle build

      - name: Read mod name and version
        id: mod_info
        run: |
          NAME=$(grep "^archives_base_name" gradle.properties | cut -d'=' -f2)
          VERSION=$(grep "^mod_version" gradle.properties | cut -d'=' -f2)

          if [ -z "$NAME" ] || [ -z "$VERSION" ]; then
            echo "Failed to read mod info from gradle.properties"
            exit 1
          fi

          JAR="build/libs/${NAME}-${VERSION}.jar"

          if [ ! -f "$JAR" ]; then
            echo "Expected jar not found: $JAR"
            exit 1
          fi

          echo "name=$NAME" >> $GITHUB_OUTPUT
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "jar=$JAR" >> $GITHUB_OUTPUT

      - name: Upload mod artifact
        uses: actions/upload-artifact@v4
        with:
          name: minecraft-mod
          path: ${{ steps.mod_info.outputs.jar }}

  create-release:
    name: Create GitHub Release
    runs-on: ubuntu-latest
    needs: build

    steps:
      - uses: actions/checkout@v4

      - name: Download mod artifact
        uses: actions/download-artifact@v4
        with:
          name: minecraft-mod
          path: ./release-artifacts/

      - name: Read mod info again (for tagging)
        id: mod_info
        run: |
          NAME=$(grep "^archives_base_name" gradle.properties | cut -d'=' -f2)
          VERSION=$(grep "^mod_version" gradle.properties | cut -d'=' -f2)
          echo "name=$NAME" >> $GITHUB_OUTPUT
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Find next available release tag
        id: tag
        run: |
          BASE="${{ steps.mod_info.outputs.name }}-${{ steps.mod_info.outputs.version }}"
          TAG="$BASE"
          i=1
          while gh release view "$TAG" >/dev/null 2>&1; do
            TAG="${BASE}($i)"
            i=$((i+1))
          done
          echo "tag=$TAG" >> $GITHUB_OUTPUT

      - name: Create release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.tag.outputs.tag }}
          name: ${{ steps.tag.outputs.tag }}
        env:
          GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}

      - name: Upload jar to release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.tag.outputs.tag }}
          files: ./release-artifacts/*.jar
        env:
          GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
