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

import sys
import importlib
import logging
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
import logging

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)：
    - 写/清 SettlementTime（进结算时刻）
    - 俱乐部自动结算开启后新进 8 → AutoSettleEligible；否则永不 eligible（老单安全）
    旧全局 ORDER_AUTO_SETTLEMENT_ENABLED 保持 False，不投递旧延时任务。
    """
    if instance.pk is None:
        return
    try:
        from orders.models import Order
        from jituan.services.order_deal import apply_enter_status_8, apply_leave_status_8

        old = Order.query.filter(pk=instance.pk).values_list('Status', flat=True).first()
        if old != 8 and instance.Status == 8:
            apply_enter_status_8(instance)
            try:
                from orders.services.team_recruit import on_order_enter_status_8
                on_order_enter_status_8(instance)
            except Exception as e:
                logger.error(f'组队进结算中锁定失败: {e}')
        elif old == 8 and instance.Status != 8:
            # 成交时长：在清空 SettlementTime 前挂到实例上供 post_save 指标使用
            instance._deal_settle_started_at = instance.SettlementTime
            apply_leave_status_8(instance)
    except Exception as e:
        logger.error(f'结算中信号处理失败: {e}')


@receiver(post_save, sender='orders.Order')
def handle_order_deal_stats(sender, instance, created, **kwargs):
    """成交指标：入池 / 完成 / 退款（统计开关关闭或 since 前订单自动跳过）。"""
    try:
        from jituan.services import deal_stats as ds
        if created:
            return
        # 入池：有打手且进行中/结算中/已完成等
        if instance.PlayerID and instance.Status in (2, 3, 4, 5, 6, 8):
            ds.on_order_enter_pool(instance)
        if instance.Status == 3:
            started = getattr(instance, '_deal_settle_started_at', None)
            ds.on_order_completed(instance, settle_started_at=started)
        elif instance.Status == 5:
            ds.on_order_refunded(instance)
            try:
                from orders.services.team_recruit import on_order_refunded
                on_order_refunded(instance)
            except Exception as e:
                logger.error(f'组队退款清退失败: {e}')
    except Exception as e:
        logger.error(f'成交指标信号处理失败: {e}')
