name: Publish MCP to npm
on:
  push:
    branches: [main]
    paths:
      - '.mokogitea/mcp/**'

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          registry-url: 'https://registry.npmjs.org'

      - name: Install and build
        working-directory: .mokogitea/mcp
        run: |
          npm ci
          npx tsc

      - name: Check version change
        id: version
        working-directory: .mokogitea/mcp
        run: |
          LOCAL_VERSION=$(node -p "require('./package.json').version")
          NPM_VERSION=$(npm view @mokoconsulting/mokogitea-mcp version 2>/dev/null || echo "0.0.0")
          if [ "$LOCAL_VERSION" != "$NPM_VERSION" ]; then
            echo "changed=true" >> $GITHUB_OUTPUT
            echo "Version changed: $NPM_VERSION -> $LOCAL_VERSION"
          else
            echo "changed=false" >> $GITHUB_OUTPUT
            echo "Version unchanged: $LOCAL_VERSION"
          fi

      - name: Publish to npm
        if: steps.version.outputs.changed == 'true'
        working-directory: .mokogitea/mcp
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Publish to Gitea registry
        if: steps.version.outputs.changed == 'true'
        working-directory: .mokogitea/mcp
        run: |
          npm publish --registry ${{ github.server_url }}/api/packages/${{ github.repository_owner }}/npm/ \
            --//$(echo "${{ github.server_url }}" | sed 's|https://||')/api/packages/${{ github.repository_owner }}/npm/:_authToken=${{ secrets.MOKOGITEA_TOKEN }}
