import collections


def _build_pep8_output(result):
    """
    Build the PEP8 output based on flake8 results.

    Results from both tools conform to the following format:

      <filename>:<line number>:<column number>: <issue code> <issue desc>

    with some issues providing more details in the description within
    parentheses.

    :param result: output from flake8
    :returns: list of flake8 output lines by error
    """
    # Aggregate individual errors by error
    _dict = collections.defaultdict(list)
    for line in str(result).split("\n"):
        if line:
            # Preserve only the code and brief description for each issue to
            # facilitate aggregating the results.  For example,
            #
            #    E501 line too long (178 > 79 characters) -> E501 line too long
            #    E303 too many blank lines (4) -> E303 too many blank lines
            parts = line.replace("(", ":").split(":")
            line_num, col_num, base_issue = parts[1:4]

            # Strip the whitespace around the base <issue code> <description>.
            #
            # Also restore the missing colon, stripped above, if the issue
            # was 'missing whitespace' surrounding a colon.
            issue = base_issue.strip()
            key = "{}:'".format(issue) if issue.endswith("after '") else issue

            _dict[key].append("{} ({})".format(line_num, col_num))

    # Build the output as one issue per entry
    return ["{}: {}".format(k, ", ".join(_dict[k])) for k in
            sorted(_dict.keys())]