# -*- coding: utf8 -*-

"""Helper utilities for pickling cloud components."""

from __future__ import annotations

__all__ = ['MigrationUnpickler']

import pickle  # nosec
import typing


MIGRATIONS: typing.Final[typing.Mapping[str, typing.Tuple[str, typing.Mapping[str, str]]]] = {
    'anaconda_navigator.api.cloud.token': ('anaconda_navigator.api.nucleus.token', {'CloudToken': 'NucleusToken'}),
    # 'anaconda_navigator.api.nucleus.token': ('anaconda_navigator.api.cloud.token', {'NucleusToken': 'CloudToken'}),
}


class MigrationUnpickler(pickle.Unpickler):
    """Helper class to allow unpickling of moved components."""

    def find_class(self, __module_name: str, __global_name: str) -> typing.Any:
        """Detect the class by its module name and global name."""
        __module_name, global_names = MIGRATIONS.get(__module_name, (__module_name, {}))
        __global_name = global_names.get(__global_name, __global_name)
        return super().find_class(__module_name, __global_name)
