
from django.utils.deprecation import MiddlewareMixin
from django.utils import timezone
from .models import VisitorLog, PageView
import re


class AnalyticsMiddleware(MiddlewareMixin):
    def __init__(self, get_response):
        self.get_response = get_response
        # Bot patterns
        self.bot_patterns = [
            r'bot', r'crawler', r'spider', r'scraper',
            r'googlebot', r'bingbot', r'facebookexternalhit',
            r'twitterbot', r'linkedinbot', r'whatsapp'
        ]
        super().__init__(get_response)

    def process_request(self, request):
        # Skip tracking for admin, static files, and API endpoints
        if any(request.path.startswith(path) for path in ['/admin/', '/static/', '/media/', '/api/']):
            return None

        # Get visitor information
        ip_address = self.get_client_ip(request)
        user_agent = request.META.get('HTTP_USER_AGENT', '')
        page_visited = request.get_full_path()
        referrer = request.META.get('HTTP_REFERER', '')
        session_key = request.session.session_key

        # Check if it's a bot
        is_bot = self.is_bot(user_agent)

        # Log visitor
        try:
            VisitorLog.objects.create(
                ip_address=ip_address,
                user_agent=user_agent,
                page_visited=page_visited,
                referrer=referrer,
                session_key=session_key,
                is_bot=is_bot
            )

            # Update page views
            self.update_page_views(page_visited, session_key)
        except Exception:
            # Silently fail to avoid breaking the site
            pass

        return None

    def get_client_ip(self, request):
        """Get the real IP address of the client"""
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def is_bot(self, user_agent):
        """Check if the user agent indicates a bot"""
        user_agent_lower = user_agent.lower()
        return any(re.search(pattern, user_agent_lower) for pattern in self.bot_patterns)

    def update_page_views(self, page_path, session_key):
        """Update page view statistics"""
        today = timezone.now().date()
        
        page_view, created = PageView.objects.get_or_create(
            page_path=page_path,
            date=today,
            defaults={'views_count': 0, 'unique_views': 0}
        )
        
        page_view.views_count += 1
        
        # Check if this is a unique view (simplified by session)
        if session_key:
            from django.core.cache import cache
            cache_key = f"page_view_{page_path}_{session_key}_{today}"
            if not cache.get(cache_key):
                page_view.unique_views += 1
                cache.set(cache_key, True, 86400)  # 24 hours
        
        page_view.save()
