from datetime import datetime

from flask import current_app
from flask_login import current_user

from .models import Notification
from .services.localization_service import LocalizationService
from .services.settings_service import SettingsService


def register_context_processors(app) -> None:
    @app.context_processor
    def inject_global_context():
        unread_notifications = 0
        latest_notifications = []
        if current_user.is_authenticated:
            unread_notifications = Notification.query.filter_by(user_id=current_user.id, is_read=False).count()
            latest_notifications = (
                Notification.query.filter_by(user_id=current_user.id)
                .order_by(Notification.created_at.desc())
                .limit(5)
                .all()
            )
        current_locale = LocalizationService.current_locale()
        return {
            "app_name": SettingsService.get("app_name", current_app.config["APP_NAME"]),
            "app_logo_url": SettingsService.app_logo_url(),
            "auth_logo_url": current_app.config["AUTH_LOGO_URL"],
            "brand_color": current_app.config["BRAND_COLOR"],
            "current_year": datetime.utcnow().year,
            "unread_notifications_count": unread_notifications,
            "latest_notifications": latest_notifications,
            "current_locale": current_locale,
            "is_rtl": LocalizationService.is_rtl(current_locale),
            "t": LocalizationService.translate,
            "ltext": LocalizationService.localize_text,
            "available_locales": current_app.config["SUPPORTED_LOCALES"],
            "user_can": lambda code: current_user.is_authenticated and current_user.has_permission(code),
        }
