import logging
from typing import Optional, TYPE_CHECKING
from django.conf import settings
from .choices import CONTEXT, SYNCMODES

if TYPE_CHECKING:
    from .models import SyncableModel

from .constants import (
    SYNCMODE_KEY,
    SYNC_COMPLETED_KEY,
)

logger = logging.getLogger(__name__)


def skip_publication(
    record_data: dict | None = None,
    record: Optional['SyncableModel'] = None,
) -> bool:
    """
    Some events should not be published back to the Concordia MQ.
    Examine the event data to determine if the change should be
    published to the MQ or not.
    """
    if not record_data:
        return False

    try:
        if record_data[SYNCMODE_KEY] == SYNCMODES.Local:
            return False
    except KeyError:
        pass

    try:
        if record_data[CONTEXT.Origin][SYNC_COMPLETED_KEY]:
            return True
    except KeyError:
        pass

    if not settings.SYNC_ENABLED:
        logger.debug('Skip publishing %s to "%s" - sync is disabled', record)
        return True

    if not record:
        return False

    if not record.is_syncable():
        return True

    return False
