package com.qaup.collision.websocket.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import com.qaup.collision.websocket.handler.CollisionWebSocketHandler;

/**
 * WebSocket启动监听器
 * 用于在应用启动完成后验证WebSocket服务状态
 * 
 * @author qaup-collision
 */
@Component
public class WebSocketStartupListener
{
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketStartupListener.class);

    /**
     * 应用启动完成后的处理
     */
    @EventListener
    public void handleApplicationReady(ApplicationReadyEvent event)
    {
        LOGGER.info("🎯 应用启动完成，正在验证WebSocket服务状态...");
        
        try {
            // 验证Spring WebSocket配置是否正确加载
            String[] webSocketConfigurerBeans = event.getApplicationContext().getBeanNamesForType(WebSocketConfigurer.class);
            
            if (webSocketConfigurerBeans.length > 0) {
                LOGGER.info("✅ WebSocketConfigurer已正确注册: {}", java.util.Arrays.toString(webSocketConfigurerBeans));
            } else {
                LOGGER.warn("⚠️  未找到WebSocketConfigurer Bean");
            }
            
            // 检查CollisionWebSocketHandler是否被注册
            boolean hasWebSocketHandler = event.getApplicationContext().containsBean("collisionWebSocketHandler");
            if (hasWebSocketHandler) {
                LOGGER.info("✅ CollisionWebSocketHandler已正确注册");
                
                // 获取Handler实例并显示连接信息
                CollisionWebSocketHandler handler = event.getApplicationContext().getBean("collisionWebSocketHandler", CollisionWebSocketHandler.class);
                LOGGER.info("📊 当前WebSocket连接数: {}", handler.getConnectionCount());
            } else {
                LOGGER.warn("⚠️  CollisionWebSocketHandler未注册");
            }
            
            // 检查WebSocket相关的配置类
            boolean hasWebSocketConfig = event.getApplicationContext().containsBean("webSocketConfig");
            if (hasWebSocketConfig) {
                LOGGER.info("✅ WebSocketConfig配置类已加载");
            } else {
                LOGGER.warn("⚠️  WebSocketConfig配置类未找到");
            }
            
            LOGGER.info("🌟 冲突检测WebSocket服务初始化完成");
            LOGGER.info("📡 WebSocket端点可用: ws://localhost:8080/collision");
            
        } catch (Exception e) {
            LOGGER.error("❌ WebSocket服务验证失败", e);
        }
    }
} 