import os
import zipfile
from typing import List

from libs.osaf.osaf_core import OSAF_Core


def create_backup(osa : OSAF_Core, paths: List[str], backup_dir: str = None) -> str:
    """Create backup of important files"""
    if backup_dir is None:
        backup_dir = os.path.join(osa.master_workdir, 'backups')

    timestamp = osa.time.getNowForFileName()
    backup_file = os.path.join(backup_dir, f'backup_{timestamp}.zip')

    osa.files.mkdir(backup_dir, parents=True)

    with zipfile.ZipFile(backup_file, 'w') as zipf:
        for path in paths:
            if osa.files.exists(path):
                if osa.files.is_file(path):
                    zipf.write(path, os.path.basename(path))
                else:
                    for root, dirs, files in os.walk(path):
                        for file in files:
                            file_path = os.path.join(root, file)
                            arcname = os.path.relpath(file_path, start=os.path.dirname(path))
                            zipf.write(file_path, arcname)

    osa.log.i(f"Backup created: {backup_file}")
    return backup_file