name: Snapshot Release

on:
  workflow_dispatch:
    inputs:
      branch:
        description: "Branch to create snapshot from"
        required: true
        default: "main"

permissions:
  contents: write
  id-token: write

jobs:
  snapshot:
    name: Snapshot Release
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repo
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          ref: ${{ github.event.inputs.branch }}

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version-file: ".node-version"
          registry-url: "https://registry.npmjs.org"

      - name: Install pnpm
        uses: pnpm/action-setup@v5

      - name: Get pnpm store directory
        id: pnpm-cache
        shell: bash
        run: echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_OUTPUT

      - name: Cache pnpm dependencies
        uses: actions/cache@v5
        with:
          path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
          key: ${{ runner.os }}-pnpm-${{ hashFiles('**/pnpm-lock.yaml') }}
          restore-keys: |
            ${{ runner.os }}-pnpm-

      - name: Install Dependencies
        run: pnpm install

      - name: Build Packages
        run: pnpm packages:build

      - name: Version Snapshot
        run: pnpm changeset version --snapshot snapshot

      - name: Publish Snapshot
        run: pnpm changeset publish --tag snapshot --no-git-tag
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Snapshot Summary
        run: |
          echo "## Snapshot Release" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Snapshot released from branch: $BRANCH" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "Install with:" >> $GITHUB_STEP_SUMMARY
          echo '```bash' >> $GITHUB_STEP_SUMMARY
          echo 'pnpm add @cherrystudio/ai-core@snapshot' >> $GITHUB_STEP_SUMMARY
          echo 'pnpm add @cherrystudio/ai-sdk-provider@snapshot' >> $GITHUB_STEP_SUMMARY
          echo 'pnpm add @cherrystudio/extension-table-plus@snapshot' >> $GITHUB_STEP_SUMMARY
          echo '```' >> $GITHUB_STEP_SUMMARY
        env:
          BRANCH: ${{ github.event.inputs.branch }}
