name: PyPI Release

# Only trigger on GitHub release publication, not on tag push.
# When a release is created, GitHub fires both 'release' and 'push' events.
# Using only 'release' prevents duplicate workflow runs.
on:
  release:
    types: [published]

# Cancel in-progress runs for the same tag
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  build:
    name: Build Distribution
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Validate semantic version tag
        id: version
        run: |
          TAG="${GITHUB_REF#refs/tags/}"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"

          # Validate semantic versioning format (v1.2.3 or v1.2.3-prerelease)
          if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.]+)?$ ]]; then
              echo "ERROR: Tag '$TAG' does not follow semantic versioning (vX.Y.Z or vX.Y.Z-prerelease)"
              exit 1
          fi

          # Extract version without 'v' prefix
          VERSION="${TAG#v}"
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"

          # Check if this is a prerelease
          if [[ "$TAG" =~ -[a-zA-Z0-9.]+ ]]; then
              echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
              IS_PRERELEASE="true"
          else
              echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
              IS_PRERELEASE="false"
          fi

          echo "Parsed version: $VERSION (prerelease: $IS_PRERELEASE)"

      - name: Install uv
        uses: astral-sh/setup-uv@v7
        with:
          version: "latest"

      - name: Set up Python
        run: uv python install 3.11

      - name: Install build dependencies
        run: uv sync --all-extras

      - name: Build package
        run: uv build

      - name: Verify built package version
        env:
          TAG_VERSION: ${{ steps.version.outputs.version }}
        run: |
          # Extract version from built wheel filename
          # Wheel format: {distribution}-{version}(-{build tag})?-{python}-{abi}-{platform}.whl
          shopt -s nullglob
          WHEEL_FILES=(dist/*.whl)
          if [ ${#WHEEL_FILES[@]} -eq 0 ]; then
              echo "ERROR: No wheel files found in dist/"
              exit 1
          fi
          WHEEL_FILE="${WHEEL_FILES[0]}"
          WHEEL_NAME=$(basename "$WHEEL_FILE")

          # Extract version from wheel filename (second field after splitting by -)
          # Handle PEP 440 version normalization (e.g., 0.5.0-beta -> 0.5.0b0)
          WHEEL_VERSION=$(echo "$WHEEL_NAME" | sed -E 's/^[^-]+-([^-]+)-.*/\1/')

          echo "Built wheel: $WHEEL_NAME"
          echo "Wheel version: $WHEEL_VERSION"
          echo "Expected tag version: $TAG_VERSION"

          # Normalize the tag version for comparison (PEP 440)
          # Convert common patterns: -alpha -> a0, -beta -> b0, -rc -> rc0
          # Also handle numbered variants: -alpha.1 -> a1, -beta.2 -> b2, -rc.3 -> rc3
          NORMALIZED_TAG=$(echo "$TAG_VERSION" | sed -E '
            s/-alpha\.([0-9]+)/a\1/
            s/-alpha/a0/
            s/-beta\.([0-9]+)/b\1/
            s/-beta/b0/
            s/-rc\.([0-9]+)/rc\1/
            s/-rc/rc0/
          ')

          echo "Normalized tag version: $NORMALIZED_TAG"

          if [ "$WHEEL_VERSION" != "$NORMALIZED_TAG" ]; then
              echo "ERROR: Built package version does not match git tag!"
              echo "  Wheel version: $WHEEL_VERSION"
              echo "  Expected (normalized): $NORMALIZED_TAG"
              echo ""
              echo "This may indicate an issue with dynamic versioning configuration."
              exit 1
          fi

          echo "Version verification passed!"

      - name: Check package
        run: |
          uv run twine check dist/*

      - name: List built artifacts
        run: ls -la dist/

      - name: Upload distribution artifacts
        uses: actions/upload-artifact@v6
        with:
          name: python-package-distributions
          path: dist/

  test-install:
    name: Test Installation
    needs: build
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [ubuntu-latest, macos-latest]
        python-version: ["3.11"]

    steps:
      - name: Set up Python ${{ matrix.python-version }}
        uses: actions/setup-python@v6
        with:
          python-version: ${{ matrix.python-version }}

      - name: Download distribution artifacts
        uses: actions/download-artifact@v7
        with:
          name: python-package-distributions
          path: dist/

      - name: Install package from wheel
        run: |
          pip install dist/*.whl

      - name: Verify installation
        run: |
          # Check that the package is installed
          pip show freecad-robust-mcp

          # Check that the CLI is available
          freecad-mcp --help || echo "CLI help check completed"

          # Check that the module can be imported
          python -c "import freecad_mcp; print(f'freecad-robust-mcp version: {freecad_mcp.__version__ if hasattr(freecad_mcp, \"__version__\") else \"unknown\"}')"

  publish-testpypi:
    name: Publish to TestPyPI
    needs: [build, test-install]
    runs-on: ubuntu-latest
    # Only publish alpha releases to TestPyPI for early testing.
    # Beta and RC releases go to PyPI since they are closer to stable.
    # This is intentional - do not change to contains(github.ref, '-').
    if: contains(github.ref, '-alpha')
    environment:
      name: testpypi
      url: https://test.pypi.org/p/freecad-robust-mcp
    permissions:
      id-token: write

    steps:
      - name: Download distribution artifacts
        uses: actions/download-artifact@v7
        with:
          name: python-package-distributions
          path: dist/

      - name: Publish to TestPyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository-url: https://test.pypi.org/legacy/

  publish-pypi:
    name: Publish to PyPI
    needs: [build, test-install]
    runs-on: ubuntu-latest
    # Publish beta, rc, and stable releases to PyPI (not alpha).
    # Alpha releases are too experimental for PyPI - they go to TestPyPI only.
    # This is intentional - do not change to !contains(github.ref, '-').
    if: ${{ !contains(github.ref, '-alpha') }}
    environment:
      name: pypi
      url: https://pypi.org/p/freecad-robust-mcp
    permissions:
      id-token: write

    steps:
      - name: Download distribution artifacts
        uses: actions/download-artifact@v7
        with:
          name: python-package-distributions
          path: dist/

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1

  create-github-release-assets:
    name: Add Assets to GitHub Release
    needs: [build, test-install]
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Download distribution artifacts
        uses: actions/download-artifact@v7
        with:
          name: python-package-distributions
          path: dist/

      - name: Upload to GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          files: dist/*
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  generate-summary:
    name: Generate Release Summary
    needs: [publish-pypi, publish-testpypi]
    if: always()
    runs-on: ubuntu-latest

    steps:
      - name: Generate release summary
        env:
          REF_NAME: ${{ github.ref_name }}
        run: |
          {
            echo "## PyPI Release Summary"
            echo ""
            echo "**Tag:** $REF_NAME"
            echo ""
          } >> "$GITHUB_STEP_SUMMARY"

          # Alpha releases go to TestPyPI only; beta, rc, and stable go to PyPI
          if [[ "$REF_NAME" == *"-alpha"* ]]; then
              {
                echo "**Type:** Alpha prerelease (published to TestPyPI only)"
                echo ""
                echo "### Install from TestPyPI"
                echo ""
                echo "\`\`\`bash"
                echo "pip install --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/ freecad-robust-mcp"
                echo "\`\`\`"
              } >> "$GITHUB_STEP_SUMMARY"
          elif [[ "$REF_NAME" == *"-beta"* ]]; then
              {
                echo "**Type:** Beta prerelease (published to PyPI)"
                echo ""
                echo "### Install from PyPI"
                echo ""
                echo "\`\`\`bash"
                echo "pip install freecad-robust-mcp"
                echo "\`\`\`"
                echo ""
                echo "Or with uv:"
                echo ""
                echo "\`\`\`bash"
                echo "uv pip install freecad-robust-mcp"
                echo "\`\`\`"
              } >> "$GITHUB_STEP_SUMMARY"
          elif [[ "$REF_NAME" == *"-rc"* ]]; then
              {
                echo "**Type:** Release candidate (published to PyPI)"
                echo ""
                echo "### Install from PyPI"
                echo ""
                echo "\`\`\`bash"
                echo "pip install freecad-robust-mcp"
                echo "\`\`\`"
                echo ""
                echo "Or with uv:"
                echo ""
                echo "\`\`\`bash"
                echo "uv pip install freecad-robust-mcp"
                echo "\`\`\`"
              } >> "$GITHUB_STEP_SUMMARY"
          else
              {
                echo "**Type:** Stable release (published to PyPI)"
                echo ""
                echo "### Install from PyPI"
                echo ""
                echo "\`\`\`bash"
                echo "pip install freecad-robust-mcp"
                echo "\`\`\`"
                echo ""
                echo "Or with uv:"
                echo ""
                echo "\`\`\`bash"
                echo "uv pip install freecad-robust-mcp"
                echo "\`\`\`"
              } >> "$GITHUB_STEP_SUMMARY"
          fi
