name: Publish to MCP Registry

on:
  push:
    tags: ["v*"]
  workflow_dispatch:

jobs:
  publish:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    permissions:
      id-token: write
      contents: read

    steps:
      - name: Checkout code
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Setup Node.js
        uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
        with:
          node-version: "20"
          registry-url: "https://registry.npmjs.org"
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Run smoke tests
        run: npm run test:smoke
        continue-on-error: true

      - name: Run linting
        run: npm run lint

      - name: Build package
        run: npm run build

      - name: Extract version from tag
        id: version
        env:
          EVENT_NAME: ${{ github.event_name }}
          REF_NAME: ${{ github.ref }}
        run: |
          if [[ "$EVENT_NAME" == "push" && "$REF_NAME" == refs/tags/* ]]; then
            VERSION=${GITHUB_REF#refs/tags/v}
          else
            VERSION=$(node -p "require('./package.json').version")
          fi
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Publishing version: $VERSION"

      - name: Update server.json version
        env:
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          jq --arg v "$VERSION" '.version = $v | .packages[] |= if .registryType == "npm" then .version = $v else . end' server.json > tmp && mv tmp server.json
          echo "Updated server.json:"
          cat server.json

      - name: Publish to npm
        run: npm publish
        continue-on-error: true
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Install MCP Publisher
        run: |
          curl -L "https://github.com/modelcontextprotocol/registry/releases/download/v1.4.0/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher
          chmod +x mcp-publisher

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

      - name: Publish to MCP Registry
        run: ./mcp-publisher publish

      - name: Verify publication
        if: ${{ always() }}
        run: |
          echo "Waiting for registry to update..."
          sleep 30
          curl -s "https://registry.modelcontextprotocol.io/v0/servers?search=io.github.ChiR24/unreal-engine-mcp" | jq '.'
