"""
Context Processors
==================

Functions that inject global variables into all templates.
"""

from datetime import datetime
from flask_login import current_user
from database import SessionLocal, UserNotification


def inject_globals():
    """Inject global variables into all templates."""
    return {
        'current_year': datetime.now().year,
        'now': datetime.now()  # Must be value, not method - templates use now.strftime()
    }


def inject_notifications():
    """Inject unread notifications count into all templates."""
    if current_user.is_authenticated:
        db = SessionLocal()
        try:
            unread_count = db.query(UserNotification).filter(
                UserNotification.user_id == current_user.id,
                UserNotification.is_read == False
            ).count()
            return {'unread_notifications_count': unread_count}
        finally:
            db.close()
    return {'unread_notifications_count': 0}


def inject_page_view_id():
    """Inject page_view_id into all templates for JS tracking."""
    from utils.analytics import get_current_page_view_id
    return {'page_view_id': get_current_page_view_id()}


def register_context_processors(app):
    """Register all context processors with the app."""
    app.context_processor(inject_globals)
    app.context_processor(inject_notifications)
    app.context_processor(inject_page_view_id)
