if (location.toString().includes('/pull-requests?create')) {
  const addOnly = async () => ['ADD']

  const allProjects = async () => fetch('https://git.add123.com/rest/api/latest/projects')
    .then(resp => resp.json())
    .then(async ({ values }) => values.map(project => project.key).filter(key => !['GRAV', 'TEST'].includes(key)))

  const names = [
    "Tam Nguyen",
    "David Daniel",
    "Nikalas Culvey",
    "Michael Mezzina",
    "Sage Vaillancourt",
    "John Cyr",
    "Adam Weizman",
    "Caleb Soper",
    "Rockey Liles",
    "Fernando Batista",
    "Kaitlyn Turner"
  ]

  const urlPrefix = 'https://git.add123.com/rest/api/latest'

  const getPullRequestsForProject = async project => {
    return await fetch(`${urlPrefix}/projects/${project}/repos?limit=999`)
      .then(resp => resp.json())
      .then(async (resp) => {
        if (!resp) {
          return []
        }
        const  { values: allRepos } = resp
        const prListUrls = allRepos.map(repo => `${urlPrefix}/projects/${project}/repos/${repo.slug}/pull-requests`)
        return (await Promise.all(
            prListUrls.map(async prListUrl => await fetch(prListUrl).then(resp => resp.json())))
        ).flatMap(({values}) => values)})
  }

  allProjects().then(async allProjects => {
    const allPullRequests = (await Promise.all(allProjects.map(async project => await getPullRequestsForProject(project)))).flatMap(a => a)
    const reviewerCounts = Object.fromEntries(names.map(name => [name, 0]))
    allPullRequests.forEach(({reviewers}) => {
      reviewers?.map(r => r.user.displayName)
        .filter(displayName => names.includes(displayName))
        //.filter(displayName => !["Chris Gamache", "Tom Keels", "Todd Sherrin", "Kelly Gunter", "Mark Garrett"].includes(displayName))
        .forEach(displayName => {
          reviewerCounts[displayName] ??= 0
          reviewerCounts[displayName] += 1
        })
    })
    const sortedCounts = Object.entries(reviewerCounts)
      .map(([name, count]) => ({name, count}))
      .toSorted((a, b) => a.count - b.count)
      const tryDisplay = () => setTimeout(() => {
        if (!sortedCounts.length || document.getElementById('reviewer-counts')) {
          return
        }
        const formBodyMain = document.querySelector('.create-pull-request-form .form-body .form-body-main')
        if (formBodyMain) {
          const countsParent = formBodyMain.lastChild.cloneNode(true)
          const reviewerCountsNode = document.createElement('ol')
          reviewerCountsNode.id = 'reviewer-counts'
          reviewerCountsNode.style.columns = '3'
          reviewerCountsNode.style.listStyle = 'none'
          reviewerCountsNode.style.paddingLeft = '2px'
          reviewerCountsNode.style.marginTop = 'auto'
          // reviewerCountsNode.style.lineHeight = '95%'
          reviewerCountsNode.style.fontSize = '0.9em'
          sortedCounts.slice(0, 6).forEach(({ name, count }) => {
            const listItem = document.createElement('li')
            listItem.innerText = `${count} PR${count !== 1 ? 's' : 's'} – ${name}`
            reviewerCountsNode.appendChild(listItem)
          })

          const projectHeadsUp = document.createElement('div')
          projectHeadsUp.innerText = 'Note: this list does not take into account any projects that you do not have access to. E.g. STA'
          reviewerCountsNode.appendChild(projectHeadsUp)

          const label = countsParent.querySelector('.form-label')
          label.innerText = 'Now reviewing'
          const message = countsParent.querySelector('.form-field-content')
          message.replaceChildren(reviewerCountsNode)
          formBodyMain.appendChild(countsParent)
        } else {
          tryDisplay()
        }
      }, 300)
      tryDisplay()
    })
}
