///|
pub fn best_query(report : BenchmarkReport, metric : String) -> String {
  let pairs = sorted_query_metric_pairs(report, metric)
  if pairs.is_empty() {
    ""
  } else {
    pairs[0].0
  }
}

///|
pub fn worst_query(report : BenchmarkReport, metric : String) -> String {
  let pairs = sorted_query_metric_pairs(report, metric)
  if pairs.is_empty() {
    ""
  } else {
    pairs.sort_by(fn(a, b) {
      let by_value = a.1.compare(b.1)
      if by_value == 0 {
        a.0.compare(b.0)
      } else {
        by_value
      }
    })
    pairs[0].0
  }
}

///|
pub fn render_ranked_metric_table(
  report : BenchmarkReport,
  metric : String,
) -> String {
  let pairs = sorted_query_metric_pairs(report, metric)
  pairs.sort_by(fn(a, b) {
    let by_value = b.1.compare(a.1)
    if by_value == 0 {
      a.0.compare(b.0)
    } else {
      by_value
    }
  })
  let rows : Array[String] = ["Rank,Query,Metric,Value"]
  for index, pair in pairs {
    rows.push("\{index + 1},\{pair.0},\{metric},\{pair.1}")
  }
  rows.join("\n")
}

///|
pub fn metric_rank(
  report : BenchmarkReport,
  metric : String,
  query_id : String,
) -> Int {
  let pairs = sorted_query_metric_pairs(report, metric)
  for index, pair in pairs {
    if pair.0 == query_id {
      return index + 1
    }
  }
  0
}

///|
pub fn metric_rank_delta(
  baseline : BenchmarkReport,
  candidate : BenchmarkReport,
  metric : String,
  query_id : String,
) -> Int {
  metric_rank(baseline, metric, query_id) -
  metric_rank(candidate, metric, query_id)
}