from django.db import connection
from django.conf import settings
from django.contrib.sessions.base_session import AbstractBaseSession


# pylint: disable=unused-argument
class HighAvailabilityRouter:
    def db_for_read(self, model, **hints):
        if "read" not in settings.DATABASES:
            # None will enable the default behaviour of the db router
            return None

        # always take Session from the default database.
        if issubclass(model, AbstractBaseSession):
            return None

        # Use db_for_write during transactions since the current connection may have
        # pending write operations. This ensures we read from the same database where
        # writes are being performed, preventing inconsistencies that could occur if
        # we read from a replica that hasn't received the transaction's changes yet.
        # Even if the current operation is a read, we need the primary database to
        # maintain transaction isolation.
        if connection.in_atomic_block:
            return self.db_for_write(model, **hints)

        instance = hints.get("instance", None)
        if instance is not None and instance.pk is None:
            # None will enable the default behaviour of the db router
            # which does not cause any errors
            return None

        return "read"

    def db_for_write(self, model, **hints):
        return "default"

    def allow_relation(self, obj1, obj2, **hints):
        return True

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        return True
