from website.models.seo import PageSEOSetting

def seo_context(request):
    """
    Django context processor that determines the current page based on request.path,
    and returns its associated PageSEOSetting record to the template context.
    """
    path = request.path
    page_name = 'home'
    
    # Map the URL path prefix to page_name choices defined in PageSEOSetting
    if path == '/':
        page_name = 'home'
    elif path.startswith('/about/'):
        page_name = 'about'
    elif path.startswith('/services/'):
        # Check if it's a dynamic service subpage (e.g. /services/ai-seo/)
        parts = path.strip('/').split('/')
        if len(parts) > 1:
            page_name = f"service_{parts[1]}"
        else:
            page_name = 'services'
    elif path.startswith('/blog/'):
        page_name = 'blog'
    elif path.startswith('/contact/'):
        page_name = 'contact'
    elif path.startswith('/team/'):
        page_name = 'team'
    else:
        # Default fallback to home settings
        page_name = 'home'
        
    try:
        seo_settings = PageSEOSetting.objects.get(page_name=page_name)
    except PageSEOSetting.DoesNotExist:
        seo_settings = None
        
    return {
        'seo_settings': seo_settings
    }
