from django.db import OperationalError, ProgrammingError

from core.models import SiteSetting
from core.seo import person_schema, website_schema
from profiles.models import Profile


def site_context(request):
    """Sediakan profil, pengaturan situs, badge panel, dan structured data."""
    try:
        profile = Profile.get_solo()
        setting = SiteSetting.get_solo()
    except (OperationalError, ProgrammingError):
        # Terjadi sebelum migrasi dijalankan.
        return {"profile": None, "setting": None, "social_links": []}

    social_links = list(profile.social_links.filter(is_active=True))

    ctx = {
        "profile": profile,
        "setting": setting,
        "social_links": social_links,
    }

    # Structured data hanya relevan di halaman publik, bukan di panel admin.
    if not request.path.startswith(("/panel/", "/django-admin/")):
        ctx["schema_person"] = person_schema(request, profile, setting, social_links)
        ctx["schema_website"] = website_schema(request, profile, setting)

    if request.user.is_authenticated:
        from blog.models import Comment
        from core.models import ContactMessage

        ctx["unread_messages"] = ContactMessage.objects.filter(is_read=False).count()
        ctx["pending_comments"] = Comment.objects.filter(is_approved=False).count()

    return ctx
