package com.qaup.collision.websocket.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import com.qaup.collision.websocket.handler.CollisionWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket测试控制器
 * 用于验证collision包是否被正确扫描，以及WebSocket配置是否正确
 */
@RestController
@RequestMapping("/test/websocket")
public class WebSocketTestController
{
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketTestController.class);

    @Autowired
    private ApplicationContext applicationContext;
    
    @Autowired
    private CollisionWebSocketHandler collisionWebSocketHandler;

    /**
     * 检查WebSocket配置状态
     */
    @GetMapping("/status")
    public Map<String, Object> checkWebSocketStatus()
    {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查ServerEndpointExporter是否存在
            String[] exporterBeans = applicationContext.getBeanNamesForType(ServerEndpointExporter.class);
            result.put("serverEndpointExporter", exporterBeans.length > 0 ? exporterBeans : "未找到");
            
            // 检查collision相关Bean
            String[] collisionBeans = applicationContext.getBeanNamesForType(Object.class);
            long collisionCount = java.util.Arrays.stream(collisionBeans)
                .filter(name -> name.toLowerCase().contains("collision"))
                .count();
            result.put("collisionBeansCount", collisionCount);
            
            // 检查WebSocket相关Bean
            long websocketCount = java.util.Arrays.stream(collisionBeans)
                .filter(name -> name.toLowerCase().contains("websocket"))
                .count();
            result.put("websocketBeansCount", websocketCount);
            
            // 检查CollisionWebSocketHandler状态
            result.put("webSocketHandlerStatus", "正常");
            result.put("currentConnections", collisionWebSocketHandler.getConnectionCount());
            
            result.put("status", "success");
            result.put("message", "collision包已正确扫描，WebSocket测试控制器正常工作");
            
            LOGGER.info("✅ collision包扫描正常，ServerEndpointExporter: {}, CollisionBeans: {}, WebSocketBeans: {}", 
                exporterBeans.length, collisionCount, websocketCount);
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", e.getMessage());
            LOGGER.error("❌ WebSocket状态检查失败", e);
        }
        
        return result;
    }

    /**
     * 测试collision模块是否正常工作
     */
    @GetMapping("/collision-test")
    public Map<String, Object> testCollisionModule()
    {
        Map<String, Object> result = new HashMap<>();
        
        try {
            result.put("status", "success");
            result.put("message", "collision模块正常工作");
            result.put("timestamp", System.currentTimeMillis());
            result.put("contextPath", "/test/websocket");
            
            LOGGER.info("✅ collision模块测试通过");
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", e.getMessage());
            LOGGER.error("❌ collision模块测试失败", e);
        }
        
        return result;
    }
    
    /**
     * 测试WebSocket消息广播
     */
    @PostMapping("/broadcast")
    public Map<String, Object> testWebSocketBroadcast(@RequestParam(defaultValue = "测试消息") String message)
    {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 构造测试消息
            String testMessage = String.format(
                "{\"type\":\"test\",\"message\":\"%s\",\"timestamp\":%d,\"from\":\"WebSocketTestController\"}",
                message, System.currentTimeMillis()
            );
            
            // 广播消息到所有连接的客户端
            collisionWebSocketHandler.broadcastMessage(testMessage);
            
            result.put("status", "success");
            result.put("message", "消息广播成功");
            result.put("broadcastMessage", testMessage);
            result.put("connectionCount", collisionWebSocketHandler.getConnectionCount());
            
            LOGGER.info("✅ WebSocket消息广播成功: {}", testMessage);
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", e.getMessage());
            LOGGER.error("❌ WebSocket消息广播失败", e);
        }
        
        return result;
    }
    
    /**
     * 获取WebSocket连接统计信息
     */
    @GetMapping("/connections")
    public Map<String, Object> getConnectionStats()
    {
        Map<String, Object> result = new HashMap<>();
        
        try {
            result.put("status", "success");
            result.put("currentConnections", collisionWebSocketHandler.getConnectionCount());
            result.put("timestamp", System.currentTimeMillis());
            result.put("endpoint", "ws://localhost:8080/collision");
            
            LOGGER.info("✅ WebSocket连接统计: {} 个活动连接", collisionWebSocketHandler.getConnectionCount());
            
        } catch (Exception e) {
            result.put("status", "error");
            result.put("message", e.getMessage());
            LOGGER.error("❌ 获取WebSocket连接统计失败", e);
        }
        
        return result;
    }
    
    /**
     * 测试页面重定向
     */
    @GetMapping("/page")
    public String redirectToTestPage()
    {
        return "redirect:/websocket-test.html";
    }
} 