---
name: Release

# yamllint disable-line rule:truthy
on:
  release:
    types:
      - published

env:
  DEFAULT_PYTHON: "3.13"

jobs:
  release:
    name: Releasing to PyPi
    runs-on: ubuntu-latest
    environment:
      name: release
      url: https://pypi.org/p/python-bsblan
    permissions:
      contents: write
      id-token: write
    steps:
      - name: ⤵️ Check out code from GitHub
        uses: actions/checkout@v6.0.1
      - name: 🏗 Set up uv
        uses: astral-sh/setup-uv@v7
        with:
          enable-cache: true
      - name: 🏗 Set up Python ${{ env.DEFAULT_PYTHON }}
        id: python
        uses: actions/setup-python@v6.1.0
        with:
          python-version: ${{ env.DEFAULT_PYTHON }}
      - name: 🏗 Install dependencies
        run: uv sync
      - name: 🏗 Set package version
        run: |
          version="${{ github.event.release.tag_name }}"
          version="${version,,}"
          version="${version#v}"
          sed -i '0,/version = ".*"/{s/version = ".*"/version = "'"${version}"'"/}' pyproject.toml
      - name: 🏗 Build package
        run: uv build
      - name: 🚀 Publish to PyPi
        uses: pypa/gh-action-pypi-publish@v1.13.0
        with:
          verbose: true
          print-hash: true
      - name: ✍️ Sign published artifacts
        uses: sigstore/gh-action-sigstore-python@v3.2.0
        with:
          inputs: ./dist/*.tar.gz ./dist/*.whl
          release-signing-artifacts: false
      - name: 🔍 Verify signature files
        run: |
          # Retry mechanism for file system sync
          max_retries=5
          retry_delay=2
          retries=0
          while [ $retries -lt $max_retries ]; do
            echo "Checking for signature files (attempt $((retries + 1))/$max_retries)..."
            if find ./dist -name "*.sigstore.json" -type f -exec echo "Found: {}" \; -exec ls -la {} \;; then
              echo "Signature files found and listed."
              break
            else
              echo "Files not ready, retrying in $retry_delay seconds..."
              sleep $retry_delay
              retries=$((retries + 1))
            fi
          done
          if [ $retries -eq $max_retries ]; then
            echo "Error: Signature files not found after $max_retries attempts."
            exit 1
          fi
          # Ensure files are not locked or being written to
          for file in ./dist/*.sigstore.json; do
            if [ -f "$file" ]; then
              echo "Checking file: $file"
              # Test file readability
              cat "$file" > /dev/null && echo "✓ File is readable" || echo "✗ File read error"
              # Ensure file handles are closed
              sync
            fi
          done
          # Poll for file system operations to complete
          max_wait_time=30
          wait_interval=2
          waited_time=0
          while [ $waited_time -lt $max_wait_time ]; do
            all_files_ready=true
            for file in ./dist/*.sigstore.json; do
              if [ -f "$file" ]; then
                # Test file readability
                if ! cat "$file" > /dev/null; then
                  echo "File $file is not readable yet."
                  all_files_ready=false
                  break
                fi
              else
                echo "File $file does not exist yet."
                all_files_ready=false
                break
              fi
            done
            if [ "$all_files_ready" = true ]; then
              echo "All files are ready."
              break
            fi
            echo "Waiting for files to be ready..."
            sleep $wait_interval
            waited_time=$((waited_time + wait_interval))
          done
          if [ $waited_time -ge $max_wait_time ]; then
            echo "Error: Files not ready after $max_wait_time seconds."
            exit 1
          fi
      - name: 📋 List signature files explicitly
        id: list-files
        run: |
          echo "signature_files<<EOF" >> $GITHUB_OUTPUT
          find ./dist -name "*.sigstore.json" -type f | tr '\n' '\0' | xargs -0 -I {} echo "{}"
          echo "EOF" >> $GITHUB_OUTPUT

          # Also create a space-separated list for the upload action
          FILES=$(find ./dist -name "*.sigstore.json" -type f | tr '\n' ' ')
          echo "files_list=$FILES" >> $GITHUB_OUTPUT
          echo "Found files: $FILES"
      - name: 📤 Upload signature files to release
        if: github.event_name == 'release' && github.event.action == 'published'
        run: |
          # Upload files individually to avoid Node.js file handle issues
          for file in ./dist/*.sigstore.json; do
            if [ -f "$file" ]; then
              echo "Uploading $file..."
              # Use GitHub CLI for more reliable uploads
              gh release upload ${{ github.event.release.tag_name }} "$file" --clobber
              if [ $? -ne 0 ]; then
                echo "✗ Failed to upload $file" >&2
                exit 1
              fi
              echo "✓ Uploaded $file"
              sleep 1  # Small delay between uploads
            fi
          done
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
