import logging

from celery.exceptions import MaxRetriesExceededError

from config import celery_app as app

from .models import ScormFile
from .services import ScormValidationError, prepare_scorm

log = logging.getLogger(__name__)


@app.task(bind=True)
def prepare_scorm_task(self, scorm_file_id: int, force: bool = False) -> None:
    """
    Подготовка scorm-курса к использованию
    """
    error_message = None
    try:
        prepare_scorm(scorm_file_id=scorm_file_id, force=force)

    except ScormValidationError as scorm_exc:
        log.error(scorm_exc)
        error_message = str(scorm_exc)

    except Exception as exc:
        log.error(exc)
        try:
            raise self.retry(max_retries=3, countdown=60)
        except MaxRetriesExceededError:
            error_message = str(exc)
            raise

    finally:
        if error_message:
            ScormFile.objects.filter(id=scorm_file_id).update(
                error_messages=error_message,
                scorm_status=ScormFile.SCORM_MODULE_STATUS_ERROR,
            )
