import sre_parse
import re
import sre_constants


def sort_regex(shortcut_list):
    """
    Sort list in the following order
        1. The smallest maximum width of the regex
        2. The shortest regex string
        3. Regex string in alphabetical order (exception for '.', '?')
    """
    def ranking(item):
        """ Sorting function """
        regex = item['pattern'] + '$'
        regex_max_width = int(sre_parse.parse(regex).getwidth()[1])

        # Capture group should not impact length
        l = re.sub(r'[()]', '', item['pattern'])
        # two character specifier should not impact length
        l = re.sub(r'\\(\w)', '\1', l)
        length = len(l)

        # "\d" and "\w" placed before "."
        a = re.sub(r'[\\]', u"\U0010FFFD", item['pattern'])
        # "atf" before "(atf)" with "at." last
        a = re.sub(r'[(]', '', a)
        # Make sure regex symbols after letters or numbers
        alphabetical = re.sub(r'[.?*)]', u"\U0010FFFF", a)

        # patterns with infinite wildcards like \d+ or .*
        if regex_max_width >= int(sre_constants.MAXREPEAT):
            # in this case longer string more specific
            length = -length
        return (regex_max_width, length, alphabetical)

    return sorted(shortcut_list, key=ranking)