"""Malware detection callbacks"""

import logging

from lasuite.malware_detection.enums import ReportStatus

from core.models import Item, ItemUploadStateChoices

logger = logging.getLogger(__name__)
security_logger = logging.getLogger("drive.security")


def malware_detection_callback(file_path, status, error_info, **kwargs):
    """Malware detection callback"""

    item_id = kwargs.get("item_id")
    try:
        item = Item.objects.get(pk=item_id)
    except Item.DoesNotExist:
        logger.info("Item %s does not exist anymore", item_id)
        return

    if status == ReportStatus.SAFE:
        logger.info("File %s is safe", file_path)
        item.upload_state = ItemUploadStateChoices.READY
        item.save(update_fields=["upload_state"])
        return

    if status == ReportStatus.UNKNOWN:
        security_logger.warning(
            "File %s for Item %s has an unknown reportstatus. Error info: %s",
            file_path,
            item_id,
            error_info,
        )

        error_code = error_info.get("error_code")
        if error_code == 413:
            item.upload_state = ItemUploadStateChoices.FILE_TOO_LARGE_TO_ANALYZE
            item.save(update_fields=["upload_state"])
            return

    if status == ReportStatus.UNSAFE:
        security_logger.warning(
            "File %s for Item %s is suspicious. Error info: %s",
            file_path,
            item_id,
            error_info,
        )

    item.malware_detection_info = error_info
    item.upload_state = ItemUploadStateChoices.SUSPICIOUS
    item.save(update_fields=["upload_state", "malware_detection_info"])
