"""
Detect disk almost full and show biggest directories in /home.
"""

import os
import shutil

# Thresholds in percentage
WARN_LEVEL = 80   # geel
CRIT_LEVEL = 90   # rood


def format_gb(bytes_val: int) -> str:
    return f"{bytes_val / (1024 ** 3):.2f} GB"


def get_disk_usage(path: str = "/"):
    total, used, free = shutil.disk_usage(path)
    percent_used = used / total * 100 if total > 0 else 0
    return total, used, free, percent_used


def top_dirs(base: str, limit: int = 5):
    """
    Bepaal de grootste subdirectories in 'base' (alleen 1 niveau diep).
    """
    if not os.path.isdir(base):
        return []

    sizes = []
    for name in os.listdir(base):
        full = os.path.join(base, name)
        if not os.path.isdir(full):
            continue
        total_size = 0
        for root, dirs, files in os.walk(full):
            for f in files:
                try:
                    fp = os.path.join(root, f)
                    total_size += os.path.getsize(fp)
                except OSError:
                    pass
        sizes.append((name, total_size))

    sizes.sort(key=lambda x: x[1], reverse=True)
    return sizes[:limit]


def run():
    print("== DiskGuard ==")

    total, used, free, percent_used = get_disk_usage("/")

    print(f"Total: {format_gb(total)}")
    print(f"Used : {format_gb(used)}")
    print(f"Free : {format_gb(free)}")
    print(f"Usage: {percent_used:.1f}%")

    if percent_used >= CRIT_LEVEL:
        print("\nSTATUS: CRITICAL – disk almost full!")
    elif percent_used >= WARN_LEVEL:
        print("\nSTATUS: WARNING – disk usage high.")
    else:
        print("\nSTATUS: OK – disk usage normal.")
        return

    # Extra info bij hoge vulling: grootste dirs in /home
    home = os.path.expanduser("~")
    print(f"\nScanning biggest directories in {home} (this may take a moment)...")

    dirs = top_dirs(home, limit=5)
    if not dirs:
        print("No directories found or cannot scan.")
        return

    print("\nTop directories by size:")
    for name, size in dirs:
        print(f"  {name:<20} {format_gb(size)}")
