from .models import SystemSetting
from django.db.utils import OperationalError
from django.core.management import call_command
import os
import time
import logging

logger = logging.getLogger(__name__)

STARTUP_TIMESTAMP = int(time.time())

def project_context(request):
    return {
        "project_description": os.getenv("PROJECT_DESCRIPTION", ""),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
        "deployment_timestamp": STARTUP_TIMESTAMP,
    }

def global_settings(request):
    settings = None
    try:
        settings = SystemSetting.objects.first()
        if not settings:
            settings = SystemSetting.objects.create()
    except Exception:
        # If DB is broken (OperationalError, etc.), just return None.
        # Do not try to fix it here to avoid infinite loops or crashes during template rendering.
        pass

    return {
        'site_settings': settings,
        'global_settings': settings,
        'decimal_places': settings.decimal_places if settings else 3
    }
