# typed: strict
# frozen_string_literal: true

require "uri"
require "utils/github/actions"
require "utils/github/api"
require "utils/output"

require "system_command"

# A module that interfaces with GitHub, code like PAT scopes, credential handling and API errors.
#
# @api internal
module GitHub
  extend SystemCommand::Mixin
  extend Utils::Output::Mixin

  MAX_PER_PAGE = 100

  WorkflowArray = T.type_alias { [T::Array[T::Hash[String, T.untyped]], String, String, String, String, T::Array[String], String] }

  sig { params(repo: String, filters: T.untyped).returns(T::Array[T::Hash[String, T.untyped]]) }
  def self.issues(repo:, **filters)
    uri = url_to("repos", repo, "issues")
    uri.query = URI.encode_www_form(filters)
    API.open_rest(uri)
  end

  sig { params(query: String, qualifiers: T.untyped).returns(T::Array[T::Hash[String, T.untyped]]) }
  def self.search_issues(query, **qualifiers)
    json = search("issues", query, **qualifiers)
    json.fetch("items", [])
  end

  sig { params(files: T::Hash[String, { content: String }], description: String, private: T::Boolean).returns(String) }
  def self.create_gist(files, description, private:)
    url = "#{API_URL}/gists"
    data = { "public" => !private, "files" => files, "description" => description }
    API.open_rest(url, data:, scopes: CREATE_GIST_SCOPES)["html_url"]
  end

  sig { params(repo: String, title: String, body: String).returns(String) }
  def self.create_issue(repo, title, body)
    url = "#{API_URL}/repos/#{repo}/issues"
    data = { "title" => title, "body" => body }
    API.open_rest(url, data:, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)["html_url"]
  end

  sig { params(repo: String, issue: T.any(String, Integer), body: String).returns(T::Hash[String, T.untyped]) }
  def self.create_issue_comment(repo, issue, body)
    url = "#{API_URL}/repos/#{repo}/issues/#{issue}/comments"
    API.open_rest(url, data: { body: }, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
  end

  sig { params(user: String, repo: String).returns(T::Hash[String, T.untyped]) }
  def self.repository(user, repo)
    API.open_rest(url_to("repos", user, repo))
  end

  sig {
    params(
      name:            String,
      tap:             T.nilable(Tap),
      tap_remote_repo: T.nilable(String),
      state:           T.nilable(String),
      type:            T.nilable(String),
    ).returns(T::Array[T::Hash[String, T.untyped]])
  }
  def self.issues_for_formula(name, tap: CoreTap.instance, tap_remote_repo: tap&.full_name, state: nil, type: nil)
    return [] unless tap_remote_repo

    search_issues(name, repo: tap_remote_repo, state:, type:, in: "title")
  end

  sig { returns(T::Hash[String, T.untyped]) }
  def self.user
    @user ||= T.let(API.open_rest("#{API_URL}/user"), T.nilable(T::Hash[String, T.untyped]))
  end

  sig { params(query: String, only: T.nilable(T.any(Symbol, String))).void }
  def self.print_pull_requests_matching(query, only = nil)
    open_or_closed_prs = search_issues(query, is: only, type: "pr", user: "Homebrew")

    open_prs, closed_prs = open_or_closed_prs.partition { |pr| pr["state"] == "open" }
                                             .map { |prs| prs.map { |pr| "#{pr["title"]} (#{pr["html_url"]})" } }

    if open_prs.present?
      ohai "Open pull requests"
      open_prs.each { |pr| puts pr }
    end

    if closed_prs.present?
      puts if open_prs.present?

      ohai "Closed pull requests"
      closed_prs.take(20).each { |pr| puts pr }

      puts "..." if closed_prs.count > 20
    end

    puts "No pull requests found for #{query.inspect}" if open_prs.blank? && closed_prs.blank?
  end

  sig { params(repo: String, org: T.nilable(String)).returns(T::Hash[String, T.untyped]) }
  def self.create_fork(repo, org: nil)
    url = "#{API_URL}/repos/#{repo}/forks"
    data = {}
    data[:organization] = org if org
    scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
    API.open_rest(url, data:, scopes:)
  end

  sig { params(repo: String, org: T.nilable(String)).returns(T::Boolean) }
  def self.fork_exists?(repo, org: nil)
    reponame = repo.split("/").fetch(1)

    username = org || API.open_rest(url_to("user")) { |json| json["login"] }
    json = API.open_rest(url_to("repos", username, reponame))

    return false if json["message"] == "Not Found"

    true
  end

  sig { params(repo: String, title: String, head: String, base: String, body: String).returns(T::Hash[String, T.untyped]) }
  def self.create_pull_request(repo, title, head, base, body)
    url = "#{API_URL}/repos/#{repo}/pulls"
    data = { title:, head:, base:, body:, maintainer_can_modify: true }
    scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
    API.open_rest(url, data:, scopes:)
  end

  # We default to private if we aren't sure or if the GitHub API is disabled.
  sig { params(full_name: String).returns(T::Boolean) }
  def self.private_repo?(full_name)
    uri = url_to "repos", full_name
    API.open_rest(uri) { |json| json.fetch("private", true) }
  end

  sig { params(main_params: String, qualifiers: T.untyped).returns(String) }
  def self.search_query_string(*main_params, **qualifiers)
    params = T.let(main_params.to_a, T::Array[T.nilable(String)])

    from = qualifiers.fetch(:from, nil)
    to = qualifiers.fetch(:to, nil)

    params << if from && to
      "created:#{from}..#{to}"
    elsif from
      "created:>=#{from}"
    elsif to
      "created:<=#{to}"
    end

    params += qualifiers.except(:args, :from, :to).flat_map do |key, value|
      Array(value).map { |v| "#{key.to_s.tr("_", "-")}:#{v}" }
    end

    "q=#{URI.encode_www_form_component(params.compact.join(" "))}&per_page=#{MAX_PER_PAGE}"
  end

  sig { params(subroutes: T.any(String, Integer)).returns(URI::Generic) }
  def self.url_to(*subroutes)
    URI.parse([API_URL, *subroutes].join("/"))
  end

  sig { params(entity: String, queries: String, qualifiers: T.untyped).returns(T::Hash[String, T.untyped]) }
  def self.search(entity, *queries, **qualifiers)
    uri = url_to "search", entity
    uri.query = search_query_string(*queries, **qualifiers)
    API.open_rest(uri)
  end

  sig {
    params(user: String, repo: String, pull_request: T.any(String, Integer), commit: T.nilable(String))
      .returns(T::Array[T::Hash[String, T.untyped]])
  }
  def self.repository_approved_reviews(user, repo, pull_request, commit: nil)
    query = <<~EOS
      { repository(name: "#{repo}", owner: "#{user}") {
          pullRequest(number: #{pull_request}) {
            reviews(states: APPROVED, first: 100) {
              nodes {
                author {
                  ... on User { email login name databaseId }
                  ... on Organization { email login name databaseId }
                }
                authorAssociation
                commit { oid }
              }
            }
          }
        }
      }
    EOS

    result = API.open_graphql(query, scopes: ["user:email"])
    reviews = result["repository"]["pullRequest"]["reviews"]["nodes"]

    valid_associations = %w[MEMBER OWNER]
    reviews.filter_map do |r|
      next if commit.present? && commit != r["commit"]["oid"]
      next unless valid_associations.include? r["authorAssociation"]

      email = r["author"]["email"].presence ||
              "#{r["author"]["databaseId"]}+#{r["author"]["login"]}@users.noreply.github.com"

      name = r["author"]["name"].presence ||
             r["author"]["login"]

      {
        "email" => email,
        "name"  => name,
        "login" => r["author"]["login"],
      }
    end
  end

  sig { params(user: String, repo: String, workflow: String, ref: String, inputs: T.untyped).void }
  def self.workflow_dispatch_event(user, repo, workflow, ref, **inputs)
    url = "#{API_URL}/repos/#{user}/#{repo}/actions/workflows/#{workflow}/dispatches"
    API.open_rest(url, data:           { ref:, inputs: },
                       request_method: :POST,
                       scopes:         CREATE_ISSUE_FORK_OR_PR_SCOPES)
  end

  sig { params(user: String, repo: String, tag: String).returns(T::Hash[String, T.untyped]) }
  def self.get_release(user, repo, tag)
    url = "#{API_URL}/repos/#{user}/#{repo}/releases/tags/#{tag}"
    API.open_rest(url, request_method: :GET)
  end

  sig { params(user: String, repo: String).returns(T::Hash[String, T.untyped]) }
  def self.get_latest_release(user, repo)
    url = "#{API_URL}/repos/#{user}/#{repo}/releases/latest"
    API.open_rest(url, request_method: :GET)
  end

  sig { params(user: String, repo: String, tag: String, previous_tag: T.nilable(String)).returns(T::Hash[String, T.untyped]) }
  def self.generate_release_notes(user, repo, tag, previous_tag: nil)
    url = "#{API_URL}/repos/#{user}/#{repo}/releases/generate-notes"
    data = { tag_name: tag }
    data[:previous_tag_name] = previous_tag if previous_tag.present?
    API.open_rest(url, data:, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
  end

  sig {
    params(user: String, repo: String, tag: String, id: T.nilable(String), name: T.nilable(String),
           body: T.nilable(String), draft: T::Boolean).returns(T::Hash[String, T.untyped])
  }
  def self.create_or_update_release(user, repo, tag, id: nil, name: nil, body: nil, draft: false)
    url = "#{API_URL}/repos/#{user}/#{repo}/releases"
    method = if id
      url += "/#{id}"
      :PATCH
    else
      :POST
    end
    data = {
      tag_name: tag,
      name:     name || tag,
      draft:,
    }
    data[:body] = body if body.present?
    API.open_rest(url, data:, request_method: method, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
  end

  sig {
    params(user: String, repo: String, id: Integer, local_file: String, remote_file: T.nilable(String)).void
  }
  def self.upload_release_asset(user, repo, id, local_file:, remote_file: nil)
    url = "https://uploads.github.com/repos/#{user}/#{repo}/releases/#{id}/assets"
    url += "?name=#{remote_file}" if remote_file
    API.open_rest(url, data_binary_path: local_file, request_method: :POST, scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
  end

  sig {
    params(
      user:             String,
      repo:             String,
      pull_request:     String,
      workflow_id:      String,
      artifact_pattern: String,
      head_sha:         T.nilable(String),
    ).returns(WorkflowArray)
  }
  def self.get_workflow_run(user, repo, pull_request, workflow_id: "tests.yml", artifact_pattern: "bottles{,_*}",
                            head_sha: nil)
    scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES

    # GraphQL unfortunately has no way to get the workflow yml name, so we need an extra REST call.
    workflow_api_url = "#{API_URL}/repos/#{user}/#{repo}/actions/workflows/#{workflow_id}"
    workflow_payload = API.open_rest(workflow_api_url, scopes:)
    workflow_id_num = workflow_payload["id"]

    query = <<~EOS
      query ($user: String!, $repo: String!, $pr: Int!) {
        repository(owner: $user, name: $repo) {
          pullRequest(number: $pr) {
            commits(last: 1) {
              nodes {
                commit {
                  oid
                  checkSuites(first: 100) {
                    nodes {
                      status,
                      workflowRun {
                        databaseId,
                        url,
                        workflow {
                          databaseId
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    EOS
    variables = {
      user:,
      repo:,
      pr:   pull_request.to_i,
    }
    result = API.open_graphql(query, variables:, scopes:)

    commit_node = result["repository"]["pullRequest"]["commits"]["nodes"].first
    check_suite = if commit_node.present?
      commit = commit_node["commit"]
      if head_sha.present? && commit["oid"].downcase != head_sha.downcase
        raise API::Error, "Pull request ##{pull_request} is at #{commit["oid"]} but expected #{head_sha}."
      end

      commit["checkSuites"]["nodes"].select do |suite|
        suite.dig("workflowRun", "workflow", "databaseId") == workflow_id_num
      end
    else
      []
    end

    [check_suite, user, repo, pull_request, workflow_id, scopes, artifact_pattern]
  end

  sig { params(workflow_array: WorkflowArray).returns(T::Array[String]) }
  def self.get_artifact_urls(workflow_array)
    check_suite, user, repo, pr, workflow_id, scopes, artifact_pattern = *workflow_array
    if check_suite.empty?
      raise API::Error, <<~EOS
        No matching check suite found for these criteria!
          Pull request: #{pr}
          Workflow:     #{workflow_id}
      EOS
    end

    last_check = check_suite.fetch(-1)
    status = last_check["status"].sub("_", " ").downcase
    if status != "completed"
      raise API::Error, <<~EOS
        The newest workflow run for ##{pr} is still #{status}!
          #{Formatter.url last_check["workflowRun"]["url"]}
      EOS
    end

    run_id = last_check["workflowRun"]["databaseId"]
    artifacts = []
    per_page = 50
    API.paginate_rest("#{API_URL}/repos/#{user}/#{repo}/actions/runs/#{run_id}/artifacts",
                      per_page:, scopes:) do |result|
      result = result["artifacts"]
      artifacts.concat(result)
      break if result.length < per_page
    end

    matching_artifacts =
      artifacts
      .group_by { |art| art["name"] }
      .select { |name| File.fnmatch?(artifact_pattern, name, File::FNM_EXTGLOB) }
      .map { |_, arts| arts.max_by { |art| art["created_at"] } }

    if matching_artifacts.empty?
      raise API::Error, <<~EOS
        No artifacts with the pattern `#{artifact_pattern}` were found!
          #{Formatter.url last_check["workflowRun"]["url"]}
      EOS
    end

    matching_artifacts.map { |art| art["archive_download_url"] }
  end

  sig { params(org: String, team: String).returns(T::Hash[String, String]) }
  def self.members_by_team(org, team)
    query = <<~EOS
        { organization(login: "#{org}") {
          teams(first: 100) {
            nodes {
              ... on Team { name }
            }
          }
          team(slug: "#{team}") {
            members(first: 100) {
              nodes {
                ... on User { login name }
              }
            }
          }
        }
      }
    EOS
    result = API.open_graphql(query, scopes: ["read:org", "user"])

    if result.dig("organization", "teams", "nodes").blank? || result.dig("organization", "team").blank?
      raise API::Error, "Could not access the team #{org}/#{team}. " \
                        "Please check that your GitHub account has access to the team and that your token has the " \
                        "required permissions."
    end

    result["organization"]["team"]["members"]["nodes"].to_h { |member| [member["login"], member["name"]] }
  end

  sig {
    params(user: String)
      .returns(
        T::Array[{
          closest_tier_monthly_amount: Integer,
          login:                       String,
          monthly_amount:              Integer,
          name:                        String,
        }],
      )
  }
  def self.sponsorships(user)
    query = <<~EOS
        query($user: String!, $after: String) { organization(login: $user) {
          sponsorshipsAsMaintainer(first: 100, after: $after) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              tier {
                monthlyPriceInDollars
                closestLesserValueTier {
                  monthlyPriceInDollars
                }
              }
              sponsorEntity {
                ... on Organization { login name }
                ... on User { login name }
              }
            }
          }
        }
      }
    EOS

    sponsorships = T.let([], T::Array[T::Hash[String, T.untyped]])
    errors = T.let([], T::Array[T::Hash[String, T.untyped]])

    API.paginate_graphql(query, variables: { user: }, scopes: ["user"], raise_errors: false) do |result|
      # Some organisations do not permit themselves to be queried through the
      # API like this and raise an error so handle these errors later.
      # This has been reported to GitHub.
      errors += result["errors"] if result["errors"].present?

      current_sponsorships = result.dig("data", "organization", "sponsorshipsAsMaintainer")
      # if `current_sponsorships` is blank, then there should be errors to report.
      next { "hasNextPage" => false } if current_sponsorships.blank?

      # The organisations mentioned above will show up as nil nodes.
      if (nodes = current_sponsorships["nodes"].compact.presence)
        sponsorships += nodes
      end

      current_sponsorships.fetch("pageInfo")
    end

    # Only raise errors if we didn't get any sponsorships.
    raise API::Error, errors.map { |e| e["message"] }.join("\n") if sponsorships.blank? && errors.present?

    sponsorships.map do |sponsorship|
      sponsor = sponsorship["sponsorEntity"]
      tier = sponsorship["tier"].presence || {}
      monthly_amount = tier["monthlyPriceInDollars"].presence || 0
      closest_tier = tier["closestLesserValueTier"].presence || {}
      closest_tier_monthly_amount = closest_tier["monthlyPriceInDollars"].presence || 0

      {
        name:                        sponsor["name"].presence || sponsor["login"],
        login:                       sponsor["login"],
        monthly_amount:,
        closest_tier_monthly_amount:,
      }
    end
  end

  sig { params(user: String, repo: String, ref: T.nilable(String)).returns(T.nilable(String)) }
  def self.get_repo_license(user, repo, ref: nil)
    url = "#{API_URL}/repos/#{user}/#{repo}/license"
    url += "?ref=#{ref}" if ref.present?
    response = API.open_rest(url)
    return unless response.key?("license")

    response["license"]["spdx_id"]
  rescue API::HTTPNotFoundError
    nil
  rescue API::AuthenticationFailedError => e
    raise unless e.message.match?(API::GITHUB_IP_ALLOWLIST_ERROR)
  end

  sig { params(name: String, version: T.nilable(String)).returns(Regexp) }
  def self.pull_request_title_regex(name, version = nil)
    return /(^|\s)#{Regexp.quote(name)}(:|,|\s|$)/i if version.blank?

    /(^|\s)#{Regexp.quote(name)}(:|,|\s)(.*\s)?#{Regexp.quote(version)}(:|,|\s|$)/i
  end

  sig {
    params(name: String, tap_remote_repo: String, state: T.nilable(String), version: T.nilable(String))
      .returns(T::Array[T::Hash[String, T.untyped]])
  }
  def self.fetch_pull_requests(name, tap_remote_repo, state: nil, version: nil)
    return [] if Homebrew::EnvConfig.no_github_api?

    regex = pull_request_title_regex(name, version)
    query = "is:pr #{name} #{version}".strip

    # Unauthenticated users cannot use GraphQL so use search REST API instead.
    # Limit for this is 30/minute so is usually OK unless you're spamming bump PRs (e.g. CI).
    if API.credentials_type == :none
      return issues_for_formula(query, tap_remote_repo:, state:).select do |pr|
        pr["html_url"].include?("/pull/") && regex.match?(pr["title"])
      end
    elsif state == "open" && ENV["GITHUB_REPOSITORY_OWNER"] == "Homebrew"
      # Try use PR API, which might be cheaper on rate limits in some cases.
      # The rate limit of the search API under GraphQL is unclear as it
      # costs the same as any other query according to /rate_limit.
      # The PR API is also not very scalable so limit to Homebrew CI.
      return fetch_open_pull_requests(name, tap_remote_repo, version:)
    end

    query += " repo:#{tap_remote_repo} in:title"
    query += " state:#{state}" if state.present?
    graphql_query = <<~EOS
      query($query: String!, $after: String) {
        search(query: $query, type: ISSUE, first: 100, after: $after) {
          nodes {
            ... on PullRequest {
              number
              title
              url
              state
            }
          }
          pageInfo {
            hasNextPage
            endCursor
          }
        }
      }
    EOS
    variables = { query: }

    pull_requests = []
    API.paginate_graphql(graphql_query, variables:) do |result|
      data = result["search"]
      pull_requests.concat(data["nodes"].select { |pr| regex.match?(pr["title"]) })
      data["pageInfo"]
    end
    pull_requests.map! do |pr|
      pr.merge({
        "html_url" => pr.delete("url"),
        "state"    => pr.fetch("state").downcase,
      })
    end
  rescue API::RateLimitExceededError => e
    opoo e.message
    pull_requests || []
  end

  sig {
    params(name: String, tap_remote_repo: String, version: T.nilable(String))
      .returns(T::Array[T::Hash[String, String]])
  }
  def self.fetch_open_pull_requests(name, tap_remote_repo, version: nil)
    return [] if tap_remote_repo.blank?

    # Bust the cache every three minutes.
    cache_expiry = 3 * 60
    cache_epoch = Time.now - (Time.now.to_i % cache_expiry)
    cache_key = "#{tap_remote_repo}_#{cache_epoch.to_i}"

    @open_pull_requests ||= T.let({}, T.nilable(T::Hash[String, T.untyped]))
    @open_pull_requests[cache_key] ||= begin
      query = <<~EOS
        query($owner: String!, $repo: String!, $states: [PullRequestState!], $after: String) {
          repository(owner: $owner, name: $repo) {
            pullRequests(states: $states, first: 100, after: $after) {
              nodes {
                number
                title
                url
              }
              pageInfo {
                hasNextPage
                endCursor
              }
            }
          }
        }
      EOS
      owner, repo = tap_remote_repo.split("/")
      variables = { owner:, repo:, states: ["OPEN"] }

      pull_requests = []
      API.paginate_graphql(query, variables:) do |result|
        data = result.dig("repository", "pullRequests")
        pull_requests.concat(data["nodes"])
        data["pageInfo"]
      end
      pull_requests
    end

    regex = pull_request_title_regex(name, version)
    @open_pull_requests[cache_key].select { |pr| regex.match?(pr["title"]) }
                                  .map { |pr| pr.merge("html_url" => pr.delete("url")) }
  rescue API::RateLimitExceededError => e
    opoo e.message
    pull_requests || []
  end

  # Check for duplicate pull requests that modify the same file.
  #
  # Exits the process on duplicates if `strict` or both `version` and
  # `official_tap`, otherwise warns.
  #
  # @api internal
  sig {
    params(
      name:            String,
      tap_remote_repo: String,
      file:            String,
      quiet:           T::Boolean,
      state:           T.nilable(String),
      version:         T.nilable(String),
      official_tap:    T::Boolean,
      strict:          T::Boolean,
    ).void
  }
  def self.check_for_duplicate_pull_requests(name, tap_remote_repo, file:, quiet: false, state: nil,
                                             version: nil, official_tap: true, strict: false)
    pull_requests = fetch_pull_requests(name, tap_remote_repo, state:, version:)

    pull_requests.select! do |pr|
      get_pull_request_changed_files(
        tap_remote_repo, pr["number"]
      ).any? { |f| f["filename"] == file }
    end
    return if pull_requests.blank?

    confidence = version ? "are" : "might be"
    duplicates_message = <<~EOS
      These #{"#{state} " if state}pull requests #{confidence} duplicates:
      #{pull_requests.map { |pr| "#{pr["title"]} #{pr["html_url"]}" }.join("\n")}
    EOS
    error_message = <<~EOS
      Duplicate PRs must not be opened.
      Manually open these PRs if you are sure that they are not duplicates (and tell us that in the PR).
    EOS

    if strict || (version && official_tap)
      odie <<~EOS
        #{duplicates_message.chomp}
        #{error_message}
      EOS
    elsif !official_tap
      opoo duplicates_message
    elsif quiet
      opoo error_message
    else
      opoo <<~EOS
        #{duplicates_message.chomp}
        #{error_message}
      EOS
    end
  end

  sig { params(tap_remote_repo: String, pull_request: T.any(String, Integer)).returns(T::Array[T.untyped]) }
  def self.get_pull_request_changed_files(tap_remote_repo, pull_request)
    files = []
    API.paginate_rest(url_to("repos", tap_remote_repo, "pulls", pull_request, "files")) do |result|
      files.concat(result)
    end
    files
  end

  sig {
    params(user: String, repo: String, pull_request: T.any(String, Integer), per_page: Integer)
      .returns(T::Array[String])
  }
  def self.pull_request_commits(user, repo, pull_request, per_page: MAX_PER_PAGE)
    pr_data = API.open_rest(url_to("repos", user, repo, "pulls", pull_request))
    commits_api = pr_data["commits_url"]
    commit_count = pr_data["commits"]
    commits = []

    if commit_count > API_MAX_ITEMS
      raise API::Error, "Getting #{commit_count} commits would exceed limit of #{API_MAX_ITEMS} API items!"
    end

    API.paginate_rest(commits_api, per_page:) do |result, page|
      commits.concat(result.map { |c| c["sha"] })

      return commits if commits.length == commit_count

      if result.empty? || page * per_page >= commit_count
        raise API::Error, "Expected #{commit_count} commits but actually got #{commits.length}!"
      end
    end

    commits
  end

  sig { params(user: String, repo: String, pull_request: T.any(String, Integer)).returns(T::Array[String]) }
  def self.pull_request_labels(user, repo, pull_request)
    pr_data = API.open_rest(url_to("repos", user, repo, "pulls", pull_request))
    pr_data["labels"].map { |label| label["name"] }
  end

  sig {
    params(user: String, repo: String, ref: String, version: Version,
           length: T.nilable(Integer)).returns(T.nilable(String))
  }
  def self.last_commit(user, repo, ref, version, length: nil)
    return if Homebrew::EnvConfig.no_github_api?

    require "utils/curl"
    result = Utils::Curl.curl_output(
      "--silent", "--head", "--location",
      "--header", "Accept: application/vnd.github.sha",
      url_to("repos", user, repo, "commits", ref).to_s
    )

    return unless result.status.success?

    commit = result.stdout[/^ETag: "(\h+)"/i, 1]
    return if commit.blank?

    if length
      return if commit.length < length

      commit = commit[0, length]
      odie "commit does not exist" unless commit

      # We return nil if the following fails as we currently don't have a way to
      # determine the reason for the failure. This means we can't distinguish a
      # GitHub API rate limit from a non-unique short commit where the latter
      # needs (n+1) or more characters to match `git rev-parse --short=n`.
      return if multiple_short_commits_exist?(user, repo, commit)
    end

    version.update_commit(commit)
    commit
  end

  sig { params(user: String, repo: String, commit: String).returns(T::Boolean) }
  def self.multiple_short_commits_exist?(user, repo, commit)
    return false if Homebrew::EnvConfig.no_github_api?

    require "utils/curl"
    result = Utils::Curl.curl_output(
      "--silent", "--head", "--location",
      "--header", "Accept: application/vnd.github.sha",
      "--output", File::NULL,
      # This is a Curl format token, not a Ruby one.
      # rubocop:disable Style/FormatStringToken
      "--write-out", "%{http_code}",
      # rubocop:enable Style/FormatStringToken
      url_to("repos", user, repo, "commits", commit).to_s
    )

    return true unless result.status.success?
    return true if (output = result.stdout).blank?

    output != "200"
  end

  MAXIMUM_OPEN_PRS = 15

  sig { params(tap: T.nilable(Tap)).returns(T::Boolean) }
  def self.too_many_open_prs?(tap)
    # We don't enforce unofficial taps.
    return false if tap.nil? || !tap.official?

    # BrewTestBot can open as many PRs as it wants.
    return false if ENV["HOMEBREW_TEST_BOT_AUTOBUMP"].present?

    odie "Cannot count PRs as `$HOMEBREW_NO_GITHUB_API` is set!" if Homebrew::EnvConfig.no_github_api?

    query = <<~EOS
      query($after: String) {
        viewer {
          login
          pullRequests(first: 100, states: OPEN, after: $after) {
            totalCount
            nodes {
              baseRepository {
                owner {
                  login
                }
              }
            }
            pageInfo {
              hasNextPage
              endCursor
            }
          }
        }
      }
    EOS
    puts

    homebrew_prs_count = 0

    begin
      API.paginate_graphql(query) do |result|
        data = result.fetch("viewer")
        github_user = data.fetch("login")

        # BrewTestBot can open as many PRs as it wants.
        return false if github_user.casecmp?("brewtestbot")

        pull_requests = data.fetch("pullRequests")
        return false if pull_requests.fetch("totalCount") < MAXIMUM_OPEN_PRS

        homebrew_prs_count += pull_requests.fetch("nodes").count do |node|
          node.dig("baseRepository", "owner", "login").casecmp?("homebrew")
        end
        return true if homebrew_prs_count >= MAXIMUM_OPEN_PRS

        pull_requests.fetch("pageInfo")
      end
    rescue => e
      # Ignore SAML access errors (https://github.com/Homebrew/brew/issues/18610) and related
      # IP allow list errors (https://github.com/orgs/Homebrew/discussions/6263)
      return false if e.message.include?("Resource protected by organization SAML enforcement") ||
                      e.message.include?("your IP address is not permitted to access this resource")

      raise
    end

    false
  end

  sig { params(organisation: String, from: String, to: String, verbose: T::Boolean).returns(T::Array[String]) }
  def self.organisation_repositories(organisation, from, to, verbose)
    from_date = Date.parse(from)
    to_date = Date.parse(to)

    rest_api_url = "#{GitHub::API_URL}/orgs/#{organisation}/repos"
    params = "type=sources"
    repositories = []
    GitHub::API.paginate_rest(rest_api_url, per_page: MAX_PER_PAGE, additional_query_params: params) do |result|
      repositories.concat(result)
    end
    repositories.filter_map do |repository|
      pushed_at = Date.parse(repository.fetch("pushed_at"))
      created_at = Date.parse(repository.fetch("created_at"))
      archived_at = Date.parse(repository.fetch("archived_at", from))
      full_name = repository.fetch("full_name")

      not_pushed = pushed_at < from_date
      not_created = created_at > to_date
      archived = archived_at < from_date

      if not_pushed || not_created || archived
        if verbose
          reasons = []
          reasons << "not pushed" if not_pushed
          reasons << "not created" if not_created
          reasons << "archived" if archived
          opoo "Repository #{full_name} #{reasons.join(", ")} from #{from_date} to #{to_date}. Skipping."
        end

        next
      end

      full_name
    end
  end

  sig {
    params(user: String, reviewed_by: String, from: T.nilable(String), to: T.nilable(String))
      .returns(T::Array[T::Hash[String, T.untyped]])
  }
  def self.search_approved_pull_requests_in_user_or_organisation(user, reviewed_by, from:, to:)
    search_issues("", is: "pr", review: "approved", user:, reviewed_by:, from:, to:)
  rescue GitHub::API::ValidationFailedError
    opoo "Couldn't search GitHub for PRs reviewed by #{reviewed_by}. Their profile might be private. Defaulting to 0."
    []
  end
end
