import collections
import click


def fix_file(filename):
    """
    Slurps a file, and does various checks and fixes:
    * Sorts the file
    * Ensures column names are unique
    """
    with open(filename, "rU", encoding="utf-8") as rfile:
        lines = rfile.readlines()

    heads = collections.defaultdict(int)
    for item in lines[0].split(","):
        heads[item] += 1
    bad_heads = []
    for key, value in heads.items():
        if value > 1:
            bad_heads.append(key)

    if len(bad_heads) > 0:
        dupe_strs = "\n*  ".join(bad_heads)
        raise click.UsageError(f"CSV headers must have unique names. Duplicated column names:\n*  {dupe_strs}")

    return [lines[0], *sorted(lines[1:])]