name: Publish Memory Graph

on:
    push:
        branches:
            - main
        paths: 
            - "packages/memory-graph/package.json"

jobs:
    publish:
        runs-on: ubuntu-latest
        permissions: 
            contents: read
            id-token: write
        defaults:
            run:
                working-directory: ./packages/memory-graph
        steps:
            - name: Checkout
              uses: actions/checkout@v4

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

            - name: Upgrade npm for trusted publishing support
              run: npm install -g npm@latest

            - name: Setup Bun
              uses: oven-sh/setup-bun@v2

            - name: Install dependencies
              run: bun install

            - name: Check if version changed
              id: version-check
              run: |
                PACKAGE_NAME=$(jq -r '.name' package.json)
                LOCAL_VERSION=$(jq -r '.version' package.json)
                NPM_VERSION=$(npm view "$PACKAGE_NAME" version 2>/dev/null || echo "0.0.0")
                if [ "$LOCAL_VERSION" = "$NPM_VERSION" ]; then
                  echo "Version $LOCAL_VERSION already published, skipping."
                  echo "changed=false" >> "$GITHUB_OUTPUT"
                else
                  echo "Publishing $LOCAL_VERSION (npm has $NPM_VERSION)"
                  echo "changed=true" >> "$GITHUB_OUTPUT"
                fi

            - name: Build
              if: steps.version-check.outputs.changed == 'true'
              run: bun run build

            - name: Publish
              if: steps.version-check.outputs.changed == 'true'
              run: npm publish --access public --provenance
