"""Module containing the tasks for the JCOP backend."""

import logging

import requests
from celery import shared_task

from .. import MalwareDetectionHandler
from ..exceptions import MalwareDetectionInvalidAuthenticationError

logger = logging.getLogger(__name__)


@shared_task(
    bind=True,
    default_retry_delay=3,
    max_retries=100,
    dont_autoretry_for=(MalwareDetectionInvalidAuthenticationError,),
)
def analyse_file_async(
    self,
    file_path: str,
    file_hash: str | None = None,
    **kwargs,
) -> None:
    """Task starting analysis process for a file."""
    backend = MalwareDetectionHandler()()  # JCOPBackend
    try:
        should_retry = backend.check_analysis(file_path, file_hash=file_hash, **kwargs)
    except requests.exceptions.RequestException as exc:
        if self.request.retries >= self.max_retries:
            backend.failed_analysis(file_path, "Max retries fetching results exceeded")
            return
        self.retry(exc=exc)

    if should_retry:
        self.retry()


@shared_task(bind=True, max_retries=6, dont_autoretry_for=(MalwareDetectionInvalidAuthenticationError,))
def trigger_new_analysis(
    self,
    file_path: str,
    **kwargs,
) -> None:
    """Trigger a new analysis for a file."""
    backend = MalwareDetectionHandler()()  # JCOPBackend
    try:
        backend.trigger_new_analysis(file_path, **kwargs)
    except requests.exceptions.RequestException as exc:
        if self.request.retries >= self.max_retries:
            backend.failed_analysis(file_path, "Max retries triggering new analysis exceeded")
            return
        self.retry(exc=exc)
        return
    except TimeoutError:
        if self.request.retries >= self.max_retries:
            backend.failed_analysis(file_path, "Max retries triggering new analysis exceeded")
            return
        self.retry(exc=TimeoutError())
        return
