name: Hotfix Release

on:
  workflow_dispatch:
    inputs:
      description:
        description: 'Brief description of the hotfix'
        required: true
      branch_name:
        description: 'Hotfix branch name (e.g., hotfix/critical-security-fix)'
        required: true

permissions:
  contents: write
  pull-requests: write

jobs:
  hotfix-release:
    runs-on: ubuntu-latest
    environment: production  # Requires maintainer approval
    steps:
      - name: Validate branch name
        run: |
          if [[ ! "${{ github.event.inputs.branch_name }}" =~ ^hotfix/ ]]; then
            echo "❌ Branch name must start with 'hotfix/'" >> $GITHUB_STEP_SUMMARY
            exit 1
          fi

      - name: Checkout hotfix branch
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.branch_name }}
          fetch-depth: 0

      - name: Setup Bun
        uses: oven-sh/setup-bun@v2
        with:
          bun-version: '1.3.1'

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

      - name: Calculate hotfix version (auto-patch bump)
        id: version
        run: |
          CURRENT_VERSION=$(node -p "require('./package.json').version")
          echo "Current version: $CURRENT_VERSION"
          
          # Remove any pre-release suffix
          BASE_VERSION=$(echo $CURRENT_VERSION | sed 's/-.*$//')
          IFS='.' read -r -a VERSION_PARTS <<< "$BASE_VERSION"
          
          MAJOR="${VERSION_PARTS[0]}"
          MINOR="${VERSION_PARTS[1]}"
          PATCH="${VERSION_PARTS[2]}"
          
          # Hotfixes always bump patch version
          PATCH=$((PATCH + 1))
          NEW_VERSION="${MAJOR}.${MINOR}.${PATCH}"
          
          echo "new_version=$NEW_VERSION" >> $GITHUB_OUTPUT
          echo "Hotfix version will be: $NEW_VERSION"

      - name: Update version in all files
        run: |
          # Update package.json
          bun x json -I -f package.json -e "this.version='${{ steps.version.outputs.new_version }}'"
          
          # Update manifests
          bun x json -I -f manifest/chrome.json -e "this.version='${{ steps.version.outputs.new_version }}'"
          bun x json -I -f manifest/firefox.json -e "this.version='${{ steps.version.outputs.new_version }}'"
          bun x json -I -f safari/Mue\ Extension/Resources/manifest.json -e "this.version='${{ steps.version.outputs.new_version }}'"
          
          # Update Safari Xcode project
          sed -i "s/MARKETING_VERSION = [^;]*/MARKETING_VERSION = ${{ steps.version.outputs.new_version }}/g" safari/Mue.xcodeproj/project.pbxproj
          
          # Update constants.js
          sed -i "s/export const VERSION = '[^']*'/export const VERSION = '${{ steps.version.outputs.new_version }}'/" src/config/constants.js

      - name: Install dependencies
        run: bun install

      - name: Build extension
        run: bun run build
        env:
          NODE_ENV: production

      - name: Commit version bump
        run: |
          git add package.json manifest/chrome.json manifest/firefox.json safari/Mue\ Extension/Resources/manifest.json safari/Mue.xcodeproj/project.pbxproj src/config/constants.js
          git commit -m "chore: hotfix version bump to ${{ steps.version.outputs.new_version }}"

      - name: Merge hotfix to main
        run: |
          git fetch origin main
          git checkout main
          git merge --no-ff ${{ github.event.inputs.branch_name }} -m "fix: merge hotfix ${{ github.event.inputs.branch_name }} (#${{ steps.version.outputs.new_version }})"
          git tag -a "v${{ steps.version.outputs.new_version }}" -m "Hotfix v${{ steps.version.outputs.new_version }}: ${{ github.event.inputs.description }}"
          git push origin main
          git push origin "v${{ steps.version.outputs.new_version }}"

      - name: Generate changelog
        id: changelog
        run: |
          # Get commits from hotfix branch
          git checkout ${{ github.event.inputs.branch_name }}
          COMMITS=$(git log --pretty=format:"- %s (%h)" origin/main..${{ github.event.inputs.branch_name }})
          
          {
            echo "changelog<<EOF"
            echo "### 🚨 Hotfix"
            echo "${{ github.event.inputs.description }}"
            echo ""
            echo "### Changes"
            echo "$COMMITS"
            echo "EOF"
          } >> $GITHUB_OUTPUT

      - name: Create GitHub Release
        run: |
          git checkout main
          
          RELEASE_NOTES=$(cat <<EOF
          ## 🚨 Mue Hotfix v${{ steps.version.outputs.new_version }}
          
          **This is an emergency hotfix release.**
          
          ${{ steps.changelog.outputs.changelog }}
          
          ### 📦 Installation
          
          **Browser Extensions (will be updated shortly):**
          - **Chrome**: [Chrome Web Store](https://chromewebstore.google.com/detail/mue/bngmbednanpcfochchhgbkookpiaiaid)
          - **Edge**: [Edge Add-ons](https://microsoftedge.microsoft.com/addons/detail/mue/aepnglgjfokepefimhbnibfjekidhmja)
          - **Firefox**: [Firefox Add-ons](https://addons.mozilla.org/en-GB/firefox/addon/mue/)
          
          **Immediate Manual Installation:**
          - Download the ZIP file below for immediate deployment
          - Chrome/Edge: Load unpacked extension
          - Firefox: Install from about:debugging
          
          ---
          
          **⚠️ This hotfix should be submitted to stores immediately.**
          EOF
          )
          
          gh release create "v${{ steps.version.outputs.new_version }}" \
            "build/chrome-${{ steps.version.outputs.new_version }}.zip" \
            "build/firefox-${{ steps.version.outputs.new_version }}.zip" \
            --title "🚨 Hotfix v${{ steps.version.outputs.new_version }}" \
            --notes "$RELEASE_NOTES" \
            --latest
        env:
          GH_TOKEN: ${{ github.token }}

      - name: Back-merge to beta
        run: |
          git fetch origin beta
          git checkout beta
          git merge --no-ff main -m "chore: back-merge hotfix v${{ steps.version.outputs.new_version }} from main"
          git push origin beta

      - name: Back-merge to dev
        run: |
          git fetch origin dev
          git checkout dev
          git merge --no-ff main -m "chore: back-merge hotfix v${{ steps.version.outputs.new_version }} from main"
          git push origin dev

      - name: Output success summary
        run: |
          echo "## 🚨 Hotfix Released!" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "**Version**: v${{ steps.version.outputs.new_version }}" >> $GITHUB_STEP_SUMMARY
          echo "**Description**: ${{ github.event.inputs.description }}" >> $GITHUB_STEP_SUMMARY
          echo "**Release URL**: https://github.com/${{ github.repository }}/releases/tag/v${{ steps.version.outputs.new_version }}" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### ✅ Completed Actions" >> $GITHUB_STEP_SUMMARY
          echo "- [x] Merged hotfix to \`main\`" >> $GITHUB_STEP_SUMMARY
          echo "- [x] Created tag v${{ steps.version.outputs.new_version }}" >> $GITHUB_STEP_SUMMARY
          echo "- [x] Created GitHub Release" >> $GITHUB_STEP_SUMMARY
          echo "- [x] Back-merged to \`beta\` branch" >> $GITHUB_STEP_SUMMARY
          echo "- [x] Back-merged to \`dev\` branch" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "### 🚨 URGENT: Manual Steps Required" >> $GITHUB_STEP_SUMMARY
          echo "1. **Submit to stores IMMEDIATELY**:" >> $GITHUB_STEP_SUMMARY
          echo "   - Go to [Submit workflow](https://github.com/${{ github.repository }}/actions/workflows/submit.yml)" >> $GITHUB_STEP_SUMMARY
          echo "   - Run with tag: \`${{ steps.version.outputs.new_version }}\`" >> $GITHUB_STEP_SUMMARY
          echo "2. Update [muetab.com/blog/changelog](https://muetab.com/blog/changelog)" >> $GITHUB_STEP_SUMMARY
          echo "3. Notify users via Discord/social media" >> $GITHUB_STEP_SUMMARY
          echo "4. Delete hotfix branch: \`${{ github.event.inputs.branch_name }}\`" >> $GITHUB_STEP_SUMMARY
