import os
import sys
import shutil

CACHE_DIR = os.path.expanduser("~/.babicli/cache")


def ensure_cache():
    if not os.path.exists(CACHE_DIR):
        os.makedirs(CACHE_DIR, exist_ok=True)


def cache_size():
    total = 0
    for root, dirs, files in os.walk(CACHE_DIR):
        for f in files:
            total += os.path.getsize(os.path.join(root, f))
    return total


def human(n):
    for unit in ["B", "KB", "MB", "GB", "TB"]:
        if n < 1024:
            return f"{n:.2f} {unit}"
        n /= 1024
    return f"{n:.2f} PB"


def run():
    ensure_cache()

    if len(sys.argv) < 3:
        print("Cache commands:")
        print("  cache show      - list cached files")
        print("  cache size      - show cache size")
        print("  cache clear     - remove ALL cache data")
        return

    sub = sys.argv[2].lower()

    if sub == "show":
        print(f"== Cache Folder: {CACHE_DIR} ==\n")
        items = list(os.listdir(CACHE_DIR))

        if not items:
            print("(empty)")
            return

        for i in items:
            print(" -", i)
        return

    if sub == "size":
        s = cache_size()
        print("Cache size:", human(s))
        return

    if sub == "clear":
        shutil.rmtree(CACHE_DIR, ignore_errors=True)
        os.makedirs(CACHE_DIR, exist_ok=True)
        print("Cache cleared.")
        return

    print(f"Unknown cache command: {sub}")
    print("Try: cache show | cache size | cache clear")
