name: Publish to PyPI

on:
  release:
    types: [published]

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

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

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

      - name: Build package
        run: python -m build

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

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/

  test-install:
    name: Test Install (Python ${{ matrix.python-version }})
    runs-on: ubuntu-latest
    needs: build
    strategy:
      matrix:
        python-version: ["3.10", "3.11", "3.12"]

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

      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

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

      - name: Test CLI
        run: |
          pretorin --help
          pretorin version

  publish:
    name: Publish to PyPI
    runs-on: ubuntu-latest
    needs: [build, test-install]
    environment: pypi
    permissions:
      id-token: write  # Required for trusted publishing

    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

      - name: Validate release tag matches package version
        env:
          RELEASE_TAG: ${{ github.event.release.tag_name }}
        run: |
          set -euo pipefail

          artifact_file="$(ls dist/pretorin-*.tar.gz | head -n 1 || true)"
          if [[ -z "$artifact_file" ]]; then
            echo "::error::No source distribution found in dist/."
            exit 1
          fi

          artifact_name="$(basename "$artifact_file")"
          package_version="${artifact_name#pretorin-}"
          package_version="${package_version%.tar.gz}"
          if [[ ! "$package_version" =~ ^[0-9][A-Za-z0-9.+-]*$ ]]; then
            echo "::error::Could not parse version from '${artifact_name}'."
            exit 1
          fi

          tag_version="${RELEASE_TAG#v}"

          if [[ "$package_version" != "$tag_version" ]]; then
            echo "::error::Release tag '${RELEASE_TAG}' does not match package version '${package_version}'."
            exit 1
          fi

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          skip-existing: true
        # No API token needed - uses OIDC trusted publishing

  publish-mcp-registry:
    name: Publish to MCP Registry
    runs-on: ubuntu-latest
    needs: publish
    permissions:
      id-token: write  # Required for GitHub OIDC authentication

    steps:
      - uses: actions/checkout@v4

      - name: Install mcp-publisher
        run: |
          curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_linux_amd64.tar.gz" | tar xz mcp-publisher

      - name: Authenticate to MCP Registry
        run: ./mcp-publisher login github-oidc

      - name: Sync MCP package version with release tag
        env:
          RELEASE_TAG: ${{ github.event.release.tag_name }}
        run: |
          set -euo pipefail
          python3 <<'PY'
          import json
          import os
          from pathlib import Path

          release_tag = os.environ["RELEASE_TAG"]
          release_version = release_tag[1:] if release_tag.startswith("v") else release_tag
          path = Path("server.json")
          data = json.loads(path.read_text(encoding="utf-8"))

          data["version"] = release_version
          for pkg in data.get("packages", []):
              if pkg.get("registryType") == "pypi":
                  pkg["version"] = release_version

          path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
          print(f"Updated server.json package version to {release_version}")
          PY

      - name: Validate server.json
        run: ./mcp-publisher validate

      - name: Publish to MCP Registry (retry on PyPI propagation)
        run: |
          set -euo pipefail

          max_attempts=10
          retry_delay_seconds=30

          for attempt in $(seq 1 "$max_attempts"); do
            set +e
            publish_output="$(./mcp-publisher publish 2>&1)"
            publish_status=$?
            set -e

            echo "$publish_output"

            if [[ "$publish_status" -eq 0 ]]; then
              exit 0
            fi

            if ! echo "$publish_output" | grep -q "PyPI package 'pretorin' not found"; then
              echo "::error::MCP publish failed with a non-retryable error."
              exit "$publish_status"
            fi

            if [[ "$attempt" -eq "$max_attempts" ]]; then
              echo "::error::MCP publish failed after ${max_attempts} attempts waiting for PyPI package availability."
              exit "$publish_status"
            fi

            echo "MCP registry could not resolve PyPI package yet (attempt ${attempt}/${max_attempts}). Retrying in ${retry_delay_seconds}s..."
            sleep "$retry_delay_seconds"
          done
