name: Create Release on Merge

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: read

    steps:
      - name: Checkout repo branch
        uses: actions/checkout@v4
        with:
          ref: repo
          fetch-depth: 0

      # Get the merged PR info
      - name: Get PR information
        id: pr_info
        run: |
          # Fetch and checkout master to analyze history
          git fetch origin master
          git checkout -B master origin/master
          
          # Initialize variables
          FOUND_PR=false
          
          # Get the last 10 merge commits
          MERGE_COMMITS=$(git log --merges --format='%H' -n 10)
          
          for COMMIT in $MERGE_COMMITS; do
            # Extract PR number
            PR_NUMBER=$(git show --format=%B -s $COMMIT | grep -oP 'Merge pull request #\K\d+' || true)
          
            # Fallback: Try to match squash merge pattern "Title (#123)"
            if [ -z "$PR_NUMBER" ]; then
               PR_NUMBER=$(git show --format=%B -s $COMMIT | grep -oP '\(#\K\d+(?=\))' || true)
            fi
          
            if [ -n "$PR_NUMBER" ]; then
              echo "Checking PR #$PR_NUMBER..."
              PR_JSON=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
                https://api.github.com/repos/${{ github.repository }}/pulls/$PR_NUMBER)
          
              PR_TITLE=$(echo "$PR_JSON" | jq -r .title)
          
              # Check if title matches version pattern
              if [[ "$PR_TITLE" == *"1.4."* ]]; then
                 echo "✅ Found Release PR: #$PR_NUMBER - $PR_TITLE"
                 echo "pr_number=$PR_NUMBER" >> $GITHUB_OUTPUT
                 echo "pr_title=$PR_TITLE" >> $GITHUB_OUTPUT
          
                 PR_AUTHOR=$(echo "$PR_JSON" | jq -r .user.login)
                 echo "pr_author=$PR_AUTHOR" >> $GITHUB_OUTPUT
          
                 # Check first-time contributor
                 CONTRIBUTOR_JSON=$(curl -s -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
                   https://api.github.com/repos/${{ github.repository }}/contributors/$PR_AUTHOR)
                 CONTRIBUTIONS=$(echo "$CONTRIBUTOR_JSON" | jq -r .contributions)
                 if [ "$CONTRIBUTIONS" = "1" ]; then
                   echo "is_first_contributor=true" >> $GITHUB_OUTPUT
                 fi
          
                 # Get PR body safely
                 PR_BODY=$(echo "$PR_JSON" | jq -r .body)
                 {
                   echo "pr_body<<EOF"
                   echo "$PR_BODY"
                   echo "EOF"
                 } >> $GITHUB_OUTPUT
          
                 FOUND_PR=true
                 break
              fi
            fi
          done
          
          if [ "$FOUND_PR" = "false" ]; then
            echo "⚠️ No recent PR found matching '1.4.*'."
          fi

      # \Switch back to the 'repo' branch where APKs are stored
      - name: Switch back to repo branch
        run: |
          echo "Switching git context back to 'repo' branch..."
          git checkout repo

      - name: Find APK and extract version
        id: apk_info
        run: |
          # Find the Kavita APK
          APK_PATH=$(find ./apk -name "tachiyomi-all.kavita-*.apk" -type f | head -n 1)
          
          if [ -z "$APK_PATH" ]; then
            echo "❌ No Kavita APK found in ./apk folder!"
            echo "Current directory contents:"
            ls -R
            exit 1
          fi
          
          APK_FILENAME=$(basename "$APK_PATH")
          # Extract version (e.g., v1.4.22)
          VERSION=$(echo "$APK_FILENAME" | grep -oP 'v\d+\.\d+\.\d+')
          
          if [ -z "$VERSION" ]; then
             echo "❌ Could not determine version from filename: $APK_FILENAME"
             exit 1
          fi
          
          echo "Found APK: $APK_PATH"
          echo "Detected Version: $VERSION"
          
          echo "apk_path=$APK_PATH" >> $GITHUB_OUTPUT
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      # Check if release already exists to prevent duplicates
      - name: Check if release exists
        id: check_release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          VERSION="${{ steps.apk_info.outputs.version }}"
          echo "Checking if release $VERSION already exists..."
          
          if gh release view "$VERSION" > /dev/null 2>&1; then
            echo "⚠️ Release $VERSION already exists! Skipping creation."
            echo "exists=true" >> $GITHUB_OUTPUT
          else
            echo "✅ Release $VERSION does not exist. Proceeding."
            echo "exists=false" >> $GITHUB_OUTPUT
          fi

      - name: Get changelog
        if: steps.check_release.outputs.exists == 'false'
        id: changelog
        run: |
          # We need master history again for the changelog
          git checkout master
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          if [ -n "$LAST_TAG" ]; then
            COMMITS=$(git log $LAST_TAG..HEAD --pretty=format:"- %s (%h)")
          else
            COMMITS=$(git log --pretty=format:"- %s (%h)" -n 20)
          fi
          
          {
            echo "changelog<<EOF"
            echo "$COMMITS"
            echo "EOF"
          } >> $GITHUB_OUTPUT

      # Switch back to 'repo' branch to upload the APK
      - name: Final Switch to repo branch
        if: steps.check_release.outputs.exists == 'false'
        run: |
          git checkout repo

      - name: Create Release
        if: steps.check_release.outputs.exists == 'false'
        uses: softprops/action-gh-release@v2
        with:
          name: Release ${{ steps.apk_info.outputs.version }}
          tag_name: ${{ steps.apk_info.outputs.version }}
          target_commitish: repo
          body: |
            ## 🚀 Release ${{ steps.apk_info.outputs.version }}
            
            ${{ steps.pr_info.outputs.pr_body }}
            
            ---
            
            <details>
            <summary>📦 View Full Commit Log</summary>
            
            ${{ steps.changelog.outputs.changelog }}
            </details>
            
            ---
            🤖 *This release was automatically created*
          files: ${{ steps.apk_info.outputs.apk_path }}
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
