name: 'Generate Release Notes'
description: 'Generate formatted release notes with download table and contributor info'
inputs:
  version:
    description: 'The version string (e.g., 9.1.3)'
    required: true
  repo:
    description: 'Repository in owner/repo format'
    required: true
  github_token:
    description: 'GitHub token for API access'
    required: true
outputs:
  release_notes_file:
    description: 'Path to the release notes file'
    value: ${{ steps.generate.outputs.release_notes_file }}
runs:
  using: "composite"
  steps:
    - name: Generate release notes
      id: generate
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        VERSION: ${{ inputs.version }}
        REPO: ${{ inputs.repo }}
      run: |
        set -e

        TAG_NAME="v$VERSION"
        echo "Generating release notes for $TAG_NAME"

        # Check if tag exists via GitHub API (works without local git tags)
        TAG_EXISTS=$(gh api repos/$REPO/git/refs/tags/$TAG_NAME --jq '.ref' 2>/dev/null || echo "")

        # Check if this tag already has a release on GitHub
        RELEASE_EXISTS=$(gh api repos/$REPO/releases/tags/$TAG_NAME --jq '.tag_name' 2>/dev/null || echo "")

        if [ -n "$TAG_EXISTS" ]; then
          # Tag exists on GitHub - use it as target (covers both new and existing releases)
          TARGET_COMMIT="$TAG_NAME"
          if [ -n "$RELEASE_EXISTS" ]; then
            # Release already exists - find the release before this one
            echo "Tag $TAG_NAME exists with release, finding previous release..."
            PREVIOUS_TAG=$(gh api repos/$REPO/releases --jq "[.[] | select(.tag_name != \"$TAG_NAME\")] | .[0].tag_name" 2>/dev/null || echo "")
          else
            # New release - use latest release as previous
            echo "Tag $TAG_NAME exists on GitHub, creating new release..."
            PREVIOUS_TAG=$(gh api repos/$REPO/releases/latest --jq '.tag_name' 2>/dev/null || echo "")
          fi
        else
          # Tag doesn't exist yet - preview mode, use HEAD
          echo "Tag $TAG_NAME doesn't exist yet, using HEAD for preview"
          PREVIOUS_TAG=$(gh api repos/$REPO/releases/latest --jq '.tag_name' 2>/dev/null || echo "")
          TARGET_COMMIT="HEAD"
        fi

        echo "Previous release: ${PREVIOUS_TAG:-none}"
        echo "Target commit: $TARGET_COMMIT"

        # Generate auto release notes from GitHub
        if [ -n "$PREVIOUS_TAG" ]; then
          AUTO_NOTES=$(gh api repos/$REPO/releases/generate-notes \
            -f tag_name="$TAG_NAME" \
            -f target_commitish="$TARGET_COMMIT" \
            -f previous_tag_name="$PREVIOUS_TAG" \
            --jq '.body' 2>/dev/null || echo "")
        else
          AUTO_NOTES=$(gh api repos/$REPO/releases/generate-notes \
            -f tag_name="$TAG_NAME" \
            -f target_commitish="$TARGET_COMMIT" \
            --jq '.body' 2>/dev/null || echo "")
        fi

        echo "AUTO_NOTES length: ${#AUTO_NOTES}"
        echo "=== AUTO_NOTES content ==="
        echo "$AUTO_NOTES"
        echo "=== end AUTO_NOTES ==="

        # Extract What's Changed content (just the bullet points)
        WHATS_CHANGED_CONTENT=""
        if echo "$AUTO_NOTES" | grep -q "What's Changed"; then
          WHATS_CHANGED_CONTENT=$(echo "$AUTO_NOTES" | sed -n "/## What's Changed/,/## New Contributors\|## Full Changelog\|^$/p" | grep "^\* " || echo "")
        fi

        # Extract New Contributors section
        NEW_CONTRIBUTORS=""
        if echo "$AUTO_NOTES" | grep -q "New Contributors"; then
          NEW_CONTRIBUTORS=$(echo "$AUTO_NOTES" | sed -n "/## New Contributors/,/## Full Changelog\|^$/p" | head -20)
        fi

        # Extract Full Changelog link
        FULL_CHANGELOG=$(echo "$AUTO_NOTES" | grep "Full Changelog" | head -1 || echo "")

        # Extract unique contributors from the changelog (exclude bots)
        CONTRIBUTORS=$(echo "$AUTO_NOTES" | grep -oE '@[a-zA-Z0-9_-]+' | grep -ivE '^@(copilot|claude)$' | sort -u | tr '\n' ' ' | sed 's/ /, /g' | sed 's/, $//' || echo "")

        # Build the release notes file
        RELEASE_NOTES_FILE="release_notes.md"

        {
          echo "## Lemonade Server"
          echo ""
          echo "| Operating System | Downloads |"
          echo "|------------------|-----------|"
          echo "| **Windows** | [lemonade.msi](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade.msi) (Server + App) |"
          echo "| **Ubuntu 24.04+** | [Launchpad PPA](https://launchpad.net/~lemonade-team/+archive/ubuntu/stable) (Server + App) |"
          echo "| **Fedora 43** | [lemonade-server-${VERSION}.x86_64.rpm](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-server-${VERSION}.x86_64.rpm) (Server + App) |"
          echo "| **macOS (beta)** | [Lemonade-${VERSION}-Darwin.pkg](https://github.com/$REPO/releases/download/$TAG_NAME/Lemonade-${VERSION}-Darwin.pkg) (Server + App) |"
          echo ""
          echo "> lemonade-server-minimal.msi is deprecated and will be removed in a future release."
          echo ""
          echo "> **Other platforms?** See our [Installation Options](https://lemonade-server.ai/install_options.html) for [Docker](https://lemonade-server.ai/install_options.html#docker), [Snap](https://lemonade-server.ai/install_options.html#ubuntu), [Arch](https://lemonade-server.ai/install_options.html#arch), [Fedora](https://lemonade-server.ai/install_options.html#fedora), [Debian](https://lemonade-server.ai/install_options.html#debian), and more."
          echo ""
          echo "## Embeddable Lemonade"
          echo ""
          echo "Portable binaries for bundling into your own installer. Run \`lemond ./\` as a subprocess."
          echo ""
          echo "| Platform | Download |"
          echo "|----------|----------|"
          echo "| **Ubuntu x64** | [lemonade-embeddable-${VERSION}-ubuntu-x64.tar.gz](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-embeddable-${VERSION}-ubuntu-x64.tar.gz) |"
          echo "| **Windows x64** | [lemonade-embeddable-${VERSION}-windows-x64.zip](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-embeddable-${VERSION}-windows-x64.zip) |"
          echo ""
          echo "---"
          echo ""
        } > "$RELEASE_NOTES_FILE"

        # Build What's Changed section with thank you and collapsible details
        if [ -n "$WHATS_CHANGED_CONTENT" ]; then
          {
            echo "## What's Changed"
            echo ""
            if [ -n "$CONTRIBUTORS" ]; then
              echo "Thanks $CONTRIBUTORS for your awesome contributions to this release!"
              echo ""
            fi
            echo "<details>"
            echo "<summary>Click to expand changelog</summary>"
            echo ""
            echo "$WHATS_CHANGED_CONTENT"
            echo ""
            echo "</details>"
            echo ""
          } >> "$RELEASE_NOTES_FILE"
        fi
        [ -n "$NEW_CONTRIBUTORS" ] && echo "$NEW_CONTRIBUTORS" >> "$RELEASE_NOTES_FILE" && echo "" >> "$RELEASE_NOTES_FILE"
        [ -n "$FULL_CHANGELOG" ] && echo "$FULL_CHANGELOG" >> "$RELEASE_NOTES_FILE"

        # Code signing policy note
        {
          echo ""
          echo "---"
          echo ""
          echo "> Windows installers are signed. Free code signing provided by [SignPath.io](https://signpath.io), certificate by [SignPath Foundation](https://signpath.org). See our [Code Signing Policy](https://github.com/$REPO#code-signing-policy)."
        } >> "$RELEASE_NOTES_FILE"

        echo "release_notes_file=$RELEASE_NOTES_FILE" >> $GITHUB_OUTPUT
        cat "$RELEASE_NOTES_FILE"
