import base64
import contextlib
import functools
import json
from collections import defaultdict, deque
from collections.abc import Iterable
from typing import Any

from django.core.cache import caches
from django.core.exceptions import ImproperlyConfigured
from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
from django.utils.module_loading import import_string

from debug_toolbar import settings as dt_settings
from debug_toolbar.models import HistoryEntry
from debug_toolbar.sanitize import force_str

BINARY_SENTINEL = "__djdt_binary__"
POSTGIS_SENTINEL = "__djdt_postgis__"


class DebugToolbarJSONEncoder(DjangoJSONEncoder):
    def default(self, o):
        # Handle binary data (e.g., GeoDjango EWKB geometry data)
        if isinstance(o, (bytes, bytearray)):
            return {BINARY_SENTINEL: base64.b64encode(o).decode("ascii")}
        try:
            return super().default(o)
        except (TypeError, ValueError):
            return force_str(o)


def _binary_object_hook(obj):
    if BINARY_SENTINEL in obj:
        return base64.b64decode(obj[BINARY_SENTINEL])
    if POSTGIS_SENTINEL in obj:
        ewkb = base64.b64decode(obj[POSTGIS_SENTINEL])
        try:
            from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter

            adapter = PostGISAdapter.__new__(PostGISAdapter)
            adapter.is_geometry = obj.get("is_geometry", True)
            adapter.ewkb = ewkb
            adapter.geography = obj.get("geography", False)
            return adapter
        except (ImportError, ImproperlyConfigured):
            return ewkb
    return obj


class DebugToolbarJSONDecoder(json.JSONDecoder):
    """Custom JSON decoder that reconstructs binary data during parsing."""

    def __init__(self, *args, **kwargs):
        # Set object_hook if not already provided
        if "object_hook" not in kwargs:
            kwargs["object_hook"] = _binary_object_hook
        super().__init__(*args, **kwargs)


def serialize(data: Any) -> str:
    # If this starts throwing an exceptions, consider
    # Subclassing DjangoJSONEncoder and using force_str to
    # make it JSON serializable.
    return json.dumps(data, cls=DebugToolbarJSONEncoder, skipkeys=True)


def deserialize(data: str) -> Any:
    return json.loads(data, cls=DebugToolbarJSONDecoder)


class BaseStore:
    @classmethod
    def request_ids(cls) -> Iterable:
        """The stored request ids"""
        raise NotImplementedError

    @classmethod
    def exists(cls, request_id: str) -> bool:
        """Does the given request_id exist in the store"""
        raise NotImplementedError

    @classmethod
    def set(cls, request_id: str):
        """Set a request_id in the store"""
        raise NotImplementedError

    @classmethod
    def clear(cls):
        """Remove all requests from the request store"""
        raise NotImplementedError

    @classmethod
    def delete(cls, request_id: str):
        """Delete the store for the given request_id"""
        raise NotImplementedError

    @classmethod
    def save_panel(cls, request_id: str, panel_id: str, data: Any = None):
        """Save the panel data for the given request_id"""
        raise NotImplementedError

    @classmethod
    def panel(cls, request_id: str, panel_id: str) -> Any:
        """Fetch the panel data for the given request_id"""
        raise NotImplementedError


class MemoryStore(BaseStore):
    # ids is the collection of storage ids that have been used.
    # Use a dequeue to support O(1) appends and pops
    # from either direction.
    _request_ids: deque = deque()
    _request_store: dict[str, dict] = defaultdict(dict)

    @classmethod
    def request_ids(cls) -> Iterable:
        """The stored request ids"""
        return cls._request_ids

    @classmethod
    def exists(cls, request_id: str) -> bool:
        """Does the given request_id exist in the request store"""
        return request_id in cls._request_ids

    @classmethod
    def set(cls, request_id: str):
        """Set a request_id in the request store"""
        if request_id not in cls._request_ids:
            cls._request_ids.append(request_id)
        for _ in range(
            len(cls._request_ids) - dt_settings.get_config()["RESULTS_CACHE_SIZE"]
        ):
            removed_id = cls._request_ids.popleft()
            cls._request_store.pop(removed_id, None)

    @classmethod
    def clear(cls):
        """Remove all requests from the request store"""
        cls._request_ids.clear()
        cls._request_store.clear()

    @classmethod
    def delete(cls, request_id: str):
        """Delete the stored request for the given request_id"""
        cls._request_store.pop(request_id, None)
        # Suppress when request_id doesn't exist in the collection of ids.
        with contextlib.suppress(ValueError):
            cls._request_ids.remove(request_id)

    @classmethod
    def save_panel(cls, request_id: str, panel_id: str, data: Any = None):
        """Save the panel data for the given request_id"""
        cls.set(request_id)
        cls._request_store[request_id][panel_id] = serialize(data)

    @classmethod
    def panel(cls, request_id: str, panel_id: str) -> Any:
        """Fetch the panel data for the given request_id"""
        try:
            data = cls._request_store[request_id][panel_id]
        except KeyError:
            return {}
        else:
            return deserialize(data)

    @classmethod
    def panels(cls, request_id: str) -> Any:
        """Fetch all the panel data for the given request_id"""
        try:
            panel_mapping = cls._request_store[request_id]
        except KeyError:
            return {}
        for panel, data in panel_mapping.items():
            yield panel, deserialize(data)


class DatabaseStore(BaseStore):
    @classmethod
    def _cleanup_old_entries(cls):
        """
        Enforce the cache size limit - keeping only the most recently used entries
        up to RESULTS_CACHE_SIZE.
        """
        # Determine which entries to keep
        keep_ids = cls.request_ids()

        # Delete all entries not in the keep list
        if keep_ids:
            HistoryEntry.objects.exclude(request_id__in=keep_ids).delete()

    @classmethod
    def request_ids(cls):
        """Return all stored request ids within the cache size limit"""
        cache_size = dt_settings.get_config()["RESULTS_CACHE_SIZE"]
        return list(
            HistoryEntry.objects.all()[:cache_size].values_list("request_id", flat=True)
        )

    @classmethod
    def exists(cls, request_id: str) -> bool:
        """Check if the given request_id exists in the store"""
        return HistoryEntry.objects.filter(request_id=request_id).exists()

    @classmethod
    def set(cls, request_id: str):
        """Set a request_id in the store and clean up old entries"""
        with transaction.atomic():
            # Create the entry if it doesn't exist (ignore otherwise)
            _, created = HistoryEntry.objects.get_or_create(request_id=request_id)

            # Only enforce cache size limit when new entries are created
            if created:
                cls._cleanup_old_entries()

    @classmethod
    def clear(cls):
        """Remove all requests from the store"""
        HistoryEntry.objects.all().delete()

    @classmethod
    def delete(cls, request_id: str):
        """Delete the stored request for the given request_id"""
        HistoryEntry.objects.filter(request_id=request_id).delete()

    @classmethod
    def save_panel(cls, request_id: str, panel_id: str, data: Any = None):
        """Save the panel data for the given request_id"""
        with transaction.atomic():
            obj, _ = HistoryEntry.objects.get_or_create(request_id=request_id)
            store_data = obj.data
            store_data[panel_id] = serialize(data)
            obj.data = store_data
            obj.save()

    @classmethod
    def panel(cls, request_id: str, panel_id: str) -> Any:
        """Fetch the panel data for the given request_id"""
        try:
            data = HistoryEntry.objects.get(request_id=request_id).data
            panel_data = data.get(panel_id)
            if panel_data is None:
                return {}
            return deserialize(panel_data)
        except HistoryEntry.DoesNotExist:
            return {}

    @classmethod
    def panels(cls, request_id: str) -> Any:
        """Fetch all panel data for the given request_id"""
        try:
            data = HistoryEntry.objects.get(request_id=request_id).data
            for panel_id, panel_data in data.items():
                yield panel_id, deserialize(panel_data)
        except HistoryEntry.DoesNotExist:
            return {}


class _UntrackedCache:
    """
    Wrapper around a Django cache backend that suppresses debug toolbar tracking.

    The cache panel's monkey-patched methods check ``cache._djdt_panel`` and skip
    recording when it is ``None``.  This proxy temporarily sets that attribute to
    ``None`` around every call so the toolbar's own cache operations are invisible.
    """

    def __init__(self, cache):
        self._cache = cache

    def __getattr__(self, name):
        attr = getattr(self._cache, name)
        if not callable(attr):
            return attr

        @functools.wraps(attr)
        def untracked(*args, **kwargs):
            panel = getattr(self._cache, "_djdt_panel", None)
            self._cache._djdt_panel = None
            try:
                return attr(*args, **kwargs)
            finally:
                self._cache._djdt_panel = panel

        return untracked


class CacheStore(BaseStore):
    """
    Store that uses Django's cache framework to persist debug toolbar data.
    """

    _cache_table_registered = False

    @classmethod
    def _get_cache(cls):
        """Get the Django cache backend, wrapped to bypass toolbar tracking."""
        cache = _UntrackedCache(caches[dt_settings.get_config()["CACHE_BACKEND"]])

        # Register the cache table with DDT_MODELS to filter SQL queries
        if not cls._cache_table_registered:
            cls._register_cache_table_for_sql_filtering(cache._cache)
            cls._cache_table_registered = True

        return cache

    @classmethod
    def _register_cache_table_for_sql_filtering(cls, cache):
        """
        Add the cache table to DDT_MODELS.

        This ensures that when using DatabaseCache, the cache table's SQL queries
        don't appear in the SQLPanel.
        """
        # Only proceed if this is a DatabaseCache backend
        if cache.__class__.__name__ != "DatabaseCache":
            return

        # Get the cache table name
        cache_table = getattr(cache, "_table", None)
        if cache_table:
            # Import here to avoid circular dependency:
            # store.py -> panels/sql/tracking.py -> panels/sql/forms.py -> toolbar.py -> store.py
            from debug_toolbar.panels.sql import tracking

            tracking.DDT_MODELS.add(cache_table)

    @classmethod
    def _key_prefix(cls) -> str:
        """Get the cache key prefix from settings."""
        return dt_settings.get_config()["CACHE_KEY_PREFIX"]

    @classmethod
    def _request_ids_key(cls) -> str:
        """Return the cache key for the request IDs list."""
        return f"{cls._key_prefix()}request_ids"

    @classmethod
    def _request_key(cls, request_id: str) -> str:
        """Return the cache key for a specific request's data."""
        return f"{cls._key_prefix()}req:{request_id}"

    @classmethod
    def request_ids(cls) -> Iterable:
        """The stored request ids."""
        return cls._get_cache().get(cls._request_ids_key(), [])

    @classmethod
    def exists(cls, request_id: str) -> bool:
        """Does the given request_id exist in the store."""
        return request_id in cls.request_ids()

    @classmethod
    def set(cls, request_id: str):
        """Set a request_id in the store."""
        cache = cls._get_cache()
        ids_key = cls._request_ids_key()
        request_ids = deque(cache.get(ids_key, []))

        if request_id not in request_ids:
            request_ids.append(request_id)

        # Enforce RESULTS_CACHE_SIZE limit
        max_size = dt_settings.get_config()["RESULTS_CACHE_SIZE"]
        while len(request_ids) > max_size:
            removed_id = request_ids.popleft()
            cache.delete(cls._request_key(removed_id))

        cache.set(ids_key, list(request_ids), None)

    @classmethod
    def clear(cls):
        """Remove all requests from the request store."""
        cache = cls._get_cache()
        ids_key = cls._request_ids_key()
        request_ids = cache.get(ids_key, [])

        # Delete all request data
        if request_ids:
            cache.delete_many([cls._request_key(_id) for _id in request_ids])

        # Clear the request IDs list
        cache.delete(ids_key)

    @classmethod
    def delete(cls, request_id: str):
        """Delete the stored request for the given request_id."""
        cache = cls._get_cache()
        ids_key = cls._request_ids_key()
        request_ids = list(cache.get(ids_key, []))

        # Remove from the list if present
        if request_id in request_ids:
            request_ids.remove(request_id)
            cache.set(ids_key, request_ids, None)

        # Delete the request data
        cache.delete(cls._request_key(request_id))

    @classmethod
    def save_panel(cls, request_id: str, panel_id: str, data: Any = None):
        """Save the panel data for the given request_id."""
        cls.set(request_id)
        cache = cls._get_cache()
        request_key = cls._request_key(request_id)
        request_data = cache.get(request_key, {})
        request_data[panel_id] = serialize(data)
        cache.set(request_key, request_data, None)

    @classmethod
    def panel(cls, request_id: str, panel_id: str) -> Any:
        """Fetch the panel data for the given request_id."""
        cache = cls._get_cache()
        request_data = cache.get(cls._request_key(request_id), {})
        panel_data = request_data.get(panel_id)
        if panel_data is None:
            return {}
        return deserialize(panel_data)

    @classmethod
    def panels(cls, request_id: str) -> Any:
        """Fetch all the panel data for the given request_id."""
        cache = cls._get_cache()
        request_data = cache.get(cls._request_key(request_id), {})
        for panel_id, panel_data in request_data.items():
            yield panel_id, deserialize(panel_data)


def get_store() -> BaseStore:
    return import_string(dt_settings.get_config()["TOOLBAR_STORE_CLASS"])
