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 "")

        # Search for the release notes issue by exact title (e.g. "v10.8.0 release notes")
        RELEASE_NOTES_ISSUE_BODY=$(gh issue list --repo "$REPO" \
          --state open \
          --search "\"$TAG_NAME release notes\" in:title" \
          --json body --limit 1 \
          | jq -r '.[0].body // ""' 2>/dev/null || echo "")

        HEADLINE_SECTION=""
        BREAKING_CHANGES_SECTION=""

        if [ -n "$RELEASE_NOTES_ISSUE_BODY" ]; then
          echo "Found release notes issue, extracting Headline and Breaking Changes..."
          HEADLINE_SECTION=$(echo "$RELEASE_NOTES_ISSUE_BODY" | \
            awk '/^## Headline/{found=1} found && /^## / && !/^## Headline/{found=0} found{print}')
          BREAKING_CHANGES_SECTION=$(echo "$RELEASE_NOTES_ISSUE_BODY" | \
            awk '/^## Breaking Changes/{found=1} found && /^## / && !/^## Breaking Changes/{found=0} found{print}')
        else
          echo "No release notes issue found; Headline and Breaking Changes will need to be added manually."
        fi

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

        {
          if [ -n "$HEADLINE_SECTION" ]; then
            echo "$HEADLINE_SECTION"
            echo ""
          fi
          if [ -n "$BREAKING_CHANGES_SECTION" ]; then
            echo "$BREAKING_CHANGES_SECTION"
            echo ""
          fi
        } > "$RELEASE_NOTES_FILE"

        {
          echo "## Lemonade Server"
          echo ""
          echo "| Operating System | Downloads |"
          echo "|------------------|-----------|"
          echo "| **Windows** | [lemonade.msi](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade.msi) |"
          echo "| **Ubuntu 24.04+** | [Launchpad PPA](https://launchpad.net/~lemonade-team/+archive/ubuntu/stable) |"
          echo "| **Debian 13 (x86_64)** | [lemonade-server_${VERSION}-debian13_amd64.deb](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-server_${VERSION}-debian13_amd64.deb) |"
          echo "| **Debian 13 (ARM64)** | [lemonade-server_${VERSION}-debian13_arm64.deb](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-server_${VERSION}-debian13_arm64.deb) |"
          echo "| **Fedora 43 (x86_64)** | [lemonade-server-${VERSION}-fc43.x86_64.rpm](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-server-${VERSION}-fc43.x86_64.rpm) |"
          echo "| **Fedora 43 (ARM64)** | [lemonade-server-${VERSION}-fc43.aarch64.rpm](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-server-${VERSION}-fc43.aarch64.rpm) |"
          echo "| **Fedora 44 (x86_64)** | [lemonade-server-${VERSION}-fc44.x86_64.rpm](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-server-${VERSION}-fc44.x86_64.rpm) |"
          echo "| **Fedora 44 (ARM64)** | [lemonade-server-${VERSION}-fc44.aarch64.rpm](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-server-${VERSION}-fc44.aarch64.rpm) |"
          echo "| **macOS** | [Lemonade-${VERSION}-Darwin.pkg](https://github.com/$REPO/releases/download/$TAG_NAME/Lemonade-${VERSION}-Darwin.pkg) |"
          echo ""
          echo "> **Other platforms?** See our [Installation Options](https://lemonade-server.ai/docs/guide/install/) for [Docker](https://lemonade-server.ai/docs/guide/install/docker/), [Snap](https://lemonade-server.ai/docs/guide/install/ubuntu/#__tabbed_2_3), [Arch](https://lemonade-server.ai/docs/guide/install/arch/), [Debian](https://lemonade-server.ai/docs/guide/install/), 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 "| **Ubuntu arm64** | [lemonade-embeddable-${VERSION}-ubuntu-arm64.tar.gz](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-embeddable-${VERSION}-ubuntu-arm64.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 "| **macOS arm64** | [lemonade-embeddable-${VERSION}-macos-arm64.tar.gz](https://github.com/$REPO/releases/download/$TAG_NAME/lemonade-embeddable-${VERSION}-macos-arm64.tar.gz) |"
          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"
