package com.huangzj.server.net;

import com.huangzj.server.config.ClientTcpProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PreDestroy;
import java.net.BindException;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 客户端 TCP 入口：与跨服侧帧格式一致，业务仅通过 {@code @Cmd}（{@link com.huangzj.server.cmd.ServerCommandRegistry}）。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ClientTcpServer {

    private final ClientTcpProperties properties;
    private final ClientTcpChannelInitializer clientTcpChannelInitializer;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel serverChannel;

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @EventListener(ApplicationReadyEvent.class)
    public void start() throws InterruptedException {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(clientTcpChannelInitializer);
            serverChannel = b.bind(properties.getPort()).sync().channel();
            log.info("Client TCP (game) listening on {}", properties.getPort());
        } catch (Exception e) {
            if (findBindException(e) != null) {
                shutdownGroupsOnly();
                int port = properties.getPort();
                throw new IllegalStateException(
                        "区服客户端 TCP 端口 "
                                + port
                                + " 已被占用。请关闭占用进程或在 application.yml 修改 game.client-tcp.port。",
                        e);
            }
            shutdownGroupsOnly();
            throw e;
        }
    }

    private static BindException findBindException(Throwable t) {
        while (t != null) {
            if (t instanceof BindException) {
                return (BindException) t;
            }
            t = t.getCause();
        }
        return null;
    }

    private void shutdownGroupsOnly() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).syncUninterruptibly();
            bossGroup = null;
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).syncUninterruptibly();
            workerGroup = null;
        }
    }

    @PreDestroy
    public void stop() throws InterruptedException {
        if (serverChannel != null) {
            serverChannel.close().syncUninterruptibly();
        }
        if (bossGroup != null) {
            bossGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).syncUninterruptibly();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully(0, 1, TimeUnit.SECONDS).syncUninterruptibly();
        }
    }
}
