name: Manual Release

# Complete manual release pipeline.
# Usage: Actions → "Manual Release" → Run workflow → choose bump type
# Does everything: bump version, sync platforms, create tag, build bundle,
# create GitHub Release, and open a PR to sync main.

on:
  workflow_dispatch:
    inputs:
      bump:
        description: 'Version bump type'
        required: true
        type: choice
        options:
          - patch
          - minor
          - major
      create_pr:
        description: 'Create PR to sync main with version bump?'
        required: true
        type: boolean
        default: true
      dry_run:
        description: 'Dry run — no commits, tags, releases, or PRs'
        required: false
        type: boolean
        default: false

permissions:
  contents: write
  pull-requests: write

jobs:
  release:
    name: Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: main
          fetch-depth: 0

      - uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install dependencies
        run: npm ci --ignore-scripts || npm install

      - name: Bump version and sync manifests
        run: |
          node scripts/versioning.mjs apply ${{ inputs.bump }}
          NEW_VERSION=$(node -p "require('./package.json').version")
          echo "NEW_VERSION=v${NEW_VERSION}" >> $GITHUB_ENV
          echo "Bumped to v${NEW_VERSION}"

      - name: Validate version consistency
        run: |
          V="${NEW_VERSION#v}"
          pkg=$(node -p "require('./package.json').version")
          root_plugin=$(node -p "require('./plugin.json').version")
          gh_plugin=$(node -p "require('./.github/plugin/plugin.json').version")
          [ "$pkg" = "$root_plugin" ] || { echo "❌ package.json ($pkg) ≠ plugin.json ($root_plugin)"; exit 1; }
          [ "$pkg" = "$gh_plugin" ]    || { echo "❌ package.json ($pkg) ≠ .github/plugin/plugin.json ($gh_plugin)"; exit 1; }
          [ "$pkg" = "$V" ]            || { echo "❌ package.json ($pkg) ≠ expected ($V)"; exit 1; }
          echo "✅ All versions match: $pkg"

      - name: Sync platforms
        run: npm run sync

      - name: Build release bundle
        run: npm run bundle

      - name: Generate release notes
        id: notes
        run: |
          TAG="${NEW_VERSION}"
          git-cliff --config cliff.toml --tag "$TAG" -o release_notes.md 2>/dev/null || \
          awk -v ver="$TAG" '
            /^\#\# \[/ { if (found) exit; if (index($0, ver)) found=1; next }
            found { print }
          ' CHANGELOG.md > release_notes.md
          if [ ! -s release_notes.md ]; then
            echo "See [CHANGELOG.md](CHANGELOG.md) for details." > release_notes.md
          fi
          echo "✅ Release notes ready"

      - name: Commit, tag and push
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

          git add -A
          git commit -m "chore(release): ${NEW_VERSION} [skip ci]"
          git tag "${NEW_VERSION}"

          # Push tag (tags bypass branch protection)
          if [ "${{ inputs.dry_run }}" = "true" ]; then
            echo "⏸️ DRY RUN — skipping tag push"
          else
            git push origin "${NEW_VERSION}"
            echo "✅ Tag ${NEW_VERSION} pushed"
          fi

      - name: Verify bundle exists
        run: |
          if [ ! -f "dist/pantheon-${NEW_VERSION}.tar.gz" ]; then
            echo "❌ Bundle missing at dist/pantheon-${NEW_VERSION}.tar.gz"
            echo "   Run 'npm run bundle' locally and retry"
            exit 1
          fi
          echo "✅ Bundle verified: $(du -h dist/pantheon-${NEW_VERSION}.tar.gz | cut -f1)"

      - name: Create GitHub Release
        if: inputs.dry_run != 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          TAG="${NEW_VERSION}"

          gh release create "${TAG}" \
            --title "Pantheon ${TAG}" \
            --notes-file release_notes.md \
            "dist/pantheon-${TAG}.tar.gz"

          echo "✅ Published Pantheon ${TAG}"

      - name: Create PR to main
        if: inputs.create_pr == true && inputs.dry_run != 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          TAG="${NEW_VERSION}"
          BRANCH="release/${TAG}"

          # Create and push release branch
          git checkout -b "${BRANCH}"
          git push origin "${BRANCH}"

          # Create PR — no auto-merge (manual review required)
          PR_URL=$(gh pr create \
            --base main \
            --head "${BRANCH}" \
            --title "chore(release): ${TAG}" \
            --body "Release PR for Pantheon **${TAG}**.\n\nThe GitHub Release has already been published. Merging this PR syncs main with the version bump and changelog update." \
            --json url --jq '.url' 2>/dev/null || \
          gh pr create \
            --base main \
            --head "${BRANCH}" \
            --title "chore(release): ${TAG}" \
            --body "Release PR for Pantheon **${TAG}**.\n\nThe GitHub Release has already been published. Merging this PR syncs main with the version bump and changelog update." 2>/dev/null || true)

          echo "PR created: $PR_URL"
