name: CI

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]
  workflow_dispatch:

jobs:
  check-and-publish:
    runs-on: ubuntu-latest
    environment: ${{ github.event_name == 'push' && 'pypi' || '' }}
    permissions:
      contents: write
      id-token: write
    steps:
      - uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Check Windows compatibility (ASCII-only)
        run: |
          python3 << 'EOF'
          import pathlib, sys
          errors = []
          for f in pathlib.Path('.').rglob('*'):
              if not f.is_file() or '.git' in f.parts: continue
              if f.suffix.lower() not in ['.py', '.yaml', '.yml']: continue
              try:
                  f.read_bytes().decode('ascii')
              except UnicodeDecodeError as e:
                  errors.append(f"{f}: non-ASCII byte {hex(e.object[e.start])} at position {e.start}")
              except Exception:
                  pass
          if errors:
              print("Files with non-ASCII characters (may break on Windows):")
              for e in errors: print(f"  {e}")
              sys.exit(1)
          EOF

      - name: Setup Python
        if: github.event_name == 'push'
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Check and bump version if needed
        if: github.event_name == 'push'
        id: version
        run: |
          local_version=$(grep '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/' | tr -d '\r')
          echo "Local version: $local_version"

          pypi_version=$(pip index versions comfy-3d-viewers 2>/dev/null | head -1 | grep -oP '\(\K[^)]+' || echo "0.0.0")
          echo "PyPI version: $pypi_version"

          higher=$(printf '%s\n%s' "$local_version" "$pypi_version" | sort -V | tail -1)

          if [ "$local_version" = "$pypi_version" ] || [ "$higher" = "$pypi_version" ]; then
            echo "Bumping: $local_version <= $pypi_version"
            IFS='.' read -r major minor patch <<< "$pypi_version"
            new_version="${major}.${minor}.$((patch + 1))"
            sed -i "s/^version = \".*\"/version = \"${new_version}\"/" pyproject.toml

            git config user.name "github-actions[bot]"
            git config user.email "github-actions[bot]@users.noreply.github.com"
            git add pyproject.toml
            git commit -m "Bump version to ${new_version} [skip ci]"
            git push
            echo "version=$new_version" >> $GITHUB_OUTPUT
          else
            echo "No bump needed: $local_version > $pypi_version"
            echo "version=$local_version" >> $GITHUB_OUTPUT
          fi

      - name: Create tag
        if: github.event_name == 'push'
        run: |
          version="${{ steps.version.outputs.version }}"
          git rev-parse "v$version" >/dev/null 2>&1 || { git tag "v$version" && git push origin "v$version"; }

      - name: Build package
        if: github.event_name == 'push'
        run: pip install build && python -m build

      - name: Create GitHub Release
        if: github.event_name == 'push'
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ steps.version.outputs.version }}
          name: v${{ steps.version.outputs.version }}
          generate_release_notes: true
          files: dist/*

      - name: Publish to PyPI
        if: github.event_name == 'push'
        uses: pypa/gh-action-pypi-publish@release/v1
