name: Publish to PyPI

on:
  release:
    types: [published]

permissions:
  contents: read

jobs:
  publish:
    name: Build and Publish to PyPI
    runs-on: ubuntu-latest
    environment:
      name: pypi
      url: https://pypi.org/project/massgen/

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

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

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

      - name: Get version from tag
        id: version
        run: |
          echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
          echo "VERSION_WITHOUT_V=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT

      - name: Build package
        run: |
          python -m build
          echo "📦 Built packages:"
          ls -la dist/

      - name: Verify package
        run: |
          twine check dist/*

      - name: Publish to PyPI
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: |
          twine upload dist/*

      - name: Trigger ReadTheDocs build
        run: |
          echo "📚 Triggering ReadTheDocs build..."
          RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
            -H "Authorization: Token ${{ secrets.READTHEDOCS_API_TOKEN }}" \
            https://readthedocs.org/api/v3/projects/massgendoc/versions/latest/builds/)

          HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
          BODY=$(echo "$RESPONSE" | sed '$d')

          if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
            echo "✅ ReadTheDocs build triggered successfully"
            echo "$BODY" | jq . || echo "$BODY"
          else
            echo "⚠️ ReadTheDocs build trigger returned HTTP $HTTP_CODE"
            echo "$BODY"
            # Don't fail the workflow - PyPI publish was successful
          fi

      - name: Post publish summary
        run: |
          echo "### 🎉 Published to PyPI Successfully!" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Version:** ${{ steps.version.outputs.VERSION }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**PyPI URL:** https://pypi.org/project/massgen/${{ steps.version.outputs.VERSION_WITHOUT_V }}/" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Docs:** https://massgendoc.readthedocs.io/" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Install:**" >> $GITHUB_STEP_SUMMARY
          echo '```bash' >> $GITHUB_STEP_SUMMARY
          echo "pip install massgen==${{ steps.version.outputs.VERSION_WITHOUT_V }}" >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY

      - name: Comment on release (on failure)
        if: failure()
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.repos.createCommitComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              commit_sha: context.sha,
              body: '❌ PyPI publish failed for this release. Check the [workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for details.'
            });
