name: Publish to npm

on:
  push:
    branches:
      - main
    paths:
      - 'package.json'
      - 'src/**'
  workflow_dispatch:

jobs:
  check-version:
    runs-on: ubuntu-latest
    outputs:
      should-publish: ${{ steps.check.outputs.should-publish }}
      version: ${{ steps.check.outputs.version }}
    steps:
      - uses: actions/checkout@v4
      
      - name: Check if version changed
        id: check
        run: |
          PACKAGE_VERSION=$(node -p "require('./package.json').version")
          echo "version=$PACKAGE_VERSION" >> $GITHUB_OUTPUT
          
          # Check if this version is already published
          NPM_VERSION=$(npm view @louis030195/mcp-obsidian version 2>/dev/null || echo "0.0.0")
          
          if [ "$PACKAGE_VERSION" != "$NPM_VERSION" ]; then
            echo "New version detected: $PACKAGE_VERSION (npm has $NPM_VERSION)"
            echo "should-publish=true" >> $GITHUB_OUTPUT
          else
            echo "Version $PACKAGE_VERSION already published"
            echo "should-publish=false" >> $GITHUB_OUTPUT
          fi

  publish:
    needs: check-version
    if: needs.check-version.outputs.should-publish == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

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

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Run tests (if any)
        run: npm test || echo "No tests configured"
        continue-on-error: true

      - name: Publish to npm
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ needs.check-version.outputs.version }}
          name: Release v${{ needs.check-version.outputs.version }}
          body: |
            ## 🚀 Published to npm
            
            Package: [@louis030195/mcp-obsidian@${{ needs.check-version.outputs.version }}](https://www.npmjs.com/package/@louis030195/mcp-obsidian/v/${{ needs.check-version.outputs.version }})
            
            ### Installation
            \`\`\`bash
            npx -y @louis030195/mcp-obsidian
            \`\`\`
            
            ### Changes
            See [commit history](https://github.com/${{ github.repository }}/commits/v${{ needs.check-version.outputs.version }}) for details.
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
