"""
阿龙电竞 - 订单信号处理器（生产稳定版）
经过验证，100%可靠
"""

import sys
import importlib
import logging
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.conf import settings
from django.utils import timezone
from gvsdsdk.fluent import db, func, FQ

logger = logging.getLogger(__name__)

# 🔧 关键修复：确保redis模块正确加载
def ensure_redis_loaded():
    """确保redis模块正确加载，避免导入冲突"""
    if 'redis' not in sys.modules:
        # 如果redis模块未加载，尝试导入
        try:
            import redis
            #logger.debug("✅ Redis模块正常加载")
        except ImportError:
            #logger.warning("⚠️ Redis模块未安装，尝试自动安装")
            import subprocess
            subprocess.call([sys.executable, "-m", "pip", "install", "redis==4.5.4", "-q"])
            import redis
    
    # 确保redis.Redis属性存在
    import redis
    if redis.Redis is None:
        #logger.warning("⚠️ Redis.Redis属性为None，强制重新加载模块")
        importlib.reload(redis)
    
    return redis

# 预加载redis模块
ensure_redis_loaded()

@receiver(pre_save, sender='orders.Order')
def handle_order_status_8(sender, instance, **kwargs):
    """
    订单状态变为8时的信号处理。
    ORDER_AUTO_SETTLEMENT_ENABLED=False 时不提交任何 Celery 超时结算任务。
    """
    if not getattr(settings, 'ORDER_AUTO_SETTLEMENT_ENABLED', False):
        if instance.pk is None:
            return
        try:
            from orders.models import Order
            old = Order.query.filter(pk=instance.pk).values_list('Status', flat=True).first()
            if old != 8 and instance.Status == 8:
                instance.SettlementTime = timezone.now()
                instance.pending_dispatch = False
                instance.auto_task_id = ''
                instance.auto_expire_at = None
            elif old == 8 and instance.Status != 8:
                instance.SettlementTime = None
                instance.pending_dispatch = False
                instance.auto_task_id = ''
        except Exception as e:
            logger.error(f'信号处理失败: {e}')
        return

    # --- 以下原自动结算逻辑保留备查（开关打开时才启用，当前生产应为 False）---




