name: Rule Based Reviewer Assignment

on:
  pull_request:
    types: [opened, edited, reopened]

jobs:
  assign_reviewers:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout the repository
        uses: actions/checkout@v3
        with:
          fetch-depth: 2

      - name: Get PR Author and Files Changed
        id: pr-info
        run: |
          # Get PR author
          echo "author=${{ github.event.pull_request.user.login }}" >> $GITHUB_ENV

          FILES_CHANGED=$(git diff --name-only HEAD^1 HEAD)

          CORE_FILES_CHANGED=""

          for FILE in $FILES_CHANGED; do
            echo "$FILE"
            if [[ ! "$FILE" =~ ^modules/[^/]+$ && ! "$FILE" =~ ^test/ && ! "$FILE" =~ ^integrationExamples/ ]]; then
              CORE_FILES_CHANGED="true"
              echo "Found a core change"
              break
            fi
          done

          if [ "$CORE_FILES_CHANGED" = "true" ]; then
            echo "core_change=true" >> $GITHUB_ENV
          else
            echo "core_change=false" >> $GITHUB_ENV
          fi

      - name: Assign Reviewers Based on Rules
        run: |
          # Load PR author and core change flag
          AUTHOR=${{ env.author }}
          CORE_CHANGE=${{ env.core_change }}
          echo "PR Author: $AUTHOR"
          echo "Core Change: $CORE_CHANGE"

          # Define groups
          PREBID_LEAD_ENG=("dgirardi")
          PREBID_ENG=("mkomorski")
          VOLUNTEERS=("gwhigs" "jefftmahoney" "jlquaccia" "jsnellbaker" "lksharma" "mmoschovas" "monis0395" "ncolletti" "osazos" "robertrmartinez" "Rothalack")
          MEMBERS=("3link" "abazylewicz-id5" "Abyfall" "adserver-online" "aleksatr" "alexander-kislitsyn" "AlexBVolcy" "AlexisBRENON" "alexsavelyev" "anastasiiapankivFS" "And1sS" "andre-gielow-ttd" "andreacastello" "andrewmarriott-aws" "andyblackwell" "ankit-thanekar007" "AntoxaAntoxic" "apukh-magnite" "arielmtk" "armando-fs" "AvinashKapre" "bbaresic" "BenBoonsiri" "bjorn-lw" "bokelley" "bretg" "bsardo" "Bugxyb" "bwnodak" "bwschmidt" "carlosfelix" "cciocov" "ccorbo" "chicoman25" "Compile-Ninja" "CTMBNara" "danielsao" "dbemiller" "dbridges12" "decaffeinatedio" "deepthivenkat" "el-chuck" "EmilNadimanov" "Enigo" "EvgeniiMunin" "farukcam" "fatihkaya84" "Fawke" "fliccione" "FlorentDancy" "florianerl" "freestarjonny" "Fuska1" "gargcreation1992" "Gershon-Brainin" "gilbertococchi" "github-matthieu-wipliez" "github-mickael-leclerc" "github-richard-depierre" "gmcgrath11" "gmiedlar-ox" "gpolaert" "guscarreon" "gwhigs" "harpere" "harrykingriches" "headertag" "heatherboveri" "hhhjort" "hjeong12" "ianwow" "idettman" "ikp4success" "IrinLen" "jaiminpanchal27" "jclou" "jdcauley" "jdelhommeau" "jdwieland8282" "jefftmahoney" "jeremy-greenbids" "jerrycychen" "JimTharioAmazon" "jlaso" "jlquaccia" "jlukas79" "jlustig11" "jney" "joedrew" "JoelPM" "johnwier" "JonGoSonobi" "jsnellbaker" "jsut" "justadreamer" "jwrosewell" "kamermans" "kapil-tuptewar" "katherynhrabik" "khang-vu-ttd" "kim-ng93" "kiril-kalchev" "kkharma" "kvnsw" "laurb9" "lcorrigall" "linux019" "lksharma" "lpagnypubstack" "lucor" "MaksymTeqBlaze" "mansinahar" "marki1an" "matthewlane" "MaxSmileWanted" "mbellomi" "mercuryyy" "michachen" "Miroku87" "mkendall07" "mmoschovas" "mmullin" "monis0395" "monisq" "muuki88" "mwilsonmagnite" "nassimlounadi" "ncolletti" "Net-burst" "nhedley" "nicgallardo" "nickllerandi" "NikhilGopalChennissery" "OlenaPostindustria" "ollyburns" "omerDotan" "onkarvhanumante" "optidigital-prebid" "oronno" "osazos" "osulzhenko" "ourcraig" "passani" "patmmccann" "paulborile" "pb-pete" "pdamoc" "peixunzhang" "piotrj-rtbh" "pkowalski-id5" "pm-abhinav-deshpande" "pm-asit-sahoo" "pm-azhar-mulla" "pm-harshad-mane" "pm-isha-bharti" "pm-jaydeep-mohite" "pm-kapil-tuptewar" "pm-komal-kumari" "pm-manasi-moghe" "pm-nikhil-vaidya" "pm-nitin-nimbalkar" "pm-nitin-shirsat" "pm-priyanka-bagade" "pm-priyanka-deshmane" "pm-saurabh-narkhede" "pm-shivam-soni" "pm-tanishka-vishwakarma" "pm-viral-vala" "Pratik3307" "protonate" "Pubmatic-Dhruv-Sonone" "PubMatic-OpenWrap" "Pubmatic-Supriya-Patil" "PyjamaWarrior" "QuentinGallard" "rBeefrz" "richmtk" "rickyblaha" "rimaburder-index" "rishi-parmar" "rmloveland" "robertrmartinez" "schernysh" "scr-oath" "sebastienrufiange" "sebmil-daily" "sergseven" "shahinrahbariasl" "ShriprasadM" "sigma-software-prebid" "SKOCHERI" "smenzer" "snapwich" "softcoder594" "sonali-more-xandr" "ssundahlTTD" "StavBenShlomoBrowsi" "stephane-ein" "teads-antoine-azar" "tej656" "teqblaze-yurii" "thyagram-aws" "ValentinPostindustria" "VeronikaSolovei9" "vivekyadav15" "vkimcm" "vraybaud" "wi101" "yq-yang-qin" "ysfbsf" "YuriyVelichkoPI" "yuva-inmobi-1" "zapo" "zhongshixi" "zxPhoenix")

          # Helpers
          pick_random_from_group() {
            local group=("$@")
            echo "${group[$RANDOM % ${#group[@]}]}"
          }

          pick_random_from_group_excluding() {
            local excludes_str="$1"
            shift
            local group=("$@")
            IFS=" " read -r -a excludes <<< "$excludes_str"

            local filtered=()
            for user in "${group[@]}"; do
              local skip=false
              for ex in "${excludes[@]}"; do
                if [[ "$user" == "$ex" ]]; then
                  skip=true
                  break
                fi
              done
              if [[ "$skip" == false ]]; then
                filtered+=("$user")
              fi
            done

            if [[ ${#filtered[@]} -eq 0 ]]; then
              echo ""
            else
              echo "${filtered[$RANDOM % ${#filtered[@]}]}"
            fi
          }

          REVIEWERS=()

          if [[ " ${PREBID_LEAD_ENG[@]} " =~ " ${AUTHOR} " ]]; then
            # Prebid Lead authored --> 2 Reviewers (Non-Lead Prebid + Volunteer)
            echo "Prebid Lead engineer authored the PR"
            REVIEWERS+=("$(pick_random_from_group "${PREBID_ENG[@]}")")
            REVIEWERS+=("$(pick_random_from_group "${VOLUNTEERS[@]}")")
          elif [[ " ${PREBID_ENG[@]} " =~ " ${AUTHOR} " ]]; then
            echo "Prebid engineer authored the PR"
            # Any other Prebid engineer authored --> 2 Reviewers (Lead Prebid + Volunteer)
            REVIEWERS+=("${PREBID_LEAD_ENG[0]}")
            REVIEWERS+=("$(pick_random_from_group "${VOLUNTEERS[@]}")")
          elif [[ "$CORE_CHANGE" == "true" ]]; then
            # Core rules apply to anyone else --> 2 Reviewers (Lead Prebid + Volunteer)
            echo "Core change detected, applying core rules"
            REVIEWERS+=("${PREBID_LEAD_ENG[0]}")
            REVIEWERS+=("$(pick_random_from_group_excluding "$AUTHOR" "${VOLUNTEERS[@]}")")
          elif [[ " ${MEMBERS[@]} " =~ " ${AUTHOR} " ]]; then
            echo "Non-core, member authored"
            # Non-core, member authored --> 1 Reviewer (Non-Lead Prebid)
            REVIEWERS+=("$(pick_random_from_group "${PREBID_ENG[@]}")")
          else
            echo "Non-core, non-member authored"
            # Non-core, non-member authored --> 1 Reviewer (Volunteer)
            REVIEWERS+=("$(pick_random_from_group_excluding "$AUTHOR" "${VOLUNTEERS[@]}")")
          fi

          echo "Reviewers selected: ${REVIEWERS[@]}"

          # Assign reviewers using gh api
          for R in "${REVIEWERS[@]}"; do
            echo "Assigning reviewer: $R"
            gh api \
              --method POST \
              -H "Accept: application/vnd.github+json" \
              -H "X-GitHub-Api-Version: 2022-11-28" \
              /repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/requested_reviewers \
              -f reviewers[]="$R"
          done

        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
