"""What is inside an app that PyInstaller made, and how big is each part?

    python inside.py made/hello_one_folder/dist/hello
    python inside.py made/pond_with_the_model_one_folder/dist/pond 15    the 15 biggest things

Give it the folder of a one-folder app. It adds up every file under each thing in
the folder, and under each thing in _internal, and prints the biggest ones.
"""
import pathlib
import sys


def megabytes(path):
    """The size of one file, or of everything in a folder, in MB."""
    if path.is_file():
        return path.stat().st_size / 1e6
    return sum(file.stat().st_size for file in path.rglob("*") if file.is_file()) / 1e6


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return 2
    app = pathlib.Path(sys.argv[1])
    most = int(sys.argv[2]) if len(sys.argv) > 2 else 10
    things = [thing for thing in app.iterdir() if thing.name != "_internal"]
    inner = app / "_internal"
    if inner.is_dir():
        things += list(inner.iterdir())
    sizes = sorted(((megabytes(thing), thing) for thing in things), reverse=True)
    total = megabytes(app)
    files = sum(1 for file in app.rglob("*") if file.is_file())
    print(f"{app.name}: {total:,.1f} MB in {files:,} files")
    for size, thing in sizes[:most]:
        where = thing.relative_to(app).as_posix() + ("/" if thing.is_dir() else "")
        print(f"   {size:8.1f} MB   {where}")
    rest = sum(size for size, thing in sizes[most:])
    if rest:
        print(f"   {rest:8.1f} MB   everything else ({len(sizes) - most} more things)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
