name: Update Homebrew Formula

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: 'Version to update (e.g., 0.0.28)'
        required: true
        type: string

env:
  CARGO_TERM_COLOR: always

permissions:
  contents: write

jobs:
  update-formula:
    name: Update Homebrew Formula
    runs-on: ubuntu-latest
    if: github.event_name == 'release' || github.event_name == 'workflow_dispatch'
    permissions:
      contents: write

    steps:
    - name: Checkout main repository
      uses: actions/checkout@v4

    - name: Extract version from tag
      id: version
      run: |
        if [ "${{ github.event_name }}" = "release" ]; then
          # Extract version from release tag name
          VERSION="${{ github.event.release.tag_name }}"
          VERSION="${VERSION#v}"  # Remove 'v' prefix if present
        else
          VERSION="${{ github.event.inputs.version }}"
        fi
        echo "version=$VERSION" >> $GITHUB_OUTPUT
        echo "Extracted version: $VERSION"

    - name: Wait for release assets with verification
      run: |
        echo "Waiting for release assets to be available..."
        VERSION="${{ steps.version.outputs.version }}"
        BASE_URL="https://github.com/Linuxdazhao/cc_auto_switch/releases/download/v${VERSION}"
        
        # Define all files to check
        FILES=(
          "cc-switch-x86_64-apple-darwin.tar.gz"
          "cc-switch-aarch64-apple-darwin.tar.gz"
          "cc-switch-x86_64-unknown-linux-gnu.tar.gz"
          "cc-switch-aarch64-unknown-linux-gnu.tar.gz"
        )
        
        # Wait up to 10 minutes for all files to be available
        MAX_ATTEMPTS=60
        SLEEP_TIME=10
        
        for attempt in $(seq 1 $MAX_ATTEMPTS); do
          echo "Attempt $attempt/$MAX_ATTEMPTS - Checking file availability..."
          all_available=true
          
          for file in "${FILES[@]}"; do
            url="${BASE_URL}/${file}"
            if ! curl -sSL --fail --head "$url" > /dev/null 2>&1; then
              echo "File not yet available: $file"
              all_available=false
              break
            fi
          done
          
          if [ "$all_available" = true ]; then
            echo "All files are now available!"
            break
          fi
          
          if [ $attempt -eq $MAX_ATTEMPTS ]; then
            echo "ERROR: Not all files became available within the timeout period"
            exit 1
          fi
          
          echo "Waiting ${SLEEP_TIME} seconds before next check..."
          sleep $SLEEP_TIME
        done

    - name: Download and calculate checksums
      id: checksums
      run: |
        VERSION="${{ steps.version.outputs.version }}"
        BASE_URL="https://github.com/Linuxdazhao/cc_auto_switch/releases/download/v${VERSION}"
        
        # Function to download and calculate checksum with retry
        calculate_sha() {
          local filename=$1
          local max_retries=3
          local retry=0
          
          while [ $retry -lt $max_retries ]; do
            echo "Downloading $filename (attempt $((retry + 1))/$max_retries)" >&2
            
            # Download file with verbose error reporting
            if curl -sSL --fail --max-time 60 \
                   --retry 3 --retry-delay 5 --retry-max-time 300 \
                   "${BASE_URL}/${filename}" -o "${filename}"; then
              
              # Verify file was downloaded and has content
              if [ -s "${filename}" ]; then
                local sha=$(sha256sum "${filename}" | cut -d' ' -f1)
                echo "Successfully calculated SHA256 for $filename: $sha" >&2
                echo "$sha"
                rm -f "${filename}"  # Clean up
                return 0
              else
                echo "ERROR: Downloaded file is empty: $filename" >&2
              fi
            else
              echo "ERROR: Failed to download $filename (HTTP error or timeout)" >&2
            fi
            
            retry=$((retry + 1))
            if [ $retry -lt $max_retries ]; then
              echo "Retrying in 10 seconds..." >&2
              sleep 10
            fi
          done
          
          echo "ERROR: Failed to download $filename after $max_retries attempts" >&2
          return 1
        }
        
        # Calculate checksums for all platforms
        echo "Calculating SHA256 checksums for all platforms..."
        
        MAC_INTEL_SHA=$(calculate_sha "cc-switch-x86_64-apple-darwin.tar.gz")
        if [ $? -ne 0 ]; then exit 1; fi
        
        MAC_ARM_SHA=$(calculate_sha "cc-switch-aarch64-apple-darwin.tar.gz")
        if [ $? -ne 0 ]; then exit 1; fi
        
        LINUX_INTEL_SHA=$(calculate_sha "cc-switch-x86_64-unknown-linux-gnu.tar.gz")
        if [ $? -ne 0 ]; then exit 1; fi
        
        LINUX_ARM_SHA=$(calculate_sha "cc-switch-aarch64-unknown-linux-gnu.tar.gz")
        if [ $? -ne 0 ]; then exit 1; fi
        
        # Set outputs with validation
        echo "Setting GitHub outputs..."
        echo "mac_intel_sha=$MAC_INTEL_SHA" >> $GITHUB_OUTPUT
        echo "mac_arm_sha=$MAC_ARM_SHA" >> $GITHUB_OUTPUT
        echo "linux_intel_sha=$LINUX_INTEL_SHA" >> $GITHUB_OUTPUT
        echo "linux_arm_sha=$LINUX_ARM_SHA" >> $GITHUB_OUTPUT
        
        # Display summary
        echo "=== SHA256 Checksums Summary ==="
        echo "macOS Intel (x86_64): $MAC_INTEL_SHA"
        echo "macOS ARM (aarch64):  $MAC_ARM_SHA"
        echo "Linux Intel (x86_64): $LINUX_INTEL_SHA"
        echo "Linux ARM (aarch64):  $LINUX_ARM_SHA"

    - name: Checkout tap repository
      uses: actions/checkout@v4
      with:
        repository: Linuxdazhao/homebrew-cc-switch
        token: ${{ secrets.HOMEBREW_TAP_TOKEN || secrets.GITHUB_TOKEN }}
        path: homebrew-cc-switch

    - name: Update formula
      run: |
        cd homebrew-cc-switch
        VERSION="${{ steps.version.outputs.version }}"

        # Copy template and replace placeholders
        cp ../.github/workflows/formula-template.rb Formula/cc-switch.rb
        sed -i "s/__VERSION__/${VERSION}/g" Formula/cc-switch.rb
        sed -i "s/__MAC_ARM_SHA__/${{ steps.checksums.outputs.mac_arm_sha }}/g" Formula/cc-switch.rb
        sed -i "s/__MAC_INTEL_SHA__/${{ steps.checksums.outputs.mac_intel_sha }}/g" Formula/cc-switch.rb
        sed -i "s/__LINUX_ARM_SHA__/${{ steps.checksums.outputs.linux_arm_sha }}/g" Formula/cc-switch.rb
        sed -i "s/__LINUX_INTEL_SHA__/${{ steps.checksums.outputs.linux_intel_sha }}/g" Formula/cc-switch.rb

        echo "Updated formula content:"
        cat Formula/cc-switch.rb

    - name: Commit and push changes
      run: |
        cd homebrew-cc-switch
        git config --global user.name "github-actions[bot]"
        git config --global user.email "github-actions[bot]@users.noreply.github.com"
        
        git add Formula/cc-switch.rb
        git commit -m "Update cc-switch to v${{ steps.version.outputs.version }}

        - Update version to ${{ steps.version.outputs.version }}
        - Update SHA256 checksums for all platforms
        
        🤖 Auto-updated by GitHub Actions"
        
        git push origin main