package com.kexue.skills.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@Component
public class StartupListener implements ApplicationListener<ApplicationReadyEvent> {

    private static final Logger logger = LoggerFactory.getLogger(StartupListener.class);

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        String serverPort = event.getApplicationContext().getEnvironment().getProperty("server.port", "8080");
        String serverIp = getServerIp();
        
        String localhostUrl = "http://localhost:" + serverPort + "/doc.html";
        String ipUrl = "http://" + serverIp + ":" + serverPort + "/doc.html";
        
        logger.info("========================================");
        logger.info("API Documentation Access URL:");
        logger.info("========================================");
        logger.info("  Local:  {}", localhostUrl);
        logger.info("  Network:{}", ipUrl);
        logger.info("========================================\n");
    }
    
    /**
     * 获取服务器的实际IP地址
     * @return 服务器IP地址
     */
    private String getServerIp() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();
                    if (inetAddress.isSiteLocalAddress() && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Failed to get server IP address", e);
        }
        return "127.0.0.1";
    }
}