name: Upstream Sync

permissions:
  contents: write
  pull-requests: write # Required to create the PR

env:
  UPSTREAM_REPO: KuekHaoYang/KVideo
  UPSTREAM_BRANCH: main
  TARGET_BRANCH: main
  SYNC_BRANCH: upstream-sync-conflict # The branch name used if a conflict occurs

on:
  schedule:
    - cron: "0 */6 * * *"
  workflow_dispatch:

concurrency:
  group: upstream-sync-${{ github.repository }}
  cancel-in-progress: true

jobs:
  sync_latest_from_upstream:
    name: Sync latest commits from upstream repo
    runs-on: ubuntu-latest
    if: ${{ github.event.repository.fork }}

    steps:
      - name: Checkout target repo
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Required to access full history for merging

      - name: Sync and Merge (with PR Fallback)
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # 1. Configure Git
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

          # 2. Add Upstream Remote
          git remote add upstream "https://github.com/$UPSTREAM_REPO.git"
          git fetch upstream

          # 3. Attempt Merge
          echo "Attempting to merge upstream/$UPSTREAM_BRANCH into $TARGET_BRANCH..."
          
          if git merge upstream/$UPSTREAM_BRANCH; then
            echo "✅ Merge successful. Pushing changes..."
            git push origin $TARGET_BRANCH
          else
            echo "⚠️ Merge conflict detected. Aborting merge and creating PR..."
            git merge --abort

            # 4. Create a clean branch from upstream content
            git checkout -B $SYNC_BRANCH upstream/$UPSTREAM_BRANCH
            git push -f origin $SYNC_BRANCH

            # 5. Create Pull Request using GitHub CLI
            # The '|| true' prevents failure if the PR already exists
            gh pr create \
              --title "🚨 Manual Sync Required: Conflicts with Upstream" \
              --body "The automatic sync failed due to merge conflicts. This PR contains the latest upstream changes. Please resolve conflicts and merge manually." \
              --head $SYNC_BRANCH \
              --base $TARGET_BRANCH \
              || echo "PR already exists or could not be created."
          fi

      - name: Delete workflow runs
        uses: Mattraks/delete-workflow-runs@v2
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          repository: ${{ github.repository }}
          retain_days: 1
          keep_minimum_runs: 3
