name: Publish aai-embed to NPM

on:
  push:
    branches:
      - a-main
  workflow_dispatch:
    inputs:
      version_override:
        description: 'Version override (optional, e.g., 1.2.3)'
        required: false

jobs:
  publish-aai-embed:
    name: Build and Publish aai-embed
    runs-on: ubuntu-latest
    permissions:
      contents: write
      packages: write
      id-token: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Install pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 9.15.9

      - name: Setup Git
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"

      - name: Determine version bump
        id: bump
        run: |
          # Check if there are any tags
          if git tag -l | grep -q .; then
            LAST_TAG=$(git describe --tags --abbrev=0)
            echo "Last tag: $LAST_TAG"
            COMMITS=$(git log --pretty=format:"%s" $LAST_TAG..HEAD)
          else
            echo "No tags found. This is the first version."
            COMMITS=$(git log --pretty=format:"%s")
          fi

          echo "Commits since last tag:"
          echo "$COMMITS"

          # Determine version bump type based on commit messages
          BUMP_TYPE="patch"
          echo "$COMMITS" | grep -i -E '\b(BREAKING|MAJOR)\b' > /dev/null && BUMP_TYPE="major"
          if [ "$BUMP_TYPE" == "patch" ]; then
            echo "$COMMITS" | grep -i -E '\b(feat|feature|minor)\b' > /dev/null && BUMP_TYPE="minor"
          fi

          echo "bump_type=$BUMP_TYPE" >> $GITHUB_OUTPUT
          echo "Determined version bump: $BUMP_TYPE"

      - name: Bump version
        id: version
        run: |
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          echo "Current version: $CURRENT_VERSION"

          # Use manual version if provided
          if [ -n "${{ github.event.inputs.version_override }}" ]; then
            NEW_VERSION="${{ github.event.inputs.version_override }}"
            npm version $NEW_VERSION --no-git-tag-version --allow-same-version
          else
            BUMP_TYPE="${{ steps.bump.outputs.bump_type }}"
            npm version $BUMP_TYPE --no-git-tag-version
            NEW_VERSION=$(node -p "require('./package.json').version")
          fi

          echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
          echo "New version: $NEW_VERSION"

      - name: Update package metadata
        run: |
          # Update package name to scoped name
          node -e "const pkg = require('./package.json'); pkg.name = 'aai-embed'; require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));"

          # Add publishConfig
          node -e "const pkg = require('./package.json'); pkg.publishConfig = { access: 'public' }; require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));"

          # Add repository
          node -e "const pkg = require('./package.json'); pkg.repository = { type: 'git', url: 'git+https://github.com/the-answerai/chat-embed.git' }; require('fs').writeFileSync('package.json', JSON.stringify(pkg, null, 2));"

      - name: Install dependencies
        run: pnpm install

      - name: Build package
        run: pnpm build

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

      - name: Commit version bump
        run: |
          NEW_VERSION="${{ steps.version.outputs.new_version }}"

          # Commit the version bump back to the repo
          git add package.json
          git commit -m "chore: bump version to v${NEW_VERSION} [skip ci]" || echo "No changes to commit"

          echo "Version bump committed"

      - name: Create and push Git tag
        run: |
          NEW_VERSION="v${{ steps.version.outputs.new_version }}"
          echo "Creating tag $NEW_VERSION"

          if ! git tag -l | grep -q "^$NEW_VERSION$"; then
            git tag -a $NEW_VERSION -m "Release $NEW_VERSION"
            echo "Tag $NEW_VERSION created"
          else
            echo "Tag $NEW_VERSION already exists, skipping tag creation"
          fi

      - name: Push changes and tags
        run: |
          git push origin a-main
          git push origin --tags
          echo "Changes and tags pushed to origin"

      - name: Summary
        run: |
          echo "✅ Published aai-embed@${{ steps.version.outputs.new_version }} to npm"
          echo "✅ Created tag v${{ steps.version.outputs.new_version }}"
          echo ""
          echo "Next steps:"
          echo "1. In the parent repo (theanswer), update the submodule:"
          echo "   cd packages/embed && git pull origin a-main && cd ../.."
          echo "2. Commit the hash update:"
          echo "   git add packages/embed"
          echo "   git commit -m 'chore: update aai-embed to v${{ steps.version.outputs.new_version }}'"
          echo "3. Push to main - this will trigger aai-embed-react publishing"
          echo "   git push origin main"
