from pathlib import Path
import dill
import time
import traceback


def load_session(path, use_backup=True):
    """
    Loads a session
    :param path: The session folder (labelled .ses) containng the session.dill and session.back file
    :param use_backup: If True, will attempt to load backup if main fails
    :return:
    """
    target = Path(path) / "session.dill"

    try:
        with open(target, "rb") as fp:
            return dill.load(fp)[0]
    except Exception as e:
        if use_backup:
            print(f"failed to load {target.name}. Reason:")
            target = target.with_suffix(".back")
            time.sleep(0.1)  # Get nicer print statements
            traceback.print_exc()
            time.sleep(0.1)  # Get nicer print statements
            print("Trying to load backup")
            with open(target, "rb") as fp:
                return dill.load(fp)[0]
        else:
            raise e