import re


def _get_bnf_codes_and_sort_field_for_measure(measure):
    """
    Return `(bnf_codes, sort_field)` for a measure where `bnf_codes` is a list
    of BNF codes in the measure numerator (which may be empty for measures
    where this is not supported) and `sort_field` is the field in the API
    response by which results should be sorted
    """
    # For measures whose numerator sums one of the columns in the prescribing
    # table, we order the presentations by that column.  For other measures,
    # the columns used to calculate the numerator is not available here (it's
    # in BQ) so we order by total_items, which is the best we can do.
    #
    # Because the columns in BQ don't match the field names in our API (for
    # historical reasons) we need to pass them through a translation
    # dictionary.
    match = re.match(
        "SUM\((items|quantity|actual_cost)\) AS numerator", measure.numerator_columns
    )

    if match:
        sort_field = {
            "items": "total_items",
            "actual_cost": "cost",
            "quantity": "quantity",
        }[match.groups()[0]]
    else:
        sort_field = "total_items"
    if measure.numerator_is_list_of_bnf_codes:
        bnf_codes = measure.numerator_bnf_codes
    else:
        bnf_codes = []
    return bnf_codes, sort_field