package com.huangzj.cross.net;

import com.huangzj.cross.config.CrossTcpProperties;
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.stereotype.Component;

/**
 * 跨服侧的 TCP 入口：Spring 起来之后绑端口，应用关掉时把线程组也收干净。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class CrossTcpServer {

    private final CrossTcpProperties properties;
    private final CrossTcpChannelInitializer crossTcpChannelInitializer;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private Channel serverChannel;

    /** 等 Spring 容器就绪再绑端口，避免 Bean 还没齐就开始接连接。 */
    @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(crossTcpChannelInitializer);
            serverChannel = b.bind(properties.getPort()).sync().channel();
            log.info("Cross TCP {}", properties.getPort());
        } catch (Exception e) {
            if (findBindException(e) != null) {
                shutdownGroupsOnly();
                int port = properties.getPort();
                throw new IllegalStateException(
                        "跨服 TCP 端口 "
                                + port
                                + " 已被占用（Address already in use）。请关闭占用该端口的进程，或在 application.yml 里修改 cross.tcp.port。"
                                + " Windows 可查：netstat -ano | findstr :" + 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;
    }

    /** 绑定失败时尚未 assign serverChannel，只收掉线程组，避免泄漏。 */
    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;
        }
    }

    /** 进程退出时把 channel 和线程组都关掉，别留一堆 Netty 线程 hanging。 */
    @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();
        }
    }
}
