name: Hotfix

on:
  workflow_dispatch:
    inputs:
      version:
        description: 'Hotfix version (e.g., 1.9.1)'
        required: true
        type: string
      base_tag:
        description: 'Base tag to create hotfix from (e.g., v1.9.0)'
        required: true
        type: string

jobs:
  create-hotfix:
    name: Create Hotfix Branch
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.event.inputs.base_tag }}

      - 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
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Create hotfix branch
        run: |
          git checkout -b hotfix/${{ github.event.inputs.version }}
          git push origin hotfix/${{ github.event.inputs.version }}

      - name: Update versions
        run: |
          # Update root package.json
          node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync('package.json')); p.version='${{ github.event.inputs.version }}'; fs.writeFileSync('package.json', JSON.stringify(p, null, 2)+'\n');"
          
          # Update all workspace packages
          pnpm recursive exec -- node -e "const fs=require('fs'); const p=JSON.parse(fs.readFileSync('package.json')); p.version='${{ github.event.inputs.version }}'; fs.writeFileSync('package.json', JSON.stringify(p, null, 2)+'\n');" || true

      - name: Commit version updates
        run: |
          git add .
          git commit -m "chore: prepare hotfix ${{ github.event.inputs.version }}"
          git push origin hotfix/${{ github.event.inputs.version }}

      - name: Create Pull Request
        run: |
          BODY="## 🔥 Hotfix v${{ github.event.inputs.version }}
          
          This hotfix is based on tag: ${{ github.event.inputs.base_tag }}
          
          ### Issues Fixed
          - [ ] Issue #XXX: Description
          
          ### Testing
          - [ ] Hotfix tested locally
          - [ ] No regression in main functionality
          
          ### Deployment
          After merge:
          1. Tag will be created manually
          2. npm packages will be published
          3. Desktop apps will be built"
          
          gh pr create \
            --title "🔥 Hotfix v${{ github.event.inputs.version }}" \
            --base main \
            --head hotfix/${{ github.event.inputs.version }} \
            --body "$BODY"
        env:
          GH_TOKEN: ${{ secrets.PAT_TOKEN }}