import collections
import pathlib
import sys

import numpy as np

from .humansize import Humansize


def extat() -> None:
    totals = np.array([0, 0], "u8")
    ctr = collections.defaultdict(lambda: np.array([0, 0], "u8"))
    errors = dict()
    for line in sys.stdin:
        f = pathlib.Path(line.strip())
        ext = "<dir>" if f.is_dir() else f.suffix
        try:
            size = f.stat().st_size
            ctr[ext] += np.array([1, size], "u8")
            totals += np.array([1, size], "u8")
        except Exception as e:
            errors[f] = e

    total_size = Humansize(totals[1])

    for ext, (count, size) in sorted(ctr.items(), key=lambda x: x[1][0]):
        size = Humansize(size)
        count_perc = count * 100 / totals[0]
        size_perc = size.val * 100 / totals[1]
        print(
            f"{ext:7} {count:10}/{totals[0]} {count_perc:5.2f}% "
            f"{size:6.2f}/{total_size:.2f} {size_perc:5.2f}%"
        )

    if errors:
        n_errors = len(errors)
        print(f"ERROR: {n_errors} files did not stat")


if __name__ == "__main__":
    extat()
