import re


def get_cv_params(std_text):
    """accepts stdout generated by cross-validate, returns the "Best Model" Objects
     for each validated fold as a list of lists of ints
     Example output for a cv with four folds and s=24 might be
     [[2, 0, 3, 2, 1, 0, 24],
     [2, 0, 1, 2, 1, 0, 24],
     [3, 0, 3, 0, 1, 1, 24],
     [1, 0, 0, 0, 1, 1, 24]]"""

    # build a match pattern that matches a string that looks like
    # this: 'Best model:  ARIMA(1,0,0)(0,1,1)[24]' from full contents of stdout
    # containing the ARIMA parameters from each fold in a cv search
    mod_pattern = re.compile(r'Best.*24]')

    # Match the pattern against stdout
    pat_list = (re.findall(mod_pattern, std_text))
    # Find all digits in each param in pat_list, save as list of params
    params = [re.findall(r'\d', pat_list[j]) for j, _ in enumerate(pat_list)]

    # this is a bit complicated: but does a fairly simple thing:
    # converts params from a list of lists filled with digits as individual strings of len 1
    # to a list of lists filled with digits as ints. since s=24 is specified in our AutoArima pipe
    # the last two digits are always 2 and 4, we fix this by converting them both to 24 and
    # removing the last digit, converting a list like ['2', '0', '3', '2', '1', '0', '2', '4']
    # to for example [2, 0, 3, 2, 1, 0, 24], which we can feed as SARIMA params
    params = [[int(param[p]) if (p < len(param) - 2) else 24 for p,
               _ in enumerate(param)][:-1] for param in params]

    return params