import sys
from pathlib import Path
import textwrap

from typing import Optional

def size_filtering(file: Optional[str] = None) -> None:
    if file and not Path(file).exists():
        fd = open(file, "w")
    else:
        fd = sys.stdout

    print("# This workflow is to filter out large objects from git history")
    print('pip install git-filter-repo', file=fd)
    print('git filter-repo --strip-blobs-bigger-than 10M', file=fd)
    print('x git push --force --all', file=fd)
    print('# NOTE:: this will revise history and people will need to re-checkout', file=fd)
    print(file=fd)
    print("# More surgical pruning of files", file=fd)
    print("git filter-repo --path-glob '*.zip' --path-glob '*.png' --path-glob '*.mp4' --invert-paths", file=fd)

def find_large(file: Optional[str] = None) -> None:
    cmd = textwrap.dedent("""\
        git rev-list --objects --all |
            git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' |
            grep '^blob' |
            sort -k3nr |
            head -20 |
            awk '{
                split("B KB MB GB TB", units);
                size=$3; unit_index=1;
                while (size>=1024 && unit_index<5) {
                    size/=1024; unit_index++;
                }
                printf "%s\\t%.2f %s\\t%s\\n", $2, size, units[unit_index], $4;
            }'
    """)

    header = "# Command to find large items in a git history\n"

    if file:
        with open(file, "w") as fd:
            fd.write(header)
            fd.write(cmd)
    else:
        sys.stdout.write(header)
        sys.stdout.write(cmd + "\n")
