# Publish to PyPI on version tags.
# This keeps PyPI publishing independent from GitHub release creation.

name: Publish to PyPI

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      publish_target:
        description: "Manual target"
        type: choice
        required: true
        default: testpypi
        options:
          - testpypi
          - pypi-token-fallback

jobs:
  build:
    name: Build distribution
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install build dependencies
        run: |
          python -m pip install --upgrade pip
          pip install build

      - name: Validate tag matches project version
        if: startsWith(github.ref, 'refs/tags/v')
        run: |
          python - <<'PY'
          import os
          import pathlib
          import tomllib

          data = tomllib.loads(pathlib.Path("pyproject.toml").read_text(encoding="utf-8"))
          version = data["project"]["version"]
          tag = os.environ["GITHUB_REF_NAME"].lstrip("v")
          if tag != version:
              raise SystemExit(f"Tag/version mismatch: tag={tag}, pyproject={version}")
          print(f"Tag/version check passed: {version}")
          PY

      - name: Build package
        run: python -m build

      - name: Store distribution packages
        uses: actions/upload-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

  publish-to-pypi:
    name: Publish to PyPI
    needs: build
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    outputs:
      trusted_ok: ${{ steps.trusted_result.outputs.trusted_ok }}
    environment:
      name: pypi
      url: https://pypi.org/p/mudabbir
    permissions:
      id-token: write  # Required for trusted publishing

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

      - name: Publish to PyPI
        id: trusted_publish
        continue-on-error: true
        uses: pypa/gh-action-pypi-publish@release/v1

      - name: Record trusted publish status
        id: trusted_result
        if: always()
        shell: bash
        run: |
          if [ "${{ steps.trusted_publish.outcome }}" = "success" ]; then
            echo "trusted_ok=true" >> "$GITHUB_OUTPUT"
          else
            echo "trusted_ok=false" >> "$GITHUB_OUTPUT"
          fi

  publish-to-pypi-token-on-failure:
    name: Publish to PyPI (Token Fallback on Trusted Failure)
    needs:
      - build
      - publish-to-pypi
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v') && needs.publish-to-pypi.outputs.trusted_ok != 'true'
    outputs:
      fallback_ok: ${{ steps.fallback_result.outputs.fallback_ok }}
    permissions:
      contents: read
    env:
      PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
      PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}

    steps:
      - name: Resolve token
        id: token
        shell: bash
        run: |
          TOK="${PYPI_API_TOKEN:-${PYPI_TOKEN:-}}"
          if [ -n "$TOK" ]; then
            echo "has_token=true" >> "$GITHUB_OUTPUT"
            echo "token=$TOK" >> "$GITHUB_OUTPUT"
          else
            echo "has_token=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Download distributions
        if: steps.token.outputs.has_token == 'true'
        uses: actions/download-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

      - name: Publish to PyPI via API token
        if: steps.token.outputs.has_token == 'true'
        id: fallback_publish
        continue-on-error: true
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          user: __token__
          password: ${{ steps.token.outputs.token }}

      - name: Record fallback publish status
        id: fallback_result
        if: always()
        shell: bash
        run: |
          if [ "${{ steps.token.outputs.has_token }}" = "true" ] && [ "${{ steps.fallback_publish.outcome }}" = "success" ]; then
            echo "fallback_ok=true" >> "$GITHUB_OUTPUT"
          else
            echo "fallback_ok=false" >> "$GITHUB_OUTPUT"
          fi

  publish-status:
    name: Publish Status Gate
    needs:
      - publish-to-pypi
      - publish-to-pypi-token-on-failure
    runs-on: ubuntu-latest
    if: always() && startsWith(github.ref, 'refs/tags/v')
    steps:
      - name: Ensure at least one publish path succeeded
        shell: bash
        run: |
          TRUSTED_OK='${{ needs.publish-to-pypi.outputs.trusted_ok }}'
          FALLBACK_OK='${{ needs.publish-to-pypi-token-on-failure.outputs.fallback_ok }}'
          if [ "$TRUSTED_OK" = "true" ] || [ "$FALLBACK_OK" = "true" ]; then
            echo "Publish path succeeded. trusted_ok=$TRUSTED_OK fallback_ok=$FALLBACK_OK"
            exit 0
          fi
          echo "No successful PyPI publish path."
          echo "trusted_ok=$TRUSTED_OK fallback_ok=$FALLBACK_OK"
          echo "Fix PyPI Trusted Publisher OR set secret PYPI_API_TOKEN/PYPI_TOKEN."
          exit 1

  publish-to-testpypi:
    name: Publish to TestPyPI
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'workflow_dispatch' && github.event.inputs.publish_target == 'testpypi'
    environment:
      name: testpypi
      url: https://test.pypi.org/project/mudabbir/
    permissions:
      id-token: write

    steps:
      - name: Download distributions
        uses: actions/download-artifact@v4
        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-to-pypi-token-fallback:
    name: Publish to PyPI (Token Fallback)
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'workflow_dispatch' && github.event.inputs.publish_target == 'pypi-token-fallback'
    permissions:
      contents: read

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

      - name: Publish to PyPI via API token
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          user: __token__
          password: ${{ secrets.PYPI_API_TOKEN }}
