# 模板上下文处理器
import json
import os

from apps.core.models.admin_settings import AdminSettings
from apps.core.models.auxiliary import AuxiliaryConfig
from apps.core.models.cacheconfig import CacheConfig
from apps.core.models.content_config import ContentConfig
from apps.core.models.security_code import SecurityCode
from apps.core.models.site_settings import SiteSettings
from django.conf import settings
from django.core.cache import cache
from django.forms.models import model_to_dict


def get_theme_settings():
    """
    从当前主题的 themesettings.json 文件中读取设置，
    并将设置转换为 theme_{setting_name} 格式的字典
    """
    print('开始获取当前主题个性配置')
    theme_settings_dict = {}
    try:
        # 获取当前主题名称（这里需要根据您的实际实现来获取）
        current_theme_name = settings.THEME_NAME

        # 构建主题配置文件路径
        theme_config_path = os.path.join(settings.BASE_DIR, 'templates',
                                         'themes', current_theme_name,
                                         'themesettings.json')

        # 检查配置文件是否存在
        if os.path.exists(theme_config_path):
            with open(theme_config_path, 'r', encoding='utf-8') as f:
                config_data = json.load(f)

            # 提取所有设置并转换为 theme_{name} 格式
            for setting in config_data.get('settings', []):
                setting_name = setting.get('name')
                default_value = setting.get('default')

                if setting_name:
                    theme_key = f"theme_{setting_name}"
                    theme_settings_dict[theme_key] = default_value

    except Exception as e:
        print('⚠️  获取当前主题个性配置失败')
        return {}
    if theme_settings_dict:
        print('✅ 获取当前主题个性配置成功')

    else:
        print('✅ 获取当前主题个性配置完成，当前模板不需要使用个性配置')
    return theme_settings_dict


def check_config(config, include_fields=None, exclude_fields=None):
    """
    通用配置检查函数，用于处理模型配置数据
    
    参数:
    config: 配置对象（通常是Django模型实例）
    include_fields: list, 需要包含的字段列表（如果提供，则只返回这些字段）
    exclude_fields: list, 需要排除的字段列表（默认为['id']）
    
    返回:
    dict: 处理后的配置字典
    """
    # 设置默认排除字段
    if exclude_fields is None:
        exclude_fields = ['id']

    # 将模型对象转换为字典
    if hasattr(config, '_meta'):
        # 如果是Django模型实例
        config_dict = model_to_dict(config)
    else:
        # 如果已经是字典，直接使用
        config_dict = config.copy() if isinstance(config, dict) else {}

    result_dict = {}

    # 处理包含字段逻辑
    if include_fields:
        for field in include_fields:
            if field in config_dict:
                result_dict[field] = config_dict[field]
            else:
                # 如果字段不存在于配置中，可以设置为None或跳过
                result_dict[field] = None
    else:
        # 如果没有指定包含字段，使用所有字段
        result_dict = config_dict.copy()

    # 处理排除字段逻辑
    for field in exclude_fields:
        if field in result_dict:
            del result_dict[field]

    return result_dict


def templates_global(request):
    cache_key = 'templates_global_cache'
    filtered_config_cache = cache.get(cache_key)
    try:
        if filtered_config_cache and filtered_config_cache['site_name']:
            return filtered_config_cache
    except:
        pass

    filtered_config = {}
    # 获取站点配置
    site_config = SiteSettings.get_solo()
    # 使用 check_config 处理站点配置
    site_config_processed = check_config(site_config, exclude_fields=['id'])
    filtered_config.update(site_config_processed)
    # 内容扩展配置
    content_config = ContentConfig.get_solo()
    content_config_processed = check_config(content_config,
                                            exclude_fields=['id'])
    filtered_config.update(content_config_processed)
    # 缓存扩展配置
    cache_config = CacheConfig.get_solo()
    cache_config_processed = check_config(
        cache_config,
        exclude_fields=[
            'id', 'caches_setting', 'global_cache_enabled',
            'global_cache_enabled', 'index_timeout', 'channel_timeout',
            'tag_timeout', 'list_timeout', 'item_timeout'
        ])
    filtered_config.update(cache_config_processed)

    filtered_config.update({'uploadpath': settings.MEDIA_URL})

    admin_config = AdminSettings.get_solo()
    filtered_config.update(
        {'admin_site_name': getattr(admin_config, 'admin_site_name', '')})
    # SystemConfig
    # 添加额外字段
    # filtered_config.update({'current_year': 2025, 'page_title': '首页'})

    # 添加额外配置项（可选）
    # filtered_config['current_year'] = 2024
    try:
        error_render = settings.GLOBAL_CONFIG.get('AuxiliaryConfig',
                                                  {}).get('error_render', '/')
    except:
        error_render = '/'
    filtered_config.update({'error_render': error_render})
    security_code = getattr(SecurityCode.get_solo(), 'code', '')
    filtered_config.update({'security_code': security_code})
    auxi_config = AuxiliaryConfig.get_solo()
    filtered_config.update({
        'allow_registration':
        getattr(auxi_config, 'allow_registration', '/'),
        'json_ld_enabled':
        getattr(auxi_config, 'json_ld_enabled', False),
        'og_enabled':
        getattr(auxi_config, 'json_ld_enabled', True),
        'twitter_card_enabled':
        getattr(auxi_config, 'twitter_card_enabled', True),
    })
    # 获取主题设置并添加到配置中
    theme_settings = get_theme_settings()
    filtered_config.update(theme_settings)
    cache.set(cache_key, filtered_config, timeout=None)
    return filtered_config
