package org.kne.cloud.network.tun;
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;

/**
 * Windows IP 接口配置管理
 * 提供 GetIpInterfaceEntry 和 SetIpInterfaceEntry 的 Java 绑定
 */
public class WindowsIPInterfaceManager {
    
    // 内存布局定义
    public static final AddressLayout POINTER = ValueLayout.ADDRESS;
    public static final ValueLayout.OfInt DWORD = ValueLayout.JAVA_INT;
    public static final ValueLayout.OfLong DWORD64 = ValueLayout.JAVA_LONG;
    public static final ValueLayout.OfByte BYTE = ValueLayout.JAVA_BYTE;
    public static final ValueLayout.OfShort WORD = ValueLayout.JAVA_SHORT;
    public static final ValueLayout.OfBoolean BOOLEAN_LAYOUT = ValueLayout.JAVA_BOOLEAN;
    
    // 常量定义
    public static final int NO_ERROR = 0;
    public static final int AF_INET = 2;
    public static final int AF_INET6 = 23;
    public static final int SCOPE_LEVEL_COUNT = 16; // Windows定义的 ScopeLevelCount
    
    // NL_ROUTER_DISCOVERY_BEHAVIOR 枚举
    public enum RouterDiscoveryBehavior {
        RouterDiscoveryDisabled(0),
        RouterDiscoveryEnabled(1),
        RouterDiscoveryDhcp(2),
        RouterDiscoveryUnchanged(-1);
        
        private final int value;
        RouterDiscoveryBehavior(int value) { this.value = value; }
        public int getValue() { return value; }
        public static RouterDiscoveryBehavior fromValue(int value) {
            for (RouterDiscoveryBehavior b : values()) {
                if (b.value == value) return b;
            }
            return RouterDiscoveryDisabled;
        }
    }
    
    // NL_LINK_LOCAL_ADDRESS_BEHAVIOR 枚举
    public enum LinkLocalAddressBehavior {
        LinkLocalAlwaysOff(0),
        LinkLocalDelayed(1),
        LinkLocalAlwaysOn(2),
        LinkLocalUnchanged(-1);
        
        private final int value;
        LinkLocalAddressBehavior(int value) { this.value = value; }
        public int getValue() { return value; }
        public static LinkLocalAddressBehavior fromValue(int value) {
            for (LinkLocalAddressBehavior b : values()) {
                if (b.value == value) return b;
            }
            return LinkLocalAlwaysOff;
        }
    }
    
    // NL_INTERFACE_OFFLOAD_ROD 结构体 (位字段)
    public static final GroupLayout NL_INTERFACE_OFFLOAD_ROD_LAYOUT = MemoryLayout.structLayout(
        BYTE.withName("Flags")  // 位字段: 1=NlChecksumSupported, 2=NlOptionsSupported, etc.
    ).withByteAlignment(1);
    
    // NET_LUID 结构 (64位网络接口标识符)
    public static final GroupLayout NET_LUID_LAYOUT = MemoryLayout.structLayout(
        DWORD64.withName("Value")
    ).withByteAlignment(8);
    
    // MIB_IPINTERFACE_ROW 结构体布局 (64位系统，简化版本)
    // 注意：实际结构体大小可能因Windows版本而异，这里使用简化的布局
    public static final GroupLayout MIB_IPINTERFACE_ROW_LAYOUT;
    
    static {
        // 在64位系统上，结构体按照8字节对齐
        // 这是基于Windows SDK头文件的简化布局
        MIB_IPINTERFACE_ROW_LAYOUT = MemoryLayout.structLayout(
            // 键字段
            WORD.withName("Family"),              // ADDRESS_FAMILY (2字节)
            MemoryLayout.paddingLayout(6),        // 填充到8字节对齐
            
            NET_LUID_LAYOUT.withName("InterfaceLuid"),
            DWORD.withName("InterfaceIndex"),
            
            // IP接口属性
            DWORD.withName("MaxReassemblySize"),
            DWORD64.withName("InterfaceIdentifier"),
            DWORD.withName("MinRouterAdvertisementInterval"),
            DWORD.withName("MaxRouterAdvertisementInterval"),
            BOOLEAN_LAYOUT.withName("AdvertisingEnabled"),
            BOOLEAN_LAYOUT.withName("ForwardingEnabled"),
            BOOLEAN_LAYOUT.withName("WeakHostSend"),
            BOOLEAN_LAYOUT.withName("WeakHostReceive"),
            BOOLEAN_LAYOUT.withName("UseAutomaticMetric"),
            BOOLEAN_LAYOUT.withName("UseNeighborUnreachabilityDetection"),
            BOOLEAN_LAYOUT.withName("ManagedAddressConfigurationSupported"),
            BOOLEAN_LAYOUT.withName("OtherStatefulConfigurationSupported"),
            BOOLEAN_LAYOUT.withName("AdvertiseDefaultRoute"),
            MemoryLayout.paddingLayout(3),        // 填充到4字节对齐
            
            DWORD.withName("RouterDiscoveryBehavior"),
            
            DWORD.withName("DadTransmits"),
            DWORD.withName("BaseReachableTime"),
            DWORD.withName("RetransmitTime"),
            DWORD.withName("PathMtuDiscoveryTimeout"),
            
            DWORD.withName("LinkLocalAddressBehavior"),
            
            DWORD.withName("LinkLocalAddressTimeout"),
            
            // ZoneIndices 数组 (16个ULONG)
            MemoryLayout.sequenceLayout(SCOPE_LEVEL_COUNT, DWORD).withName("ZoneIndices"),
            
            DWORD.withName("SitePrefixLength"),
            DWORD.withName("Metric"),
            DWORD.withName("NlMtu"),
            
            BOOLEAN_LAYOUT.withName("Connected"),
            BOOLEAN_LAYOUT.withName("SupportsWakeUpPatterns"),
            BOOLEAN_LAYOUT.withName("SupportsNeighborDiscovery"),
            BOOLEAN_LAYOUT.withName("SupportsRouterDiscovery"),
            
            DWORD.withName("ReachableTime"),
            
            NL_INTERFACE_OFFLOAD_ROD_LAYOUT.withName("TransmitOffload"),
            NL_INTERFACE_OFFLOAD_ROD_LAYOUT.withName("ReceiveOffload"),
            MemoryLayout.paddingLayout(6),        // 填充到8字节对齐
            
            BOOLEAN_LAYOUT.withName("DisableDefaultRoutes"),
            MemoryLayout.paddingLayout(7)         // 填充到8字节对齐
        ).withByteAlignment(8);
    }
    
    // Native库加载
    private static final SymbolLookup LOOKUP;
    private static final Linker LINKER = Linker.nativeLinker();
    
    // 方法句柄
    private static final MethodHandle GET_IP_INTERFACE_ENTRY;
    private static final MethodHandle SET_IP_INTERFACE_ENTRY;
    
    static {
        try {
            // 加载iphlpapi.dll
            System.loadLibrary("iphlpapi");
            LOOKUP = SymbolLookup.loaderLookup();
            
            // 定义函数描述符
            
            // DWORD GetIpInterfaceEntry(
            //   PMIB_IPINTERFACE_ROW Row
            // );
            FunctionDescriptor getIpInterfaceEntryDesc = FunctionDescriptor.of(
                DWORD,      // 返回值: DWORD
                POINTER     // Row: PMIB_IPINTERFACE_ROW
            );
            
            // DWORD SetIpInterfaceEntry(
            //   PMIB_IPINTERFACE_ROW Row
            // );
            FunctionDescriptor setIpInterfaceEntryDesc = FunctionDescriptor.of(
                DWORD,      // 返回值: DWORD
                POINTER     // Row: PMIB_IPINTERFACE_ROW
            );
            
            // 获取函数句柄
            GET_IP_INTERFACE_ENTRY = LINKER.downcallHandle(
                LOOKUP.find("GetIpInterfaceEntry").orElseThrow(),
                getIpInterfaceEntryDesc
            );
            
            SET_IP_INTERFACE_ENTRY = LINKER.downcallHandle(
                LOOKUP.find("SetIpInterfaceEntry").orElseThrow(),
                setIpInterfaceEntryDesc
            );
            
        } catch (Throwable e) {
            throw new RuntimeException("Failed to initialize Windows IP interface manager", e);
        }
    }
    
    /**
     * MIB_IPINTERFACE_ROW 的 Java 对象表示
     */
    public static class MibIpInterfaceRow {
        private int family;
        private long interfaceLuid;
        private int interfaceIndex;
        private int maxReassemblySize;
        private long interfaceIdentifier;
        private int minRouterAdvertisementInterval;
        private int maxRouterAdvertisementInterval;
        private boolean advertisingEnabled;
        private boolean forwardingEnabled;
        private boolean weakHostSend;
        private boolean weakHostReceive;
        private boolean useAutomaticMetric;
        private boolean useNeighborUnreachabilityDetection;
        private boolean managedAddressConfigurationSupported;
        private boolean otherStatefulConfigurationSupported;
        private boolean advertiseDefaultRoute;
        private RouterDiscoveryBehavior routerDiscoveryBehavior;
        private int dadTransmits;
        private int baseReachableTime;
        private int retransmitTime;
        private int pathMtuDiscoveryTimeout;
        private LinkLocalAddressBehavior linkLocalAddressBehavior;
        private int linkLocalAddressTimeout;
        private int[] zoneIndices;
        private int sitePrefixLength;
        private int metric;
        private int nlMtu;
        private boolean connected;
        private boolean supportsWakeUpPatterns;
        private boolean supportsNeighborDiscovery;
        private boolean supportsRouterDiscovery;
        private int reachableTime;
        private byte transmitOffloadFlags;
        private byte receiveOffloadFlags;
        private boolean disableDefaultRoutes;
        
        // 空构造器
        public MibIpInterfaceRow() {}
        
        // 从内存段创建对象
        public static MibIpInterfaceRow fromMemorySegment(MemorySegment segment) {
            MibIpInterfaceRow row = new MibIpInterfaceRow();
            
            // 计算字段偏移量
            // 使用手动计算的偏移量，因为结构体布局复杂
            long offset = 0;
            
            row.family = segment.get(WORD, offset);
            offset += 8; // 2字节 + 6字节填充
            
            row.interfaceLuid = segment.get(DWORD64, offset);
            offset += 8;
            
            row.interfaceIndex = segment.get(DWORD, offset);
            offset += 4; // 4字节 
            
            row.maxReassemblySize = segment.get(DWORD, offset);
            offset += 4;
            
            row.interfaceIdentifier = segment.get(DWORD64, offset);
            offset += 8;
            
            row.minRouterAdvertisementInterval = segment.get(DWORD, offset);
            offset += 4;
            
            row.maxRouterAdvertisementInterval = segment.get(DWORD, offset);
            offset += 4;
            
            row.advertisingEnabled = segment.get(BOOLEAN_LAYOUT, offset++);
            row.forwardingEnabled = segment.get(BOOLEAN_LAYOUT, offset++);
            row.weakHostSend = segment.get(BOOLEAN_LAYOUT, offset++);
            row.weakHostReceive = segment.get(BOOLEAN_LAYOUT, offset++);
            row.useAutomaticMetric = segment.get(BOOLEAN_LAYOUT, offset++);
            row.useNeighborUnreachabilityDetection = segment.get(BOOLEAN_LAYOUT, offset++);
            row.managedAddressConfigurationSupported = segment.get(BOOLEAN_LAYOUT, offset++);
            row.otherStatefulConfigurationSupported = segment.get(BOOLEAN_LAYOUT, offset++);
            row.advertiseDefaultRoute = segment.get(BOOLEAN_LAYOUT, offset++);
            
            offset += 3; // 跳过3字节填充
            
            row.routerDiscoveryBehavior = RouterDiscoveryBehavior.fromValue(segment.get(DWORD, offset));
            offset += 4;
            
            row.dadTransmits = segment.get(DWORD, offset);
            offset += 4;
            
            row.baseReachableTime = segment.get(DWORD, offset);
            offset += 4;
            
            row.retransmitTime = segment.get(DWORD, offset);
            offset += 4;
            
            row.pathMtuDiscoveryTimeout = segment.get(DWORD, offset);
            offset += 4;
            
            row.linkLocalAddressBehavior = LinkLocalAddressBehavior.fromValue(segment.get(DWORD, offset));
            offset += 4;
            
            row.linkLocalAddressTimeout = segment.get(DWORD, offset);
            offset += 4;
            
            // ZoneIndices 数组
            row.zoneIndices = new int[SCOPE_LEVEL_COUNT];
            for (int i = 0; i < SCOPE_LEVEL_COUNT; i++) {
                row.zoneIndices[i] = segment.get(DWORD, offset);
                offset += 4;
            }
            
            row.sitePrefixLength = segment.get(DWORD, offset);
            offset += 4;
            
            row.metric = segment.get(DWORD, offset);
            offset += 4;
            
            row.nlMtu = segment.get(DWORD, offset);
            offset += 4;
            
            row.connected = segment.get(BOOLEAN_LAYOUT, offset++);
            row.supportsWakeUpPatterns = segment.get(BOOLEAN_LAYOUT, offset++);
            row.supportsNeighborDiscovery = segment.get(BOOLEAN_LAYOUT, offset++);
            row.supportsRouterDiscovery = segment.get(BOOLEAN_LAYOUT, offset++);
            
            
            row.reachableTime = segment.get(DWORD, offset);
            offset += 4; // 4字节 
            
            row.transmitOffloadFlags = segment.get(BYTE, offset++);
            offset += 1; // NL_INTERFACE_OFFLOAD_ROD 的填充
            
            row.receiveOffloadFlags = segment.get(BYTE, offset++);
            offset += 6; // NL_INTERFACE_OFFLOAD_ROD 的填充 + 填充到8字节对齐
            
            row.disableDefaultRoutes = segment.get(BOOLEAN_LAYOUT, offset);
            
            return row;
        }
        
        // 将对象转换为内存段
        public MemorySegment toMemorySegment(Arena arena) {
            MemorySegment segment = arena.allocate(MIB_IPINTERFACE_ROW_LAYOUT);
            long offset = 0;
            
            segment.set(WORD, offset, (short) family);
            offset += 8; // 2字节 + 6字节填充
            
            segment.set(DWORD64, offset, interfaceLuid);
            offset += 8;
            
            segment.set(DWORD, offset, interfaceIndex);
            offset += 4; // 4字节
            
            segment.set(DWORD, offset, maxReassemblySize);
            offset += 4;
            
            segment.set(DWORD64, offset, interfaceIdentifier);
            offset += 8;
            
            segment.set(DWORD, offset, minRouterAdvertisementInterval);
            offset += 4;
            
            segment.set(DWORD, offset, maxRouterAdvertisementInterval);
            offset += 4;
            
            segment.set(BOOLEAN_LAYOUT, offset++, advertisingEnabled);
            segment.set(BOOLEAN_LAYOUT, offset++, forwardingEnabled);
            segment.set(BOOLEAN_LAYOUT, offset++, weakHostSend);
            segment.set(BOOLEAN_LAYOUT, offset++, weakHostReceive);
            segment.set(BOOLEAN_LAYOUT, offset++, useAutomaticMetric);
            segment.set(BOOLEAN_LAYOUT, offset++, useNeighborUnreachabilityDetection);
            segment.set(BOOLEAN_LAYOUT, offset++, managedAddressConfigurationSupported);
            segment.set(BOOLEAN_LAYOUT, offset++, otherStatefulConfigurationSupported);
            segment.set(BOOLEAN_LAYOUT, offset++, advertiseDefaultRoute);
            
            offset += 3; // 跳过3字节填充

            if(routerDiscoveryBehavior!=null)
            segment.set(DWORD, offset, routerDiscoveryBehavior.getValue());
            offset += 4;
            
            segment.set(DWORD, offset, dadTransmits);
            offset += 4;
            
            segment.set(DWORD, offset, baseReachableTime);
            offset += 4;
            
            segment.set(DWORD, offset, retransmitTime);
            offset += 4;
            
            segment.set(DWORD, offset, pathMtuDiscoveryTimeout);
            offset += 4;
            if(linkLocalAddressBehavior!=null)
            segment.set(DWORD, offset, linkLocalAddressBehavior.getValue());
            offset += 4;
            
            segment.set(DWORD, offset, linkLocalAddressTimeout);
            offset += 4;
            
            // ZoneIndices 数组
            if(zoneIndices!=null)
            for (int i = 0; i < SCOPE_LEVEL_COUNT; i++) {
                segment.set(DWORD, offset, zoneIndices[i]);
                offset += 4;
            }
            
            segment.set(DWORD, offset, sitePrefixLength);
            offset += 4;
            
            segment.set(DWORD, offset, metric);
            offset += 4;
            
            segment.set(DWORD, offset, nlMtu);
            offset += 4;
            
            segment.set(BOOLEAN_LAYOUT, offset++, connected);
            segment.set(BOOLEAN_LAYOUT, offset++, supportsWakeUpPatterns);
            segment.set(BOOLEAN_LAYOUT, offset++, supportsNeighborDiscovery);
            segment.set(BOOLEAN_LAYOUT, offset++, supportsRouterDiscovery);
            
            
            segment.set(DWORD, offset, reachableTime);
            offset += 4; // 4字节
            
            segment.set(BYTE, offset++, transmitOffloadFlags);
            offset += 1; // NL_INTERFACE_OFFLOAD_ROD 的填充
            
            segment.set(BYTE, offset++, receiveOffloadFlags);
            offset += 6; // NL_INTERFACE_OFFLOAD_ROD 的填充 + 填充到8字节对齐
            
            segment.set(BOOLEAN_LAYOUT, offset, disableDefaultRoutes);
            
            return segment;
        }
        
        // 创建简单的构建器方法
        public static MibIpInterfaceRow createForInterface(long interfaceLuid, int family) {
            MibIpInterfaceRow row = new MibIpInterfaceRow();
            row.family = family;
            row.interfaceLuid = interfaceLuid;
            row.interfaceIndex = 0; // 将由系统填充
            
            // 设置合理的默认值
            row.maxReassemblySize = 65535;
            row.minRouterAdvertisementInterval = 0;
            row.maxRouterAdvertisementInterval = 0;
            row.advertisingEnabled = false;
            row.forwardingEnabled = false;
            row.weakHostSend = false;
            row.weakHostReceive = false;
            row.useAutomaticMetric = true;
            row.useNeighborUnreachabilityDetection = true;
            row.managedAddressConfigurationSupported = false;
            row.otherStatefulConfigurationSupported = false;
            row.advertiseDefaultRoute = false;
            row.routerDiscoveryBehavior = RouterDiscoveryBehavior.RouterDiscoveryDisabled;
            row.dadTransmits = 0;
            row.baseReachableTime = 0;
            row.retransmitTime = 0;
            row.pathMtuDiscoveryTimeout = 0;
            row.linkLocalAddressBehavior = LinkLocalAddressBehavior.LinkLocalAlwaysOn;
            row.linkLocalAddressTimeout = 0;
            
            row.zoneIndices = new int[SCOPE_LEVEL_COUNT];
            for (int i = 0; i < SCOPE_LEVEL_COUNT; i++) {
                row.zoneIndices[i] = 0;
            }
            
            row.sitePrefixLength = 0;
            row.metric = 0; // 自动计算
            row.nlMtu = 1500; // 默认MTU
            row.connected = true;
            row.supportsWakeUpPatterns = false;
            row.supportsNeighborDiscovery = true;
            row.supportsRouterDiscovery = false;
            row.reachableTime = 0;
            row.transmitOffloadFlags = 0;
            row.receiveOffloadFlags = 0;
            row.disableDefaultRoutes = false;
            
            return row;
        }
        
        // Getters 和 Setters (由于字段太多，只列出关键字段)
        public int getFamily() { return family; }
        public void setFamily(int family) { this.family = family; }
        
        public long getInterfaceLuid() { return interfaceLuid; }
        public void setInterfaceLuid(long interfaceLuid) { this.interfaceLuid = interfaceLuid; }
        
        public int getInterfaceIndex() { return interfaceIndex; }
        public void setInterfaceIndex(int interfaceIndex) { this.interfaceIndex = interfaceIndex; }
        
        public int getNlMtu() { return nlMtu; }
        public void setNlMtu(int nlMtu) { this.nlMtu = nlMtu; }
        
        public int getMetric() { return metric; }
        public void setMetric(int metric) { this.metric = metric; }
        
        public boolean isForwardingEnabled() { return forwardingEnabled; }
        public void setForwardingEnabled(boolean forwardingEnabled) { this.forwardingEnabled = forwardingEnabled; }
        
        public boolean isAdvertisingEnabled() { return advertisingEnabled; }
        public void setAdvertisingEnabled(boolean advertisingEnabled) { this.advertisingEnabled = advertisingEnabled; }
        
        public boolean isConnected() { return connected; }
        public void setConnected(boolean connected) { this.connected = connected; }
        
        public int getMaxReassemblySize() {
			return maxReassemblySize;
		}

		public void setMaxReassemblySize(int maxReassemblySize) {
			this.maxReassemblySize = maxReassemblySize;
		}

		public long getInterfaceIdentifier() {
			return interfaceIdentifier;
		}

		public void setInterfaceIdentifier(long interfaceIdentifier) {
			this.interfaceIdentifier = interfaceIdentifier;
		}

		public int getMinRouterAdvertisementInterval() {
			return minRouterAdvertisementInterval;
		}

		public void setMinRouterAdvertisementInterval(int minRouterAdvertisementInterval) {
			this.minRouterAdvertisementInterval = minRouterAdvertisementInterval;
		}

		public int getMaxRouterAdvertisementInterval() {
			return maxRouterAdvertisementInterval;
		}

		public void setMaxRouterAdvertisementInterval(int maxRouterAdvertisementInterval) {
			this.maxRouterAdvertisementInterval = maxRouterAdvertisementInterval;
		}

		public boolean isWeakHostSend() {
			return weakHostSend;
		}

		public void setWeakHostSend(boolean weakHostSend) {
			this.weakHostSend = weakHostSend;
		}

		public boolean isWeakHostReceive() {
			return weakHostReceive;
		}

		public void setWeakHostReceive(boolean weakHostReceive) {
			this.weakHostReceive = weakHostReceive;
		}

		public boolean isUseAutomaticMetric() {
			return useAutomaticMetric;
		}

		public void setUseAutomaticMetric(boolean useAutomaticMetric) {
			this.useAutomaticMetric = useAutomaticMetric;
		}

		public boolean isUseNeighborUnreachabilityDetection() {
			return useNeighborUnreachabilityDetection;
		}

		public void setUseNeighborUnreachabilityDetection(boolean useNeighborUnreachabilityDetection) {
			this.useNeighborUnreachabilityDetection = useNeighborUnreachabilityDetection;
		}

		public boolean isManagedAddressConfigurationSupported() {
			return managedAddressConfigurationSupported;
		}

		public void setManagedAddressConfigurationSupported(boolean managedAddressConfigurationSupported) {
			this.managedAddressConfigurationSupported = managedAddressConfigurationSupported;
		}

		public boolean isOtherStatefulConfigurationSupported() {
			return otherStatefulConfigurationSupported;
		}

		public void setOtherStatefulConfigurationSupported(boolean otherStatefulConfigurationSupported) {
			this.otherStatefulConfigurationSupported = otherStatefulConfigurationSupported;
		}

		public boolean isAdvertiseDefaultRoute() {
			return advertiseDefaultRoute;
		}

		public void setAdvertiseDefaultRoute(boolean advertiseDefaultRoute) {
			this.advertiseDefaultRoute = advertiseDefaultRoute;
		}

		public RouterDiscoveryBehavior getRouterDiscoveryBehavior() {
			return routerDiscoveryBehavior;
		}

		public void setRouterDiscoveryBehavior(RouterDiscoveryBehavior routerDiscoveryBehavior) {
			this.routerDiscoveryBehavior = routerDiscoveryBehavior;
		}

		public int getDadTransmits() {
			return dadTransmits;
		}

		public void setDadTransmits(int dadTransmits) {
			this.dadTransmits = dadTransmits;
		}

		public int getBaseReachableTime() {
			return baseReachableTime;
		}

		public void setBaseReachableTime(int baseReachableTime) {
			this.baseReachableTime = baseReachableTime;
		}

		public int getRetransmitTime() {
			return retransmitTime;
		}

		public void setRetransmitTime(int retransmitTime) {
			this.retransmitTime = retransmitTime;
		}

		public int getPathMtuDiscoveryTimeout() {
			return pathMtuDiscoveryTimeout;
		}

		public void setPathMtuDiscoveryTimeout(int pathMtuDiscoveryTimeout) {
			this.pathMtuDiscoveryTimeout = pathMtuDiscoveryTimeout;
		}

		public LinkLocalAddressBehavior getLinkLocalAddressBehavior() {
			return linkLocalAddressBehavior;
		}

		public void setLinkLocalAddressBehavior(LinkLocalAddressBehavior linkLocalAddressBehavior) {
			this.linkLocalAddressBehavior = linkLocalAddressBehavior;
		}

		public int getLinkLocalAddressTimeout() {
			return linkLocalAddressTimeout;
		}

		public void setLinkLocalAddressTimeout(int linkLocalAddressTimeout) {
			this.linkLocalAddressTimeout = linkLocalAddressTimeout;
		}

		public int[] getZoneIndices() {
			return zoneIndices;
		}

		public void setZoneIndices(int[] zoneIndices) {
			this.zoneIndices = zoneIndices;
		}

		public int getSitePrefixLength() {
			return sitePrefixLength;
		}

		public void setSitePrefixLength(int sitePrefixLength) {
			this.sitePrefixLength = sitePrefixLength;
		}

		public boolean isSupportsWakeUpPatterns() {
			return supportsWakeUpPatterns;
		}

		public void setSupportsWakeUpPatterns(boolean supportsWakeUpPatterns) {
			this.supportsWakeUpPatterns = supportsWakeUpPatterns;
		}

		public boolean isSupportsNeighborDiscovery() {
			return supportsNeighborDiscovery;
		}

		public void setSupportsNeighborDiscovery(boolean supportsNeighborDiscovery) {
			this.supportsNeighborDiscovery = supportsNeighborDiscovery;
		}

		public boolean isSupportsRouterDiscovery() {
			return supportsRouterDiscovery;
		}

		public void setSupportsRouterDiscovery(boolean supportsRouterDiscovery) {
			this.supportsRouterDiscovery = supportsRouterDiscovery;
		}

		public int getReachableTime() {
			return reachableTime;
		}

		public void setReachableTime(int reachableTime) {
			this.reachableTime = reachableTime;
		}

		public byte getTransmitOffloadFlags() {
			return transmitOffloadFlags;
		}

		public void setTransmitOffloadFlags(byte transmitOffloadFlags) {
			this.transmitOffloadFlags = transmitOffloadFlags;
		}

		public byte getReceiveOffloadFlags() {
			return receiveOffloadFlags;
		}

		public void setReceiveOffloadFlags(byte receiveOffloadFlags) {
			this.receiveOffloadFlags = receiveOffloadFlags;
		}

		public boolean isDisableDefaultRoutes() {
			return disableDefaultRoutes;
		}

		public void setDisableDefaultRoutes(boolean disableDefaultRoutes) {
			this.disableDefaultRoutes = disableDefaultRoutes;
		}

		@Override
		public String toString() {
			return "MibIpInterfaceRow [family=" + family + ", interfaceLuid=" + interfaceLuid + ", interfaceIndex="
					+ interfaceIndex + ", maxReassemblySize=" + maxReassemblySize + ", interfaceIdentifier="
					+ interfaceIdentifier + ", minRouterAdvertisementInterval=" + minRouterAdvertisementInterval
					+ ", maxRouterAdvertisementInterval=" + maxRouterAdvertisementInterval + ", advertisingEnabled="
					+ advertisingEnabled + ", forwardingEnabled=" + forwardingEnabled + ", weakHostSend=" + weakHostSend
					+ ", weakHostReceive=" + weakHostReceive + ", useAutomaticMetric=" + useAutomaticMetric
					+ ", useNeighborUnreachabilityDetection=" + useNeighborUnreachabilityDetection
					+ ", managedAddressConfigurationSupported=" + managedAddressConfigurationSupported
					+ ", otherStatefulConfigurationSupported=" + otherStatefulConfigurationSupported
					+ ", advertiseDefaultRoute=" + advertiseDefaultRoute + ", routerDiscoveryBehavior="
					+ routerDiscoveryBehavior + ", dadTransmits=" + dadTransmits + ", baseReachableTime="
					+ baseReachableTime + ", retransmitTime=" + retransmitTime + ", pathMtuDiscoveryTimeout="
					+ pathMtuDiscoveryTimeout + ", linkLocalAddressBehavior=" + linkLocalAddressBehavior
					+ ", linkLocalAddressTimeout=" + linkLocalAddressTimeout + ", zoneIndices="
					+ Arrays.toString(zoneIndices) + ", sitePrefixLength=" + sitePrefixLength + ", metric=" + metric
					+ ", nlMtu=" + nlMtu + ", connected=" + connected + ", supportsWakeUpPatterns="
					+ supportsWakeUpPatterns + ", supportsNeighborDiscovery=" + supportsNeighborDiscovery
					+ ", supportsRouterDiscovery=" + supportsRouterDiscovery + ", reachableTime=" + reachableTime
					+ ", transmitOffloadFlags=" + transmitOffloadFlags + ", receiveOffloadFlags=" + receiveOffloadFlags
					+ ", disableDefaultRoutes=" + disableDefaultRoutes + "]";
		}
    }
    
    /**
     * 获取 IP 接口条目
     * @param row 包含接口标识信息的行，函数会填充其他字段
     * @return 填充后的接口行
     * @throws WindowsAPIException 如果操作失败
     */
    public static MibIpInterfaceRow getIpInterfaceEntry(MibIpInterfaceRow row) throws WindowsAPIException {
        try (Arena arena = Arena.ofConfined()) {
            // 创建内存段
            MemorySegment rowSegment = row.toMemorySegment(arena);
            
            // 调用 GetIpInterfaceEntry
            int result = (int) GET_IP_INTERFACE_ENTRY.invokeExact(rowSegment);
            
            if (result != NO_ERROR) {
                throw new WindowsAPIException("GetIpInterfaceEntry failed", result);
            }
            
            // 从内存段读取更新后的行
            return MibIpInterfaceRow.fromMemorySegment(rowSegment);
            
        } catch (Throwable e) {
            throw new RuntimeException("Error calling GetIpInterfaceEntry", e);
        }
    }
    
    /**
     * 设置 IP 接口条目
     * @param row 要设置的接口行
     * @throws WindowsAPIException 如果操作失败
     */
    public static void setIpInterfaceEntry(MibIpInterfaceRow row) throws WindowsAPIException {
        try (Arena arena = Arena.ofConfined()) {
            // 创建内存段
            MemorySegment rowSegment = row.toMemorySegment(arena);
            
            // 调用 SetIpInterfaceEntry
            int result = (int) SET_IP_INTERFACE_ENTRY.invokeExact(rowSegment);
            
            if (result != NO_ERROR) {
                throw new WindowsAPIException("SetIpInterfaceEntry failed", result);
            }
            
        } catch (Throwable e) {
            throw new RuntimeException("Error calling SetIpInterfaceEntry", e);
        }
    }
    
    /**
     * 获取指定接口的 IP 接口信息
     * @param interfaceLuid 接口 LUID
     * @param family 地址族 (AF_INET 或 AF_INET6)
     * @return 接口信息
     * @throws WindowsAPIException 如果操作失败
     */
    public static MibIpInterfaceRow getInterfaceInfo(long interfaceLuid, int family) throws WindowsAPIException {
        // 创建只包含键字段的行
        MibIpInterfaceRow row = new MibIpInterfaceRow();
        row.setFamily(family);
        row.setInterfaceLuid(interfaceLuid);
        row.setInterfaceIndex(0); // 将由系统填充
        
        // 获取完整信息
        return getIpInterfaceEntry(row);
    }
    
    /**
     * 设置接口的 MTU
     * @param interfaceLuid 接口 LUID
     * @param family 地址族 (AF_INET 或 AF_INET6)
     * @param mtu MTU 值
     * @throws WindowsAPIException 如果操作失败
     */
    public static void setInterfaceMtu(long interfaceLuid, int family, int mtu) throws WindowsAPIException {
        // 1. 获取当前配置
        MibIpInterfaceRow row = getInterfaceInfo(interfaceLuid, family);
        row.setSitePrefixLength(0);
        // 2. 修改 MTU
        row.setNlMtu(mtu);
        
        // 3. 设置回系统
        setIpInterfaceEntry(row);
    }
    
    /**
     * 设置接口的路由度量值
     * @param interfaceLuid 接口 LUID
     * @param family 地址族 (AF_INET 或 AF_INET6)
     * @param metric 度量值 (越小优先级越高)
     * @throws WindowsAPIException 如果操作失败
     */
    public static void setInterfaceMetric(long interfaceLuid, int family, int metric) throws WindowsAPIException {
        // 1. 获取当前配置
        MibIpInterfaceRow row = getInterfaceInfo(interfaceLuid, family);
        
        // 2. 修改度量值
        row.setMetric(metric);
        
        // 3. 设置回系统
        setIpInterfaceEntry(row);
    }
    
    /**
     * 启用/禁用接口的 IP 转发
     * @param interfaceLuid 接口 LUID
     * @param family 地址族 (AF_INET 或 AF_INET6)
     * @param enable 是否启用转发
     * @throws WindowsAPIException 如果操作失败
     */
    public static void setInterfaceForwarding(long interfaceLuid, int family, boolean enable) throws WindowsAPIException {
        // 1. 获取当前配置
        MibIpInterfaceRow row = getInterfaceInfo(interfaceLuid, family);
        
        // 2. 修改转发设置
        row.setForwardingEnabled(enable);
        
        // 3. 设置回系统
        setIpInterfaceEntry(row);
    }
    
    
    /**
     * 测试方法
     */
    public static void main(String[] args) {
        try {
            System.out.println("=== Windows IP Interface Manager Test ===");
            
            // 示例：假设我们有一个 Wintun 适配器的 LUID
            long wintunLuid = 14918723638919168L;
            
            System.out.println("\n1. Testing IPv4 interface info:");
            try {
                MibIpInterfaceRow ipv4Info = getInterfaceInfo(wintunLuid, AF_INET);
                System.out.println("   " + ipv4Info);
                System.out.println("   Current MTU: " + ipv4Info.getNlMtu());
                System.out.println("   Current metric: " + ipv4Info.getMetric());
                System.out.println("   Forwarding enabled: " + ipv4Info.isForwardingEnabled());
            } catch (WindowsAPIException e) {
                System.out.println("   Failed to get IPv4 info: " + e.getMessage());
            }
            
            System.out.println("\n2. Testing IPv6 interface info:");
            try {
                MibIpInterfaceRow ipv6Info = getInterfaceInfo(wintunLuid, AF_INET6);
                System.out.println("   " + ipv6Info);
                System.out.println("   Current MTU: " + ipv6Info.getNlMtu());
                System.out.println("   Current metric: " + ipv6Info.getMetric());
                System.out.println("   Forwarding enabled: " + ipv6Info.isForwardingEnabled());
            } catch (WindowsAPIException e) {
                System.out.println("   Failed to get IPv6 info: " + e.getMessage());
            }
            
            System.out.println("\n3. Testing MTU setting:");
            try {
                // 注意：需要管理员权限
                 setInterfaceMtu(wintunLuid, AF_INET, 1800);
                 System.out.println("   Set IPv4 MTU to 1800");
                System.out.println("   (MTU setting requires administrator privileges)");
            } catch (Exception e) {
            	e.printStackTrace();
            }
            
            System.out.println("\nTest completed!");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}