"""Database utilities for concurrent access."""
import functools
import time
import logging
from django.db import OperationalError, close_old_connections

logger = logging.getLogger(__name__)


def retry_on_lock(max_retries=3, base_delay=0.5):
    """Decorator: retry on OperationalError('database is locked')."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_retries):
                close_old_connections()
                try:
                    return func(*args, **kwargs)
                except OperationalError as e:
                    if 'database is locked' in str(e) and attempt < max_retries - 1:
                        delay = base_delay * (2 ** attempt)
                        logger.warning(f'[DB_LOCKED] retry {attempt+1}/{max_retries} in {delay:.1f}s')
                        time.sleep(delay)
                        close_old_connections()
                    else:
                        raise
        return wrapper
    return decorator
