name: GitHub Release

on:
  workflow_call:
    secrets:
      RELEASE_TOKEN:
        description: 'GitHub token for release creation'
        required: true

permissions:
  contents: write

jobs:
  create-release:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
    - uses: actions/checkout@v4
      with:
        fetch-depth: 0
    
    - name: Set up Python
      uses: actions/setup-python@v4
      with:
        python-version: '3.x'
    
    - name: Install PlatformIO
      run: |
        python -m pip install --upgrade pip
        pip install --upgrade platformio esptool
    
    - name: Install xxd
      run: |
        sudo apt-get update
        sudo apt-get install xxd
    
    - name: Build Firmware
      run: |
        VERSION=$(grep '^version = ' platformio.ini | cut -d'"' -f2)
        
        # Always build firmware and LittleFS
        echo "Building firmware and LittleFS..."
        pio run -e esp32dev
        pio run -t buildfs
        
        # Copy firmware binary
        cp .pio/build/esp32dev/firmware.bin .pio/build/esp32dev/upgrade_filaman_firmware_v${VERSION}.bin
        
        # Create LittleFS binary - direct copy without header
        cp .pio/build/esp32dev/littlefs.bin .pio/build/esp32dev/upgrade_filaman_website_v${VERSION}.bin
        
        # Create full binary (always)
        (cd .pio/build/esp32dev && 
        esptool.py --chip esp32 merge_bin \
          --fill-flash-size 4MB \
          --flash_mode dio \
          --flash_freq 40m \
          --flash_size 4MB \
          -o filaman_full_${VERSION}.bin \
          0x1000 bootloader.bin \
          0x8000 partitions.bin \
          0x10000 firmware.bin \
          0x3D0000 littlefs.bin)
        
        # Verify file sizes
        echo "File sizes:"
        (cd .pio/build/esp32dev && ls -lh *.bin)
    
    - name: Get version from platformio.ini
      id: get_version
      run: |
        VERSION=$(grep '^version = ' platformio.ini | cut -d'"' -f2)
        echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
      
    - name: Generate Release Notes
      id: release_notes
      run: |
        # Get the latest tag
        LATEST_TAG=$(git for-each-ref --sort=-creatordate --format '%(refname:short)' refs/tags | sed -n '2p')
        
        if [ -n "$LATEST_TAG" ]; then
          echo "CHANGES<<EOF" >> $GITHUB_OUTPUT
          echo "Changes since ${LATEST_TAG}:" >> $GITHUB_OUTPUT
          echo "" >> $GITHUB_OUTPUT
          
          # Get all commits since last release with commit hash and author
          echo "### Added" >> $GITHUB_OUTPUT
          git log ${LATEST_TAG}..HEAD --pretty=format:"%h - %s (%an)" | grep -iE '^[a-f0-9]+ - (feat|add|new)' | sed 's/^[a-f0-9]* - feat: /- /' >> $GITHUB_OUTPUT || true
          echo "" >> $GITHUB_OUTPUT
          
          echo "### Fixed" >> $GITHUB_OUTPUT
          git log ${LATEST_TAG}..HEAD --pretty=format:"%h - %s (%an)" | grep -iE '^[a-f0-9]+ - fix' | sed 's/^[a-f0-9]* - fix: /- /' >> $GITHUB_OUTPUT || true
          echo "" >> $GITHUB_OUTPUT
          
          echo "### Changed" >> $GITHUB_OUTPUT
          git log ${LATEST_TAG}..HEAD --pretty=format:"%h - %s (%an)" | grep -ivE '^[a-f0-9]+ - (feat|fix|add|new)' | sed 's/^[a-f0-9]* - /- /' >> $GITHUB_OUTPUT || true
          echo "EOF" >> $GITHUB_OUTPUT
        else
          # First release
          echo "CHANGES<<EOF" >> $GITHUB_OUTPUT
          echo "Initial Release" >> $GITHUB_OUTPUT
          echo "" >> $GITHUB_OUTPUT
          
          # Add all commits for initial release
          echo "### Added" >> $GITHUB_OUTPUT
          git log --pretty=format:"%h - %s (%an)" | grep -iE '^[a-f0-9]+ - (feat|add|new)' | sed 's/^[a-f0-9]* - feat: /- /' >> $GITHUB_OUTPUT || true
          echo "" >> $GITHUB_OUTPUT
          
          echo "### Fixed" >> $GITHUB_OUTPUT
          git log --pretty=format:"%h - %s (%an)" | grep -iE '^[a-f0-9]+ - fix' | sed 's/^[a-f0-9]* - fix: /- /' >> $GITHUB_OUTPUT || true
          echo "" >> $GITHUB_OUTPUT
          
          echo "### Changed" >> $GITHUB_OUTPUT
          git log --pretty=format:"%h - %s (%an)" | grep -ivE '^[a-f0-9]+ - (feat|fix|add|new)' | sed 's/^[a-f0-9]* - /- /' >> $GITHUB_OUTPUT || true
          echo "EOF" >> $GITHUB_OUTPUT
        fi

    - name: Create GitHub Release
      env:
        GH_TOKEN: ${{ secrets.RELEASE_TOKEN }}
      run: |
        VERSION=${{ steps.get_version.outputs.VERSION }}
        cd .pio/build/esp32dev
        
        # Create release with available files
        FILES_TO_UPLOAD=""
        
        # Always add firmware
        if [ -f "upgrade_filaman_firmware_v${VERSION}.bin" ]; then
          FILES_TO_UPLOAD="$FILES_TO_UPLOAD upgrade_filaman_firmware_v${VERSION}.bin"
        fi
        
        # Add LittleFS and full binary only if they exist
        if [ -f "upgrade_filaman_website_v${VERSION}.bin" ]; then
          FILES_TO_UPLOAD="$FILES_TO_UPLOAD upgrade_filaman_website_v${VERSION}.bin"
        fi
        
        if [ -f "filaman_full_${VERSION}.bin" ]; then
          FILES_TO_UPLOAD="$FILES_TO_UPLOAD filaman_full_${VERSION}.bin"
        fi
        
        # Create release with available files
        if [ -n "$FILES_TO_UPLOAD" ]; then
          gh release create "v${VERSION}" \
            --title "Release ${VERSION}" \
            --notes "${{ steps.release_notes.outputs.CHANGES }}" \
            $FILES_TO_UPLOAD
        else
          echo "Error: No files found to upload"
          exit 1
        fi

    - name: Install lftp
      run: sudo apt-get install -y lftp
        
    - name: Upload Firmware via FTP
      if: success()
      env:
        FTP_PASSWORD: ${{ vars.FTP_PASSWORD }}
        FTP_USER: ${{ vars.FTP_USER }}
        FTP_HOST: ${{ vars.FTP_HOST }}
        VERSION: ${{ steps.get_version.outputs.VERSION }}
      run: |
        echo "Environment variables:"
        env | grep -E '^FTP_' | while read -r line; do
          var_name=$(echo "$line" | cut -d= -f1)
          var_value=$(echo "$line" | cut -d= -f2-)
          echo "$var_name is $(if [ -n "$var_value" ]; then echo "set"; else echo "empty"; fi)"
        done
        
        cd .pio/build/esp32dev
        if [ -n "$FTP_USER" ] && [ -n "$FTP_PASSWORD" ] && [ -n "$FTP_HOST" ]; then
          echo "All FTP credentials are present, attempting upload..."
          lftp -c "set ssl:verify-certificate no; \
                    set ftp:ssl-protect-data true; \
                    set ftp:ssl-force true; \
                    set ssl:check-hostname false; \
                    set ftp:ssl-auth TLS; \
                    open -u $FTP_USER,$FTP_PASSWORD $FTP_HOST; \
                    put -O / filaman_full_${VERSION}.bin -o filaman_full.bin"
        else
          echo "Error: Some FTP credentials are missing"
          exit 1
        fi