name: Auto Version

on:
  pull_request:
    types: [closed]
    branches: [main]

jobs:
  version:
    # Only run if PR was merged (not just closed)
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: read
    
    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        fetch-depth: 0
        token: ${{ secrets.PAT }}
    
    - name: Setup Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.9'
    
    - name: Configure git
      run: |
        git config user.name "github-actions[bot]"
        git config user.email "github-actions[bot]@users.noreply.github.com"
    
    - name: Determine version bump type
      id: bump_type
      run: |
        PR_TITLE="${{ github.event.pull_request.title }}"
        echo "PR Title: $PR_TITLE"
        
        # Convert to lowercase for case-insensitive matching
        PR_TITLE_LOWER=$(echo "$PR_TITLE" | tr '[:upper:]' '[:lower:]')
        
        # Determine bump type based on PR title prefix
        if [[ "$PR_TITLE_LOWER" =~ ^(breaking|breaking[[:space:]]change): ]]; then
          echo "Detected BREAKING CHANGE - major version bump"
          echo "bump_type=major" >> $GITHUB_OUTPUT
          echo "should_bump=true" >> $GITHUB_OUTPUT
          echo "should_build_docker=true" >> $GITHUB_OUTPUT
        elif [[ "$PR_TITLE_LOWER" =~ ^feat: ]]; then
          echo "Detected new feature - minor version bump"
          echo "bump_type=minor" >> $GITHUB_OUTPUT
          echo "should_bump=true" >> $GITHUB_OUTPUT
          echo "should_build_docker=true" >> $GITHUB_OUTPUT
        elif [[ "$PR_TITLE_LOWER" =~ ^(fix|perf|refactor): ]]; then
          echo "Detected fix/perf/refactor - patch version bump"
          echo "bump_type=patch" >> $GITHUB_OUTPUT
          echo "should_bump=true" >> $GITHUB_OUTPUT
          echo "should_build_docker=true" >> $GITHUB_OUTPUT
        elif [[ "$PR_TITLE_LOWER" =~ ^docker: ]]; then
          echo "Detected docker build request - no version bump but build Docker"
          echo "bump_type=none" >> $GITHUB_OUTPUT
          echo "should_bump=false" >> $GITHUB_OUTPUT
          echo "should_build_docker=true" >> $GITHUB_OUTPUT
        elif [[ "$PR_TITLE_LOWER" =~ ^(docs|chore|test|ci|style)\+docker: ]]; then
          echo "Detected non-versioned change with Docker build request"
          echo "bump_type=none" >> $GITHUB_OUTPUT
          echo "should_bump=false" >> $GITHUB_OUTPUT
          echo "should_build_docker=true" >> $GITHUB_OUTPUT
        elif [[ "$PR_TITLE_LOWER" =~ ^(docs|chore|test|ci|style): ]]; then
          echo "Detected non-versioned change - no version bump"
          echo "bump_type=none" >> $GITHUB_OUTPUT
          echo "should_bump=false" >> $GITHUB_OUTPUT
          echo "should_build_docker=false" >> $GITHUB_OUTPUT
        else
          echo "No recognized prefix - no version bump"
          echo "bump_type=none" >> $GITHUB_OUTPUT
          echo "should_bump=false" >> $GITHUB_OUTPUT
          echo "should_build_docker=false" >> $GITHUB_OUTPUT
        fi
    
    - name: Get current version
      if: steps.bump_type.outputs.should_bump == 'true'
      id: current_version
      run: |
        CURRENT_VERSION=$(python -c "from config import __version__; print(__version__)")
        echo "Current version: $CURRENT_VERSION"
        echo "version=$CURRENT_VERSION" >> $GITHUB_OUTPUT
    
    - name: Bump version
      if: steps.bump_type.outputs.should_bump == 'true'
      id: new_version
      run: |
        python scripts/bump_version.py ${{ steps.bump_type.outputs.bump_type }}
        NEW_VERSION=$(python -c "from config import __version__; print(__version__)")
        echo "New version: $NEW_VERSION"
        echo "version=$NEW_VERSION" >> $GITHUB_OUTPUT
    
    - name: Commit version change
      if: steps.bump_type.outputs.should_bump == 'true'
      run: |
        git add config.py
        git commit -m "chore: bump version to ${{ steps.new_version.outputs.version }}

        Automated version bump from PR #${{ github.event.pull_request.number }}
        ${{ github.event.pull_request.title }}
        
        Co-authored-by: ${{ github.event.pull_request.user.login }} <${{ github.event.pull_request.user.id }}+${{ github.event.pull_request.user.login }}@users.noreply.github.com>"
        git push
    
    - name: Create git tag
      if: steps.bump_type.outputs.should_bump == 'true'
      run: |
        git tag -a "v${{ steps.new_version.outputs.version }}" -m "Release v${{ steps.new_version.outputs.version }}
        
        Changes in this release:
        - ${{ github.event.pull_request.title }}
        
        PR: #${{ github.event.pull_request.number }}
        Author: @${{ github.event.pull_request.user.login }}"
        git push origin "v${{ steps.new_version.outputs.version }}"
    
    - name: Generate release notes
      if: steps.bump_type.outputs.should_bump == 'true'
      id: release_notes
      run: |
        # Extract PR body for release notes
        PR_BODY=$(cat << 'EOF'
        ${{ github.event.pull_request.body }}
        EOF
        )
        
        # Create release notes
        RELEASE_NOTES=$(cat << EOF
        ## What's Changed
        
        ${{ github.event.pull_request.title }} by @${{ github.event.pull_request.user.login }} in #${{ github.event.pull_request.number }}
        
        ### Details
        
        $PR_BODY
        
        ### Version Info
        - Previous version: ${{ steps.current_version.outputs.version }}
        - New version: ${{ steps.new_version.outputs.version }}
        - Bump type: ${{ steps.bump_type.outputs.bump_type }}
        
        **Full Changelog**: https://github.com/${{ github.repository }}/compare/v${{ steps.current_version.outputs.version }}...v${{ steps.new_version.outputs.version }}
        EOF
        )
        
        # Save to file for GitHub release
        echo "$RELEASE_NOTES" > release_notes.md
    
    - name: Create GitHub release
      if: steps.bump_type.outputs.should_bump == 'true'
      uses: softprops/action-gh-release@v1
      with:
        tag_name: v${{ steps.new_version.outputs.version }}
        name: Release v${{ steps.new_version.outputs.version }}
        body_path: release_notes.md
        draft: false
        prerelease: false
        generate_release_notes: true
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
    
    - name: Trigger Docker build
      if: steps.bump_type.outputs.should_build_docker == 'true'
      run: |
        echo "🐳 Triggering Docker build and publish workflow"
        # The Docker workflow will be triggered by the tag creation (if version bumped)
        # or by repository_dispatch (if docker: prefix without version bump)
        if [ "${{ steps.bump_type.outputs.should_bump }}" == "false" ]; then
          # For docker: prefix without version bump, trigger via repository_dispatch
          curl -X POST \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Accept: application/vnd.github.v3+json" \
            "https://api.github.com/repos/${{ github.repository }}/dispatches" \
            -d '{"event_type":"docker-build","client_payload":{"pr_number":"${{ github.event.pull_request.number }}","pr_title":"${{ github.event.pull_request.title }}","commit_sha":"${{ github.sha }}"}}'
          
          # Add comment to PR about Docker build
          COMMENT_BODY="🐳 **Docker Image Build Triggered**

          This PR triggered a Docker image build because of the \`+docker\` suffix in the title.

          **Expected Image Tags:**
          - \`ghcr.io/${{ github.repository_owner }}/zen-mcp-server:pr-${{ github.event.pull_request.number }}\`
          - \`ghcr.io/${{ github.repository_owner }}/zen-mcp-server:main-${{ github.sha }}\`

          **To test the image after build completes:**
          \`\`\`bash
          docker pull ghcr.io/${{ github.repository_owner }}/zen-mcp-server:pr-${{ github.event.pull_request.number }}
          \`\`\`

          **Claude Desktop config for testing:**
          \`\`\`json
          {
            \"mcpServers\": {
              \"gemini\": {
                \"command\": \"docker\",
                \"args\": [
                  \"run\", \"--rm\", \"-i\",
                  \"-e\", \"GEMINI_API_KEY\",
                  \"ghcr.io/${{ github.repository_owner }}/zen-mcp-server:pr-${{ github.event.pull_request.number }}\"
                ],
                \"env\": {
                  \"GEMINI_API_KEY\": \"your-api-key-here\"
                }
              }
            }
          }
          \`\`\`

          View the build progress in the [Actions tab](https://github.com/${{ github.repository }}/actions)."
          
          curl -X POST \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Accept: application/vnd.github.v3+json" \
            "https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.pull_request.number }}/comments" \
            -d "{\"body\":\"$COMMENT_BODY\"}"
        fi

    - name: Summary
      run: |
        if [ "${{ steps.bump_type.outputs.should_bump }}" == "true" ]; then
          echo "### ✅ Version Bumped Successfully" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "- **Previous version**: ${{ steps.current_version.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "- **New version**: ${{ steps.new_version.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Bump type**: ${{ steps.bump_type.outputs.bump_type }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Tag**: v${{ steps.new_version.outputs.version }}" >> $GITHUB_STEP_SUMMARY
          echo "- **PR**: #${{ github.event.pull_request.number }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Docker**: Will build and publish with new tag" >> $GITHUB_STEP_SUMMARY
        elif [ "${{ steps.bump_type.outputs.should_build_docker }}" == "true" ]; then
          echo "### 🐳 Docker Build Requested" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "No version bump but Docker image will be built and published." >> $GITHUB_STEP_SUMMARY
          echo "- **PR**: #${{ github.event.pull_request.number }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Title**: ${{ github.event.pull_request.title }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Docker tag**: Based on commit SHA" >> $GITHUB_STEP_SUMMARY
        else
          echo "### ℹ️ No Version Bump Required" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "PR title prefix did not require a version bump." >> $GITHUB_STEP_SUMMARY
          echo "- **PR**: #${{ github.event.pull_request.number }}" >> $GITHUB_STEP_SUMMARY
          echo "- **Title**: ${{ github.event.pull_request.title }}" >> $GITHUB_STEP_SUMMARY
        fi

