import time
import logging
from django.core.cache import cache

logger = logging.getLogger(__name__)

# 超时阈值：3分钟（设备每2分钟上报一次，留1分钟容差）
DEVICE_OFFLINE_TIMEOUT = 180


def check_device_online_status():
    """
    检查所有状态为 connected 的设备，如果超过3分钟没有上报数据，标记为离线。
    由定时任务每60秒调用一次。
    """
    from device_interaction.models import Device

    connected_devices = Device.objects.filter(status='connected')
    now = time.time()
    offline_count = 0

    for device in connected_devices:
        last_seen = cache.get(f"device:last_seen:{device.mac_address}")
        if last_seen is None or (now - float(last_seen)) > DEVICE_OFFLINE_TIMEOUT:
            device.status = 'disconnected'
            device.save(update_fields=['status'])
            cache.delete(f"device:last_seen:{device.mac_address}")
            offline_count += 1
            logger.info(f"Device {device.mac_address} marked offline (timeout)")

    if offline_count > 0:
        logger.info(f"check_device_online_status: {offline_count} device(s) marked offline")
