name: Gitea Release

on:
  workflow_call:
    secrets:
      GITEA_TOKEN:
        description: 'Token für Gitea API-Zugriff'
        required: true

    outputs:
      version:
        description: 'The version that was released'
        value: ${{ jobs.create-release.outputs.version }}

jobs:
  create-release:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get_version.outputs.VERSION }}
    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)
        
        # 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
        (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: Determine Gitea URL
      id: gitea_url
      run: |
        echo "Debug Environment:"
        echo "GITHUB_SERVER_URL=${GITHUB_SERVER_URL:-not set}"
        echo "GITEA_SERVER_URL=${GITEA_SERVER_URL:-not set}"
        echo "GITHUB_REPOSITORY=${GITHUB_REPOSITORY:-not set}"
        echo "GITEA_REPOSITORY=${GITEA_REPOSITORY:-not set}"
        echo "RUNNER_NAME=${RUNNER_NAME:-not set}"
        
        # Set API URL based on environment
        if [ -n "${GITEA_ACTIONS}" ] || [ -n "${GITEA_REPOSITORY}" ] || [[ "${RUNNER_NAME}" == *"gitea"* ]]; then
          GITEA_API_URL="${GITHUB_SERVER_URL}"
          GITEA_REPO=$(echo "${GITHUB_REPOSITORY}" | cut -d'/' -f2)
          GITEA_OWNER=$(echo "${GITHUB_REPOSITORY}" | cut -d'/' -f1)
        else
          echo "Error: This workflow is only for Gitea"
          exit 1
        fi
        
        echo "GITEA_API_URL=${GITEA_API_URL}" >> $GITHUB_OUTPUT
        echo "GITEA_REPO=${GITEA_REPO}" >> $GITHUB_OUTPUT
        echo "GITEA_OWNER=${GITEA_OWNER}" >> $GITHUB_OUTPUT

    - name: Create Gitea Release
      env:
        GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
        GITEA_API_URL: ${{ steps.gitea_url.outputs.GITEA_API_URL }}
        GITEA_REPO: ${{ steps.gitea_url.outputs.GITEA_REPO }}
        GITEA_OWNER: ${{ steps.gitea_url.outputs.GITEA_OWNER }}
      run: |
        # Debug Token (nur Länge ausgeben für Sicherheit)
        echo "Debug: Token length: ${#GITEA_TOKEN}"
        if [ -z "$GITEA_TOKEN" ]; then
          echo "Error: GITEA_TOKEN is empty"
          exit 1
        fi

        VERSION=${{ steps.get_version.outputs.VERSION }}
        cd .pio/build/esp32dev
        
        # Debug-Ausgaben
        echo "Debug: API URL: ${GITEA_API_URL}"
        echo "Debug: Repository: ${GITEA_OWNER}/${GITEA_REPO}"
        
        # Erstelle zuerst den Release ohne Dateien
        echo "Debug: Creating release..."
        RELEASE_DATA="{\"tag_name\":\"v${VERSION}\",\"name\":\"v${VERSION}\",\"body\":\"${{ steps.release_notes.outputs.CHANGES }}\"}"
        
        RELEASE_RESPONSE=$(curl -s -w "\n%{http_code}" \
          -X POST \
          -H "Authorization: token ${GITEA_TOKEN}" \
          -H "Content-Type: application/json" \
          -d "${RELEASE_DATA}" \
          "${GITEA_API_URL}/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}/releases")
        
        RELEASE_STATUS=$(echo "$RELEASE_RESPONSE" | tail -n1)
        RELEASE_BODY=$(echo "$RELEASE_RESPONSE" | head -n -1)
        
        if [ "$RELEASE_STATUS" != "201" ]; then
          echo "Error: Failed to create release"
          echo "Response: $RELEASE_BODY"
          exit 1
        fi
        
        # Extrahiere die Release-ID aus der Antwort
        RELEASE_ID=$(echo "$RELEASE_BODY" | grep -o '"id":[0-9]*' | cut -d':' -f2)
        
        # Lade die Dateien einzeln hoch
        for file in upgrade_filaman_firmware_v${VERSION}.bin upgrade_filaman_website_v${VERSION}.bin filaman_full_${VERSION}.bin; do
          if [ -f "$file" ]; then
            echo "Debug: Uploading $file..."
            UPLOAD_RESPONSE=$(curl -s -w "\n%{http_code}" \
              -X POST \
              -H "Authorization: token ${GITEA_TOKEN}" \
              -H "Content-Type: application/octet-stream" \
              --data-binary @"$file" \
              "${GITEA_API_URL}/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}/releases/${RELEASE_ID}/assets?name=${file}")
            
            UPLOAD_STATUS=$(echo "$UPLOAD_RESPONSE" | tail -n1)
            if [ "$UPLOAD_STATUS" != "201" ]; then
              echo "Warning: Failed to upload $file"
              echo "Response: $(echo "$UPLOAD_RESPONSE" | head -n -1)"
            else
              echo "Successfully uploaded $file"
            fi
          fi
        done
