from sympy.ntheory.factor_ import factorint, trailing


def _mr_safe_helper(_s):
    """
    Analyze a (new) mr_safe line for for total number of s's to
    be tested in _test along with the primes that must be cleared
    by a previous test.

    e.g.
    >>> from sympy.ntheory.primetest import _mr_safe_helper
    >>> print(_mr_safe_helper("if n < 170584961: return mr(n, [350, 3958281543])"))
     # [350, 3958281543] stot = 1 clear [2, 3, 5, 7, 29, 67, 679067]
    >>> print(_mr_safe_helper('return mr(n, [2, 379215, 457083754])'))
     # [2, 379215, 457083754] stot = 1 clear [2, 3, 5, 53, 228541877]
    """

    def _info(bases):
        """
        Analyze the list of bases, reporting the number of 'j-loops' that
        will be required if this list is passed to _test (stot) and the primes
        that must be cleared by a previous test.

        This info tag should then be appended to any new mr_safe line
        that is added so someone can easily see whether that line satisfies
        the requirements of mr_safe (see docstring there for details).
        """

        factors = []
        tot = 0
        for b in bases:
            tot += trailing(b-1)
            f = factorint(b)
            factors.extend(f)
        factors = sorted(set(factors))
        bases = sorted(set(bases))
        if bases == factors:
            factors = '== bases'
        else:
            factors = str(factors)
        return ' # %s stot = %s clear %s' % tuple(
                [str(x).replace('L','') for x in (list(bases), tot, factors)])

    _r = [int(_x) for _x in _s.split('[')[1].split(']')[0].split(',')]
    return _info(_r)