from functools import wraps
import time
from typing import Any

from django.core.cache import cache
from django.db import OperationalError, transaction


class VersionConflictError(Exception):
    """Raised on optimistic concurrency mismatch and mapped to HTTP 409 Conflict."""

    code = "VERSION_CONFLICT"

    def __init__(self, message: str, *, current_version: int, expected_version: int | None, latest_record: Any = None):
        super().__init__(message)
        self.current_version = current_version
        self.expected_version = expected_version
        self.latest_record = latest_record


def assert_expected_version(instance, expected_version: int | str | None, *, latest_record: Any = None) -> None:
    """
    Validates optimistic locking version counter on mutable records before save/post.
    Raises VersionConflictError (HTTP 409) when stale edits arrive.
    """
    if expected_version is None or expected_version == "":
        return
    try:
        exp = int(expected_version)
    except (TypeError, ValueError):
        return
    curr = int(getattr(instance, "version", 1))
    if exp != curr:
        raise VersionConflictError(
            "This record was updated by another user. Refresh the latest version before saving your changes.",
            current_version=curr,
            expected_version=exp,
            latest_record=latest_record,
        )


def _is_transient_deadlock(exc: OperationalError) -> bool:
    msg = str(exc).lower()
    pgcode = getattr(getattr(exc, "__cause__", None), "pgcode", None)
    mysql_code = None
    cause = getattr(exc, "__cause__", None)
    if cause and getattr(cause, "args", None):
        try:
            mysql_code = int(cause.args[0])
        except Exception:
            mysql_code = None
    return (
        pgcode in ("40P01", "40001")
        or mysql_code in (1213, 1205)
        or "deadlock" in msg
        or "could not serialize access" in msg
    )


def deadlock_safe_atomic(max_attempts: int = 3, base_delay: float = 0.05):
    """
    Executes an atomic DB transaction with bounded exponential backoff retries ONLY on transient
    database deadlock or serialization failure errors.
    """

    def decorator(fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            last_exc = None
            for attempt in range(max_attempts):
                try:
                    with transaction.atomic():
                        return fn(*args, **kwargs)
                except OperationalError as exc:
                    if not _is_transient_deadlock(exc) or attempt >= max_attempts - 1:
                        raise
                    last_exc = exc
                    time.sleep(base_delay * (2**attempt))
            if last_exc:
                raise last_exc

        return wrapper

    return decorator


class CacheScopeInvalidator:
    """
    Centralized company- and user/auth-version-scoped cache keys and explicit invalidation helpers
    preventing cross-company or stale authorization/dashboard cache leakage.
    """

    @staticmethod
    def build_key(*, company_id: str, namespace: str, user_id: str | None = None, auth_version: int | None = None) -> str:
        ver_epoch = CacheScopeInvalidator.company_epoch(company_id)
        if user_id:
            av = auth_version or 1
            return f"c:{company_id}:e{ver_epoch}:u:{user_id}:av{av}:{namespace}"
        return f"c:{company_id}:e{ver_epoch}:{namespace}"

    @staticmethod
    def company_epoch(company_id: str) -> int:
        k = f"epoch:c:{company_id}"
        try:
            val = cache.get(k)
            if val is None:
                cache.set(k, 1, timeout=86400)
                return 1
            return int(val)
        except Exception:
            return 1

    @staticmethod
    def invalidate_company_summaries(company_id: str) -> None:
        """Atomically bumps company summary cache epoch after voucher/treasury/inventory posting."""
        k = f"epoch:c:{company_id}"
        try:
            current = CacheScopeInvalidator.company_epoch(company_id)
            cache.set(k, current + 1, timeout=86400)
        except Exception:
            pass

