#!/usr/bin/env python3

__doc__ = "summarizes file extensions in parameters. traverses directories recursively"
__version__ = "1.0"

import sys, os
import collections, itertools

def main():
    import argparse
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--version", action="version", version=__version__)
    parser.add_argument("-a", "--alpha", action="store_true", help=
        "sort alphabetically by file extension instead of by popularity.")
    parser.add_argument("path", nargs="*")
    args = parser.parse_args()

    paths = args.path or ["."]

    counts = collections.Counter(
        get_extension(file)
        for file in itertools.chain(*(
            recursive_list(path) for path in paths
        ))
    )
    if args.alpha:
        # alphabetical by name, which is unique
        sorted_items = sorted(counts.items())
    else:
        # descending numeric, then ascending name
        sorted_items = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
    for (ext, count) in sorted_items:
        print("{}\t{}".format(count, ext))

def recursive_list(root):
    """
    yields all non-dir paths recursively relative to the root.
    somehow this is still not included in the standard library.
    """
    for dir, dirs, names in os.walk(root):
        for name in names:
            full_path = os.path.join(dir, name)
            yield os.path.relpath(full_path, root)

def get_extension(path):
    """
    returns file extension of provided path. examples:
    "a/b/c.d.e" -> ".e"
    "a/b/c" -> ""
    """
    try:
        return "." + os.path.basename(path).rsplit(".", 1)[1]
    except IndexError:
        return ""

if __name__ == "__main__":
    main()
