import os
from datetime import datetime

def backup_file(filepath, backup_dir):
    if not os.path.exists(filepath):
        return
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = os.path.basename(filepath)
    name, ext = os.path.splitext(filename)
    backup_name = f"{name}_{timestamp}{ext}"
    backup_path = os.path.join(backup_dir, backup_name)
    with open(filepath, "rb") as src, open(backup_path, "wb") as dst:
        dst.write(src.read())

    # Usuń starsze niż 5 backupów
    prefix = f"{name}_"
    all_backups = sorted([f for f in os.listdir(backup_dir) if f.startswith(prefix)], reverse=True)
    for old_file in all_backups[5:]:
        os.remove(os.path.join(backup_dir, old_file))