package com.gameplatform.server.controller.admin;

import com.gameplatform.server.device.Detection;
import com.gameplatform.server.device.DeviceStats;
import com.gameplatform.server.model.dto.device.DeviceStatusResponse;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/admin/devices")
@Tag(name = "设备状态", description = "获取所有设备的实时状态")
public class DeviceStatusController {

    private static final Logger log = LoggerFactory.getLogger(DeviceStatusController.class);

    private final Detection detection;
    private final DeviceStats deviceStats;

    public DeviceStatusController(Detection detection, DeviceStats deviceStats) {
        this.detection = detection;
        this.deviceStats = deviceStats;
    }

    @GetMapping("/status")
    @Operation(summary = "获取设备分组状态", description = "返回最近一次分组统计快照（含 categoryToDevices 与计数）。必要时会基于最新快照即时计算一次，不触发脚本刷新。")
    public ResponseEntity<DeviceStats.Snapshot> getAllDeviceStatus() {
        DeviceStats.Snapshot stats = deviceStats.getLastComputedSnapshot();
        if (stats == null) {
            // 优先使用检测缓存，其次拉取一次（带TTL），并计算分组
            DeviceStatusResponse latest = detection.getLastSnapshot();
            if (latest == null) {
                latest = detection.listAllDevices();
            }
            if (latest != null) {
                stats = deviceStats.updateWithSnapshot(latest);
            }
        }
        if (stats == null) {
            log.warn("getAllDeviceStatus: 未获取到分组统计快照，返回204");
            return ResponseEntity.noContent().build();
        }
        return ResponseEntity.ok(stats);
    }
}


