package robot.mj;

import com.robot.GameController;
import com.robot.GameInterceptor;
import com.robot.MainServer;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TObject;
import com.taurus.core.routes.ActionKey;
import com.taurus.permanent.data.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import robot.mj.info.RobotRoomInfo;
import taurus.client.TaurusClient;
import taurus.client.business.GroupRoomBusiness;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 长沙麻将游戏控制器 - 处理游戏协议
 */
public class EXGameController extends GameController {
    private static final Logger log = LoggerFactory.getLogger(EXGameController.class);
    
    private static RobotConnectionManager connectionManager = new RobotConnectionManager();
    
    //机器人房间
    private static final Map<String, RobotRoomInfo> robotRoomMapping = new ConcurrentHashMap<>();

    public EXGameController() {
        super();
        log.info("长沙麻将游戏控制器已初始化");
    }

    /**
     * 处理客户端初始化/认证协议
     */
    @ActionKey(value = Config.INIT_CONNECTION, validate = GameInterceptor.NOT_PLAYER)
    public void handleInitialization(Session session, ITObject params, int gid) {
        try {
            log.info("收到客户端初始化请求，Session: {}, GID: {}, 参数: {}", session, gid, params);
            
            String type = params.getString("type");
            String client = params.getString("client");
            log.info("客户端类型: {}, 客户端标识: {}", type, client);
            
            //验证参数
            if ("robot_mj_cs".equals(type) && "robot_mgr".equals(client)) {
                //返回成功响应
                ITObject response = TObject.newInstance();
                response.putString("status", "success");
                response.putString("message", "初始化成功");
                
                log.info("客户端初始化成功，发送响应");
                MainServer.instance.sendResponse(gid, 0, response, session);
            } else {
                log.warn("客户端初始化失败，参数验证不通过: type={}, client={}", type, client);
                
                ITObject response = TObject.newInstance();
                response.putString("status", "failed");
                response.putString("message", "参数验证失败");
                MainServer.instance.sendResponse(gid, 1, response, session);
            }
        } catch (Exception e) {
            log.error("处理初始化请求时发生错误", e);
            
            ITObject response = TObject.newInstance();
            response.putString("status", "error");
            response.putString("message", "服务器内部错误: " + e.getMessage());
            
            MainServer.instance.sendResponse(gid, 1, response, session);
        }
    }

    /**
     * 接收来自robot_mgr的创建房间协议
     */
    @ActionKey(value = Config.CREATE_ROOM_ROBOT, validate = GameInterceptor.NOT_PLAYER)
    public void createRoomForRobot(Session session, ITObject params, int gid) {
        try {
            int reqGroupId = params.getInt("groupId");
            int wanfaId = params.getInt("wanfaId");
            int robotId = params.getInt("robotId");

            //使用统一的房间创建器在Redis中创建房间
            RoomCreator.RoomInfo roomInfo = RoomCreator.createRoomInRedis(reqGroupId, wanfaId, robotId);
            
            if (roomInfo != null) {
                //返回房间信息给robot_mgr
                ITObject response = TObject.newInstance();
                response.putString("roomKey", roomInfo.getRoomId());
                response.putInt("groupId", roomInfo.getGroupId());
                response.putInt("wanfaId", roomInfo.getWanfaId());
                response.putInt("robotId", robotId);
                response.putString("server_ip", roomInfo.getServerIp());
                response.putInt("server_port", roomInfo.getServerPort());
                
                log.info("成功创建房间，房间ID: {}", roomInfo.getRoomId());
                //使用Taurus框架方法发送响应
                MainServer.instance.sendResponse(gid, 0, response, session);
            } else {
                log.error("创建房间失败，群组ID: {}, 玩法ID: {}", reqGroupId, wanfaId);
            }
        } catch (Exception e) {
            log.error("处理创建房间请求时发生错误", e);
        }
    }

    /**
     * 接收来自robot_mgr的加入房间协议
     */
    @ActionKey(value = Config.JOIN_ROOM, validate = GameInterceptor.NOT_PLAYER)
    public void joinRoom(Session session, ITObject params, int gid) {
        try {
            String connecId = params.getString("connecId");
            TaurusClient client = getCsMjGameServerConnection(connecId);
            System.out.println("接收来自robot_mgr的加入房间协议 connecId: = "+connecId);
            System.out.println("接收来自robot_mgr的加入房间协议 client: = "+client);
            if (client == null) {
                // 返回失败响应而不是直接返回
                ITObject errorResponse = TObject.newInstance();
                errorResponse.putString("status", "failed");
                errorResponse.putString("message", "无法获取游戏服务器连接");
                MainServer.instance.sendResponse(gid, 1, errorResponse, session);
                return;
            }
            
            //设置session和token
            String sessionToken = params.getString("session");
            String robotSession = null;
            if (sessionToken != null && sessionToken.contains(",")) {
                String[] sessionParts = sessionToken.split(",");
                if (sessionParts.length >= 2) {
                    robotSession = sessionParts[0];
                    String token = sessionParts[1];
                    connectionManager.setSessionAndToken(robotSession, token);
                }
            }

            Integer groupId = params.getInt("groupId");
            String roomId = params.getString("roomId");
            String robotId = params.getString("robotId");
            
            GroupRoomBusiness.joinRoom(groupId, roomId, robotSession, null);

            Thread.sleep(5000);

            params.del("groupId");
            params.del("roomId");
            params.del("connecId");
            // 发送加入房间请求到game_mj_cs
            client.send(Config.JOIN_ROOM_CS, params, response -> {
                System.out.println("joinRoomController: " + response);
                RobotRoomInfo roomInfo = new RobotRoomInfo();
                roomInfo.setRoomId(roomId);
                roomInfo.setConnecId(connecId);
                roomInfo.setUserId(0);
                //机器人房间映射关系
                robotRoomMapping.put(robotId, roomInfo);
            });

            // 发送成功响应
            ITObject paramsReq = TObject.newInstance();
            paramsReq.putString("status", "success");
            MainServer.instance.sendResponse(gid, 0, paramsReq, session);
            
        } catch (Exception e) {
            log.error("处理加入房间请求时发生错误", e);
            ITObject errorResponse = TObject.newInstance();
            errorResponse.putString("status", "error");
            errorResponse.putString("message", "处理加入房间请求时发生错误: " + e.getMessage());
            MainServer.instance.sendResponse(gid, 1, errorResponse, session);
        }
    }

    /**
     * 接收来自robot_mgr的机器人准备协议
     */
    @ActionKey(value = Config.GAME_READY, validate = GameInterceptor.NOT_PLAYER)
    public void robotReadyRoom(Session session, ITObject params, int gid) {
        try {
            String connecId = params.getString("connecId");
            TaurusClient client = getCsMjGameServerConnection(connecId);
            System.out.println("接收来自robot_mgr的机器人准备协议 connecId: = "+connecId);
            System.out.println("接收来自robot_mgr的机器人准备协议 client: = "+client);
            if (client == null) {
                ITObject errorResponse = TObject.newInstance();
                errorResponse.putString("status", "failed");
                errorResponse.putString("message", "无法获取游戏服务器连接");
                MainServer.instance.sendResponse(gid, 1, errorResponse, session);
                return;
            }

            params.del("connecId");
            Thread.sleep(1000);
            // 发送准备请求到game_mj_cs
            client.send(Config.GAME_READY_CS, params, response -> {
                System.out.println("robotReadyRoom: " + response);
            });
            
            // 发送成功响应
            ITObject paramsReq = TObject.newInstance();
            paramsReq.putString("status", "success");
            MainServer.instance.sendResponse(gid, 0, paramsReq, session);
            
        } catch (Exception e) {
            log.error("处理机器人准备请求时发生错误", e);
            ITObject errorResponse = TObject.newInstance();
            errorResponse.putString("status", "error");
            errorResponse.putString("message", "服务器内部错误: " + e.getMessage());
            MainServer.instance.sendResponse(gid, 1, errorResponse, session);
        }
    }

    /**
     * 接收来自robot_mgr的退出房间协议
     * 断开与game_mj_cs的TCP连接
     */
    @ActionKey(value = Config.EXIT_ROOM, validate = GameInterceptor.NOT_PLAYER)
    public void exitRoom(Session session, ITObject params, int gid) {
        try {
            String connecId = params.getString("connecId");
            Integer robotId = params.getInt("robotId"); // 获取机器人ID
            log.info("处理退出房间请求，connecId: {}, robotId: {}", connecId, robotId);
            
            // 清理机器人房间映射
            if (robotId != null && robotId > 0) {
                RobotRoomInfo removedInfo = robotRoomMapping.remove(robotId);
                if (removedInfo != null) {
                    log.info("清理机器人房间映射: robotId={}, 映射信息={}", robotId, removedInfo);
                }
            }
            
            TaurusClient client = getCsMjGameServerConnection(connecId);
            if (client == null) {
                log.error("无法获取到游戏服务器连接，connecId: {}", connecId);
                return;
            }

            //发送退出房间请求
            client.send(Config.EXIT_ROOM_CS, params, response -> {
                log.info("退出房间请求发送结果: returnCode={} for connecId={}", response.returnCode, connecId);
            });

            //断开与游戏服务器的连接
            //connectionManager.disconnectFromGameServer(connecId);
        } catch (Exception e) {
            log.error("处理退出房间请求时发生错误", e);
            String connecId = params.getString("connecId");
            Integer robotId = params.getInt("robotId");
            
            //出错时也要清理映射
            if (robotId != null && robotId > 0) {
                robotRoomMapping.remove(robotId);
            }
            
            //connectionManager.disconnectFromGameServer(connecId);
        }
    }
    
    /**
     * 根据机器人ID获取其所在的房间信息
     */
    public static RobotRoomInfo getRobotRoomInfo(String robotId) {
        return robotRoomMapping.get(robotId);
    }

    /**
     * 根据机器人ID删除其所在的房间信息
     */
    public static void removeRobotRoomInfo(String robotId) {
        robotRoomMapping.remove(robotId);
    }
    
    /**
     * 根据机器人ID和连接ID获取长沙麻将游戏服务器连接
     * 基于robotId和connectionId的组合复用连接
     */
    public static TaurusClient getCsMjGameServerConnection(String connecId) {
        TaurusClient taurusClient = connectionManager.getGameClient(connecId);
        System.out.println("根据机器人ID和连接ID获取长沙麻将游戏服务器连接 client: = "+taurusClient);
        if (taurusClient != null) {
            log.debug("成功获取游戏服务器连接，connecId: {}", connecId);
            // 快速检测连接状态
            connectionManager.quickCheckAndReconnect(connecId);
            return taurusClient;
        }
        taurusClient = connectionManager.connectToGameServer(connecId);
        return taurusClient;
    }

}