import hashlib import logging from django.utils import timezone from django.db import models from ..models import AnalysisCache logger = logging.getLogger(__name__) class CacheService: def generate_hash(self, prompt, dealer_id, language): """ Generate a unique MD5 hash based on the prompt, dealer ID, and language. """ key = f"{prompt}:{dealer_id or 'all'}:{language}" return hashlib.md5(key.encode()).hexdigest() def get_cached_result(self, prompt_hash, user, dealer_id): """ Retrieve a cached analysis result based on hash, dealer, and optionally user. """ try: # Check for user-specific cache if authenticated if user and user.is_authenticated: user_cache = AnalysisCache.objects.filter( prompt_hash=prompt_hash, user=user, expires_at__gt=timezone.now() ).first() if user_cache: return user_cache.result # Otherwise check for dealer-wide cache dealer_cache = AnalysisCache.objects.filter( prompt_hash=prompt_hash, dealer_id=dealer_id, expires_at__gt=timezone.now() ).first() return dealer_cache.result if dealer_cache else None except Exception as e: logger.warning(f"Cache retrieval failed: {str(e)}") return None def cache_result(self, prompt_hash, result, user, dealer_id, duration=3600): """ Save or update a cached result with an expiration timestamp. """ try: expires_at = timezone.now() + timezone.timedelta(seconds=duration) AnalysisCache.objects.update_or_create( prompt_hash=prompt_hash, user=user if user and user.is_authenticated else None, dealer_id=dealer_id, defaults={ 'result': result, 'expires_at': expires_at } ) except Exception as e: logger.warning(f"Cache saving failed: {str(e)}")