name: Deploy

on:
  push:
    branches: [main]

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    permissions: {}

    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: latest
      - run: npm ci
      - run: npm test

  docker-smoke:
    name: Docker smoke test
    needs: test
    runs-on: ubuntu-latest
    permissions: {}

    steps:
      - uses: actions/checkout@v7

      - name: Build image
        run: docker build -t fonto-docs-smoke .

      - name: Smoke test
        run: |
          docker run -d --name fonto-docs-smoke -p 8080:8080 fonto-docs-smoke
          sleep 2
          curl --retry 5 --retry-delay 1 --retry-connrefused -sf http://localhost:8080/health
          docker stop fonto-docs-smoke

  deploy-gcp:
    name: Deploy to Cloud Run
    needs: [test, docker-smoke]
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write  # GCP Workload Identity Federation

    steps:
      - uses: actions/checkout@v7

      - name: Authenticate to Google Cloud
        uses: google-github-actions/auth@v3
        with:
          workload_identity_provider: projects/781852272029/locations/global/workloadIdentityPools/github/providers/github
          service_account: github-actions@fonto-docs-mcp.iam.gserviceaccount.com

      - name: Set up Cloud SDK
        uses: google-github-actions/setup-gcloud@v3

      - name: Configure Docker for Artifact Registry
        run: gcloud auth configure-docker europe-west4-docker.pkg.dev --quiet

      - name: Build and push image
        run: |
          IMAGE=europe-west4-docker.pkg.dev/fonto-docs-mcp/fonto-docs/server
          docker build -t "$IMAGE:${{ github.sha }}" -t "$IMAGE:latest" .
          docker push "$IMAGE:${{ github.sha }}"
          docker push "$IMAGE:latest"

      - name: Deploy to Cloud Run
        run: |
          gcloud run deploy fonto-docs-mcp \
            --image="europe-west4-docker.pkg.dev/fonto-docs-mcp/fonto-docs/server:${{ github.sha }}" \
            --region=europe-west4 \
            --project=fonto-docs-mcp \
            --startup-probe=httpGet.path=/health,initialDelaySeconds=0,periodSeconds=2,failureThreshold=3,timeoutSeconds=1 \
            --quiet

  notify-smithery:
    name: Notify Smithery
    runs-on: ubuntu-latest
    needs: deploy-gcp
    permissions: {}

    steps:
      - name: PATCH server metadata
        run: |
          curl --fail-with-body -s -X PATCH https://api.smithery.ai/servers/martinmiddel%2Ffonto-docs \
            -H "Authorization: Bearer ${{ secrets.SMITHERY_API_KEY }}" \
            -H "Content-Type: application/json" \
            -d '{
              "displayName": "Fonto Docs MCP",
              "description": "Makes Fonto documentation accessible to AI tools. Fetches the underlying DITA XML and converts it to Markdown on demand - bypassing the JavaScript SPA.",
              "homepage": "https://fonto-docs.elliat.nl",
              "repositoryUrl": "https://github.com/DrRataplan/fonto-docs-mcp",
              "license": "MIT"
            }'

  publish-mcp-registry:
    name: Publish to MCP Registry
    runs-on: ubuntu-latest
    needs: [deploy-gcp, release-npm]
    permissions:
      id-token: write
      contents: read

    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0

      - name: Sync version from git tag
        run: |
          VERSION=$(git tag --sort=-version:refname | head -1 | sed 's/^v//')
          jq --arg v "$VERSION" '.version = $v' server.json > server.tmp && mv server.tmp server.json

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

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

      - name: Publish to MCP Registry
        run: ./mcp-publisher publish || echo "Already published at this version, skipping."

  release-npm:
    name: Release to npm
    needs: test
    runs-on: ubuntu-latest
    permissions:
      contents: write        # semantic-release: push tags and create releases
      issues: write          # semantic-release: comment on issues
      pull-requests: write   # semantic-release: comment on PRs
      id-token: write        # npm OIDC token exchange

    steps:
      - uses: actions/checkout@v7
        with:
          fetch-depth: 0  # semantic-release needs full git history

      - uses: actions/setup-node@v7
        with:
          node-version: latest
          registry-url: https://registry.npmjs.org

      - run: npm ci

      - name: Obtain short-lived npm token via OIDC
        run: |
          OIDC_TOKEN=$(curl -fsSL \
            -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
            "${ACTIONS_ID_TOKEN_REQUEST_URL}&audience=https://token.actions.githubusercontent.com" \
            | jq -r '.value')
          NPM_TOKEN=$(curl -fsSL -X POST https://registry.npmjs.org/-/npm/v1/tokens/oidc \
            -H 'Content-Type: application/json' \
            -d "{\"oidcToken\":\"${OIDC_TOKEN}\"}" \
            | jq -r '.token')
          echo "::add-mask::$NPM_TOKEN"
          echo "NODE_AUTH_TOKEN=$NPM_TOKEN" >> "$GITHUB_ENV"

      - name: Release (semantic-release)
        run: npx semantic-release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          NPM_CONFIG_PROVENANCE: "true"
