# .github/workflows/prepare-release.yml
name: Prepare Release

on:
  workflow_dispatch:
    inputs:
      bump:
        description: "Version bump type"
        required: true
        type: choice
        options:
          - patch
          - minor
          - major

permissions:
  contents: write
  pull-requests: write

jobs:
  prepare-release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
        with:
          fetch-depth: 0

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Calculate new version
        id: version
        run: |
          # Get current version from Cargo.toml
          CURRENT=$(grep '^version = ' Cargo.toml | head -1 | cut -d'"' -f2)

          # Calculate new version based on bump type
          IFS='.' read -r major minor patch <<< "$CURRENT"

          case "${{ inputs.bump }}" in
            major)
              major=$((major + 1))
              minor=0
              patch=0
              ;;
            minor)
              minor=$((minor + 1))
              patch=0
              ;;
            patch)
              patch=$((patch + 1))
              ;;
          esac

          NEW_VERSION="$major.$minor.$patch"
          echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
          echo "current_version=$CURRENT" >> $GITHUB_OUTPUT
          echo "Bumping from $CURRENT to $NEW_VERSION"

      - name: Update Cargo.toml
        run: |
          sed -i 's/^version = ".*"/version = "${{ steps.version.outputs.new_version }}"/' Cargo.toml

      - name: Update Cargo.lock
        run: |
          cargo update -p flux9s --precise ${{ steps.version.outputs.new_version }}

      - name: Generate changelog with Claude API
        id: changelog
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          VERSION="${{ steps.version.outputs.new_version }}"
          CURRENT_VERSION="${{ steps.version.outputs.current_version }}"

          # Get git diff since last tag
          LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
          if [ -n "$LAST_TAG" ]; then
            DIFF=$(git log $LAST_TAG..HEAD --pretty=format:"%h %s" --no-merges)
          else
            DIFF=$(git log --pretty=format:"%h %s" --no-merges --max-count=20)
          fi

          # Create the prompt
          PROMPT="Generate a concise changelog summary for version $VERSION based on these git commits. Format as bullet points under categories: Added, Changed, Fixed. Be specific but brief. Only include categories that have changes.

          Commits:
          $DIFF"

          # Generate changelog using Claude API with proper JSON escaping
          RESPONSE=$(curl -s https://api.anthropic.com/v1/messages \
            -H "content-type: application/json" \
            -H "x-api-key: $ANTHROPIC_API_KEY" \
            -H "anthropic-version: 2023-06-01" \
            -d @- << EOF
          {
            "model": "claude-3-haiku-20240307",
            "max_tokens": 1024,
            "messages": [{
              "role": "user",
              "content": $(echo "$PROMPT" | jq -Rs .)
            }]
          }
          EOF
          )

          # Extract the changelog text, with error handling
          CHANGELOG=$(echo "$RESPONSE" | jq -r '.content[0].text // empty')

          if [ -z "$CHANGELOG" ]; then
            echo "Warning: Claude API returned empty response"
            echo "API Response: $RESPONSE"
            CHANGELOG="### Changes\n- Version bump to $VERSION"
          fi

          # Save to file for next step
          echo "$CHANGELOG" > /tmp/ai_changelog.txt
          echo "Generated changelog:"
          cat /tmp/ai_changelog.txt

      - name: Update CHANGELOG.md
        run: |
          VERSION="${{ steps.version.outputs.new_version }}"
          DATE=$(date +%Y-%m-%d)

          # Read AI-generated changelog
          AI_CHANGELOG=$(cat /tmp/ai_changelog.txt 2>/dev/null || echo "### Changes\n- Version bump to $VERSION")

          # Create the new changelog entry
          cat > /tmp/changelog_entry.txt << EOF

          ## [$VERSION] - $DATE

          $AI_CHANGELOG
          EOF

          # Insert after the [Unreleased] line
          sed -i "/^## \[Unreleased\]/r /tmp/changelog_entry.txt" CHANGELOG.md

      - name: Create Pull Request
        uses: peter-evans/create-pull-request@4e1beaa7521e8b457b572c090b25bd3db56bf1c5 # v5
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          commit-message: "chore: bump version to ${{ steps.version.outputs.new_version }}"
          title: "Release v${{ steps.version.outputs.new_version }}"
          body: |
            ## Release v${{ steps.version.outputs.new_version }}

            This PR prepares the release for v${{ steps.version.outputs.new_version }}.

            **Version bump:** ${{ steps.version.outputs.current_version }} → ${{ steps.version.outputs.new_version }} (${{ inputs.bump }})

            **Changes in this PR:**
            - ✅ Updated version in Cargo.toml
            - ✅ Updated Cargo.lock
            - ✅ Updated CHANGELOG.md with AI-generated summary

            **What happens after merge:**
            1. ✅ PR gets merged to main
            2. ✅ Tag `v${{ steps.version.outputs.new_version }}` is automatically created by auto-tag workflow
            3. ✅ Release workflow is automatically triggered via workflow_dispatch
            4. ✅ Release workflow builds binaries for all platforms
            5. ✅ Publishes to crates.io
            6. ✅ Creates GitHub release with artifacts
            7. ✅ Updates Homebrew formula

            The CHANGELOG.md has been automatically generated using Claude AI. Please review and edit if needed before merging!
          branch: release-v${{ steps.version.outputs.new_version }}
          delete-branch: true
          labels: release
