import logging
import shutil

from defence360agent.files import FILES_DIR
from defence360agent.utils import importer, antivirus_mode

logger = logging.getLogger(__name__)


def _move(src, dst):
    try:
        shutil.move(src, dst)
    except FileNotFoundError:
        pass
    except Exception as err:
        logger.error(
            "Failed to move HackerTrap list to the new location: %r", err
        )


@antivirus_mode.skip
def migrate(migrator, database, fake=False, **kwargs):
    if fake:
        return

    try:
        from defence360agent.contracts.config import HackerTrap

        HackerTrapHitsSaver = importer.get(
            module="imav.malwarelib.subsys.malware",
            name="HackerTrapHitsSaver",
            default=None,
        )
    except ImportError:
        return

    HackerTrapHitsSaver.BASE_DIR = str(FILES_DIR)

    src1 = HackerTrapHitsSaver._filepath()
    src2 = HackerTrapHitsSaver._clean_filepath()
    for src in src1, src2:
        _move(str(src), HackerTrap.DIR)


def rollback(migrator, database, fake=False, **kwargs):
    pass
