from .models import (
    SiteSettings, StaticPage, YouTubeVideo,
    HomepageContent, HomepageSection, SubscribeContent, FooterContent, NavContent,
    PopupModal
)
from apps.articles.models import Category, Article


def global_settings(request):
    # Preload homepage sections with their articles
    homepage_sections = HomepageSection.objects.filter(is_active=True).select_related('category')
    sections_with_articles = []
    for section in homepage_sections:
        articles = Article.objects.filter(
            status='published',
            categories=section.category
        ).select_related('author').prefetch_related('categories')[:section.max_articles]
        total_count = Article.objects.filter(
            status='published',
            categories=section.category
        ).count()
        sections_with_articles.append({
            'section': section,
            'articles': articles,
            'total_count': total_count,
            'has_more': total_count > section.max_articles,
        })

    from django.conf import settings as dj_settings
    from . import fonts
    from .seo import organization_schema, website_schema
    site = SiteSettings.get_solo()
    return {
        'site': site,
        'SITE_URL': dj_settings.SITE_URL,
        'font_head': fonts.font_head(site),
        'GOOGLE_CLIENT_ID': getattr(dj_settings, 'GOOGLE_CLIENT_ID', ''),
        'base_schema': {'@context': 'https://schema.org',
                        '@graph': [organization_schema(site), website_schema()]},
        'nav_categories': Category.objects.filter(is_active=True).order_by('order'),
        'footer_pages': StaticPage.objects.filter(is_published=True, show_in_footer=True),
        'youtube_videos': YouTubeVideo.objects.filter(is_active=True)[:6],
        'homepage': HomepageContent.get_solo(),
        'subscribe': SubscribeContent.get_solo(),
        'footer': FooterContent.get_solo(),
        'nav_content': NavContent.get_solo(),
        'homepage_sections': sections_with_articles,
        'popup_modal': PopupModal.objects.filter(is_active=True).first(),
    }
