name: Start Release

on:
  workflow_dispatch:
    inputs:
      custom_version:
        description: 'Custom version (optional, leave empty to use changesets)'
        required: false
        type: string

jobs:
  start-release:
    name: Create Release Branch
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.PAT_TOKEN }}

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install pnpm
        uses: pnpm/action-setup@v2
        with:
          version: 10

      - name: Configure git for HTTPS
        run: |
          git config --global url."https://github.com/".insteadOf "git@github.com:"
          git config --global url."https://".insteadOf "ssh://"

      - name: Install dependencies
        run: pnpm install

      - name: Configure Git
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Check for changesets
        id: changesets
        run: |
          # Check if there are any changesets
          if [ -z "$(ls -A .changeset/*.md 2>/dev/null | grep -v README)" ]; then
            echo "has_changesets=false" >> $GITHUB_OUTPUT
            echo "⚠️ No changesets found! Please add changesets before releasing."
            echo "Run: pnpm changeset"
          else
            echo "has_changesets=true" >> $GITHUB_OUTPUT
            echo "✅ Found changesets"
          fi

      - name: Version packages
        id: version
        env:
          GITHUB_TOKEN: ${{ secrets.PAT_TOKEN }}
        run: |
          if [ -n "${{ github.event.inputs.custom_version }}" ]; then
            # Use custom version
            VERSION="${{ github.event.inputs.custom_version }}"
            echo "Using custom version: $VERSION"
            
            # Update all workspace packages to custom version (skip root)
            pnpm recursive exec -- node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync('package.json')); p.version='$VERSION'; fs.writeFileSync('package.json', JSON.stringify(p, null, 2)+'\n');" || true
          else
            # Use changesets to calculate version
            pnpm changeset version
            
            # Get the new version from any updated package
            VERSION=$(find apps packages -name "package.json" | head -1 | xargs cat | jq -r '.version')
            
            # Root package.json doesn't need version since it's private and not published
            echo "✅ Package versions updated to $VERSION"
          fi
          
          echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
          echo "New version: $VERSION"

      - name: Create release branch
        run: |
          # Delete branch if exists (locally and remotely)
          git branch -D release/${{ steps.version.outputs.VERSION }} 2>/dev/null || true
          git push origin --delete release/${{ steps.version.outputs.VERSION }} 2>/dev/null || true
          
          # Create fresh branch
          git checkout -b release/${{ steps.version.outputs.VERSION }}

      - name: Commit version updates
        run: |
          git add .
          git commit -m "chore: release version ${{ steps.version.outputs.VERSION }}"

      - name: Push release branch
        run: |
          git push origin release/${{ steps.version.outputs.VERSION }}

      - name: Create Pull Request
        run: |
          BODY="## 🚀 Release v${{ steps.version.outputs.VERSION }}
          
          This PR was automatically created by the release workflow.
          
          ### 📝 Changes
          Changes are documented in the changesets.
          
          ### ✅ Checklist
          - [ ] Version bumped correctly
          - [ ] CHANGELOG updated
          - [ ] All tests pass
          - [ ] Build successful
          
          ### 📋 Release Process
          1. Review and merge this PR
          2. **Tag will be created automatically** after merge ✨
          3. The tag will trigger:
             - NPM package publishing
             - Docker image building  
             - Desktop app builds
             - GitHub release creation
          
          > 💡 No manual tag creation needed! The tag v${{ steps.version.outputs.VERSION }} will be created automatically when this PR is merged.
          
          ---
          _Generated by GitHub Actions_"
          
          gh pr create \
            --title "🚀 Release v${{ steps.version.outputs.VERSION }}" \
            --base main \
            --head release/${{ steps.version.outputs.VERSION }} \
            --body "$BODY"
        env:
          GH_TOKEN: ${{ secrets.PAT_TOKEN }}