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

/**
 * Windows 网络接口管理类
 * 实现 GetIfEntry 和 SetIfEntry 功能，提供 MIB_IFROW 结构的 Java 对象封装
 */
public class WindowsInterfaceManager2 {
    
    // 内存布局
    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 int MAX_INTERFACE_NAME_LEN = 256;
    public static final int MAXLEN_PHYSADDR = 32;
    public static final int MAXLEN_IFDESCR = 256;
    public static final int NO_ERROR = 0;
    
    // 接口类型常量 (部分常见类型)
    public static final int IF_TYPE_ETHERNET_CSMACD = 6;
    public static final int IF_TYPE_ISO88025_TOKENRING = 9;
    public static final int IF_TYPE_PPP = 23;
    public static final int IF_TYPE_SOFTWARE_LOOPBACK = 24;
    public static final int IF_TYPE_ATM = 37;
    public static final int IF_TYPE_IEEE80211 = 71;
    public static final int IF_TYPE_TUNNEL = 131;
    public static final int IF_TYPE_IEEE1394 = 144;
    
    // 管理状态常量
    public static final int MIB_IF_ADMIN_STATUS_UP = 1;
    public static final int MIB_IF_ADMIN_STATUS_DOWN = 2;
    public static final int MIB_IF_ADMIN_STATUS_TESTING = 3;
    
    // 操作状态常量
    public static final int IF_OPER_STATUS_NON_OPERATIONAL = 0;
    public static final int IF_OPER_STATUS_UNREACHABLE = 1;
    public static final int IF_OPER_STATUS_DISCONNECTED = 2;
    public static final int IF_OPER_STATUS_CONNECTING = 3;
    public static final int IF_OPER_STATUS_CONNECTED = 4;
    public static final int IF_OPER_STATUS_OPERATIONAL = 5;
    
    // MIB_IFROW 结构体布局
    public static final GroupLayout MIB_IFROW_LAYOUT;
    
    static {
        // 手动计算偏移量以确保正确对齐
        // 注意：所有字段都是 4 字节对齐的
        long offset = 0;
        
        // 1. wszName: WCHAR[MAX_INTERFACE_NAME_LEN] (512 字节)
        // 需要 2 字节对齐，但结构体开始通常是 4 字节对齐
        var wszNameLayout = MemoryLayout.sequenceLayout(MAX_INTERFACE_NAME_LEN, WORD)
            .withName("wszName")
            .withByteAlignment(2);
        
        offset += MAX_INTERFACE_NAME_LEN * 2;  // 512 字节
        
        // 2. dwIndex: IF_INDEX (4 字节)
        // offset = 512, 是 4 的倍数
        var dwIndexLayout = DWORD
            .withName("dwIndex")
            .withByteAlignment(4);
        
        offset += 4;  // 516 字节
        
        // 3. dwType: IFTYPE (4 字节)
        // offset = 516, 是 4 的倍数
        var dwTypeLayout = DWORD
            .withName("dwType")
            .withByteAlignment(4);
        
        offset += 4;  // 520 字节
        
        // 4. dwMtu: DWORD (4 字节)
        // offset = 520, 是 4 的倍数
        var dwMtuLayout = DWORD
            .withName("dwMtu")
            .withByteAlignment(4);
        
        offset += 4;  // 524 字节
        
        // 5. dwSpeed: DWORD (4 字节)
        // offset = 524, 是 4 的倍数
        var dwSpeedLayout = DWORD
            .withName("dwSpeed")
            .withByteAlignment(4);
        
        offset += 4;  // 528 字节
        
        // 6. dwPhysAddrLen: DWORD (4 字节)
        // offset = 528, 是 4 的倍数
        var dwPhysAddrLenLayout = DWORD
            .withName("dwPhysAddrLen")
            .withByteAlignment(4);
        
        offset += 4;  // 532 字节
        
        // 7. bPhysAddr: UCHAR[MAXLEN_PHYSADDR] (32 字节)
        // offset = 532, 是 1 的倍数，但数组本身 1 字节对齐
        // 实际上需要 4 字节对齐，532 是 4 的倍数 (532 % 4 = 0)
        var bPhysAddrLayout = MemoryLayout.sequenceLayout(MAXLEN_PHYSADDR, BYTE)
            .withName("bPhysAddr")
            .withByteAlignment(1);
        
        offset += MAXLEN_PHYSADDR;  // 564 字节
        
        // 8. dwAdminStatus: DWORD (4 字节)
        // offset = 564, 是 4 的倍数
        var dwAdminStatusLayout = DWORD
            .withName("dwAdminStatus")
            .withByteAlignment(4);
        
        offset += 4;  // 568 字节
        
        // 9. dwOperStatus: INTERNAL_IF_OPER_STATUS (4 字节)
        // offset = 568, 是 4 的倍数
        var dwOperStatusLayout = DWORD
            .withName("dwOperStatus")
            .withByteAlignment(4);
        
        offset += 4;  // 572 字节
        
        // 10. dwLastChange: DWORD (4 字节)
        // offset = 572, 是 4 的倍数
        var dwLastChangeLayout = DWORD
            .withName("dwLastChange")
            .withByteAlignment(4);
        
        offset += 4;  // 576 字节
        
        // 11. dwInOctets: DWORD (4 字节)
        // offset = 576, 是 4 的倍数
        var dwInOctetsLayout = DWORD
            .withName("dwInOctets")
            .withByteAlignment(4);
        
        offset += 4;  // 580 字节
        
        // 12. dwInUcastPkts: DWORD (4 字节)
        // offset = 580, 是 4 的倍数
        var dwInUcastPktsLayout = DWORD
            .withName("dwInUcastPkts")
            .withByteAlignment(4);
        
        offset += 4;  // 584 字节
        
        // 13. dwInNUcastPkts: DWORD (4 字节)
        // offset = 584, 是 4 的倍数
        var dwInNUcastPktsLayout = DWORD
            .withName("dwInNUcastPkts")
            .withByteAlignment(4);
        
        offset += 4;  // 588 字节
        
        // 14. dwInDiscards: DWORD (4 字节)
        // offset = 588, 是 4 的倍数
        var dwInDiscardsLayout = DWORD
            .withName("dwInDiscards")
            .withByteAlignment(4);
        
        offset += 4;  // 592 字节
        
        // 15. dwInErrors: DWORD (4 字节)
        // offset = 592, 是 4 的倍数
        var dwInErrorsLayout = DWORD
            .withName("dwInErrors")
            .withByteAlignment(4);
        
        offset += 4;  // 596 字节
        
        // 16. dwInUnknownProtos: DWORD (4 字节)
        // offset = 596, 是 4 的倍数
        var dwInUnknownProtosLayout = DWORD
            .withName("dwInUnknownProtos")
            .withByteAlignment(4);
        
        offset += 4;  // 600 字节
        
        // 17. dwOutOctets: DWORD (4 字节)
        // offset = 600, 是 4 的倍数
        var dwOutOctetsLayout = DWORD
            .withName("dwOutOctets")
            .withByteAlignment(4);
        
        offset += 4;  // 604 字节
        
        // 18. dwOutUcastPkts: DWORD (4 字节)
        // offset = 604, 是 4 的倍数
        var dwOutUcastPktsLayout = DWORD
            .withName("dwOutUcastPkts")
            .withByteAlignment(4);
        
        offset += 4;  // 608 字节
        
        // 19. dwOutNUcastPkts: DWORD (4 字节)
        // offset = 608, 是 4 的倍数
        var dwOutNUcastPktsLayout = DWORD
            .withName("dwOutNUcastPkts")
            .withByteAlignment(4);
        
        offset += 4;  // 612 字节
        
        // 20. dwOutDiscards: DWORD (4 字节)
        // offset = 612, 是 4 的倍数
        var dwOutDiscardsLayout = DWORD
            .withName("dwOutDiscards")
            .withByteAlignment(4);
        
        offset += 4;  // 616 字节
        
        // 21. dwOutErrors: DWORD (4 字节)
        // offset = 616, 是 4 的倍数
        var dwOutErrorsLayout = DWORD
            .withName("dwOutErrors")
            .withByteAlignment(4);
        
        offset += 4;  // 620 字节
        
        // 22. dwOutQLen: DWORD (4 字节)
        // offset = 620, 是 4 的倍数
        var dwOutQLenLayout = DWORD
            .withName("dwOutQLen")
            .withByteAlignment(4);
        
        offset += 4;  // 624 字节
        
        // 23. dwDescrLen: DWORD (4 字节)
        // offset = 624, 是 4 的倍数
        var dwDescrLenLayout = DWORD
            .withName("dwDescrLen")
            .withByteAlignment(4);
        
        offset += 4;  // 628 字节
        
        // 24. bDescr: UCHAR[MAXLEN_IFDESCR] (256 字节)
        // offset = 628, 是 4 的倍数 (628 % 4 = 0)
        var bDescrLayout = MemoryLayout.sequenceLayout(MAXLEN_IFDESCR, BYTE)
            .withName("bDescr")
            .withByteAlignment(1);
        
        offset += MAXLEN_IFDESCR;  // 884 字节
        
        // 最终布局
        MIB_IFROW_LAYOUT = MemoryLayout.structLayout(
            // wszName: 0-511 字节 (512 字节)
            MemoryLayout.sequenceLayout(MAX_INTERFACE_NAME_LEN, WORD)
                .withName("wszName")
                .withByteAlignment(2),
            
            // dwIndex: 512-515 字节 (4 字节)
            DWORD.withName("dwIndex"),
            
            // dwType: 516-519 字节 (4 字节)
            DWORD.withName("dwType"),
            
            // dwMtu: 520-523 字节 (4 字节)
            DWORD.withName("dwMtu"),
            
            // dwSpeed: 524-527 字节 (4 字节)
            DWORD.withName("dwSpeed"),
            
            // dwPhysAddrLen: 528-531 字节 (4 字节)
            DWORD.withName("dwPhysAddrLen"),
            
            // bPhysAddr: 532-563 字节 (32 字节)
            MemoryLayout.sequenceLayout(MAXLEN_PHYSADDR, BYTE)
                .withName("bPhysAddr")
                .withByteAlignment(1),
            
            // dwAdminStatus: 564-567 字节 (4 字节)
            DWORD.withName("dwAdminStatus"),
            
            // dwOperStatus: 568-571 字节 (4 字节)
            DWORD.withName("dwOperStatus"),
            
            // dwLastChange: 572-575 字节 (4 字节)
            DWORD.withName("dwLastChange"),
            
            // dwInOctets: 576-579 字节 (4 字节)
            DWORD.withName("dwInOctets"),
            
            // dwInUcastPkts: 580-583 字节 (4 字节)
            DWORD.withName("dwInUcastPkts"),
            
            // dwInNUcastPkts: 584-587 字节 (4 字节)
            DWORD.withName("dwInNUcastPkts"),
            
            // dwInDiscards: 588-591 字节 (4 字节)
            DWORD.withName("dwInDiscards"),
            
            // dwInErrors: 592-595 字节 (4 字节)
            DWORD.withName("dwInErrors"),
            
            // dwInUnknownProtos: 596-599 字节 (4 字节)
            DWORD.withName("dwInUnknownProtos"),
            
            // dwOutOctets: 600-603 字节 (4 字节)
            DWORD.withName("dwOutOctets"),
            
            // dwOutUcastPkts: 604-607 字节 (4 字节)
            DWORD.withName("dwOutUcastPkts"),
            
            // dwOutNUcastPkts: 608-611 字节 (4 字节)
            DWORD.withName("dwOutNUcastPkts"),
            
            // dwOutDiscards: 612-615 字节 (4 字节)
            DWORD.withName("dwOutDiscards"),
            
            // dwOutErrors: 616-619 字节 (4 字节)
            DWORD.withName("dwOutErrors"),
            
            // dwOutQLen: 620-623 字节 (4 字节)
            DWORD.withName("dwOutQLen"),
            
            // dwDescrLen: 624-627 字节 (4 字节)
            DWORD.withName("dwDescrLen"),
            
            // bDescr: 628-883 字节 (256 字节)
            MemoryLayout.sequenceLayout(MAXLEN_IFDESCR, BYTE)
                .withName("bDescr")
                .withByteAlignment(1)
        ).withByteAlignment(4);  // 整个结构体 4 字节对齐
    }
    
    private static final SymbolLookup LOOKUP;
    private static final Linker LINKER = Linker.nativeLinker();
    
    // 方法句柄
    private static final MethodHandle GET_IF_ENTRY;
    private static final MethodHandle SET_IF_ENTRY;
    
    static {
        try {
            // 加载 iphlpapi.dll
            System.loadLibrary("iphlpapi");
            LOOKUP = SymbolLookup.loaderLookup();
            
            // GetIfEntry 函数
            // DWORD GetIfEntry(PMIB_IFROW pIfRow);
            FunctionDescriptor getIfEntryDesc = FunctionDescriptor.of(
                DWORD,      // 返回值: DWORD
                POINTER     // pIfRow: PMIB_IFROW
            );
            
            // SetIfEntry 函数
            // DWORD SetIfEntry(const PMIB_IFROW pIfRow);
            FunctionDescriptor setIfEntryDesc = FunctionDescriptor.of(
                DWORD,      // 返回值: DWORD
                POINTER     // pIfRow: const PMIB_IFROW
            );
            
            // 获取方法句柄
            GET_IF_ENTRY = LINKER.downcallHandle(
                LOOKUP.find("GetIfEntry").orElseThrow(),
                getIfEntryDesc
            );
            
            SET_IF_ENTRY = LINKER.downcallHandle(
                LOOKUP.find("SetIfEntry").orElseThrow(),
                setIfEntryDesc
            );
            
        } catch (Throwable e) {
            throw new RuntimeException("Failed to initialize Windows interface manager", e);
        }
    }
    
    /**
     * MIB_IFROW 结构的 Java 对象封装
     */
    public static class MibIfRow {
        private String name;               // 接口名称
        private int index;                 // 接口索引
        private int type;                  // 接口类型
        private int mtu;                   // 最大传输单元
        private long speed;                // 接口速度 (bps)
        private byte[] physAddr;           // 物理地址 (MAC)
        private int adminStatus;           // 管理状态
        private int operStatus;            // 操作状态
        private long lastChange;           // 最后状态改变时间
        private long inOctets;             // 接收字节数
        private long inUcastPkts;          // 接收单播包数
        private long inNUcastPkts;         // 接收非单播包数
        private long inDiscards;           // 接收丢弃数
        private long inErrors;             // 接收错误数
        private long inUnknownProtos;      // 接收未知协议数
        private long outOctets;            // 发送字节数
        private long outUcastPkts;         // 发送单播包数
        private long outNUcastPkts;        // 发送非单播包数
        private long outDiscards;          // 发送丢弃数
        private long outErrors;            // 发送错误数
        private long outQLen;              // 发送队列长度
        private String description;        // 接口描述
        
        public MibIfRow() {
            this.physAddr = new byte[0];
            this.description = "";
        }
        
        // Getters and Setters
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        
        public int getIndex() { return index; }
        public void setIndex(int index) { this.index = index; }
        
        public int getType() { return type; }
        public void setType(int type) { this.type = type; }
        
        public int getMtu() { return mtu; }
        public void setMtu(int mtu) { this.mtu = mtu; }
        
        public long getSpeed() { return speed; }
        public void setSpeed(long speed) { this.speed = speed; }
        
        public byte[] getPhysAddr() { return physAddr; }
        public void setPhysAddr(byte[] physAddr) { this.physAddr = physAddr; }
        
        public int getAdminStatus() { return adminStatus; }
        public void setAdminStatus(int adminStatus) { this.adminStatus = adminStatus; }
        
        public int getOperStatus() { return operStatus; }
        public void setOperStatus(int operStatus) { this.operStatus = operStatus; }
        
        public long getLastChange() { return lastChange; }
        public void setLastChange(long lastChange) { this.lastChange = lastChange; }
        
        public long getInOctets() { return inOctets; }
        public void setInOctets(long inOctets) { this.inOctets = inOctets; }
        
        public long getInUcastPkts() { return inUcastPkts; }
        public void setInUcastPkts(long inUcastPkts) { this.inUcastPkts = inUcastPkts; }
        
        public long getInNUcastPkts() { return inNUcastPkts; }
        public void setInNUcastPkts(long inNUcastPkts) { this.inNUcastPkts = inNUcastPkts; }
        
        public long getInDiscards() { return inDiscards; }
        public void setInDiscards(long inDiscards) { this.inDiscards = inDiscards; }
        
        public long getInErrors() { return inErrors; }
        public void setInErrors(long inErrors) { this.inErrors = inErrors; }
        
        public long getInUnknownProtos() { return inUnknownProtos; }
        public void setInUnknownProtos(long inUnknownProtos) { this.inUnknownProtos = inUnknownProtos; }
        
        public long getOutOctets() { return outOctets; }
        public void setOutOctets(long outOctets) { this.outOctets = outOctets; }
        
        public long getOutUcastPkts() { return outUcastPkts; }
        public void setOutUcastPkts(long outUcastPkts) { this.outUcastPkts = outUcastPkts; }
        
        public long getOutNUcastPkts() { return outNUcastPkts; }
        public void setOutNUcastPkts(long outNUcastPkts) { this.outNUcastPkts = outNUcastPkts; }
        
        public long getOutDiscards() { return outDiscards; }
        public void setOutDiscards(long outDiscards) { this.outDiscards = outDiscards; }
        
        public long getOutErrors() { return outErrors; }
        public void setOutErrors(long outErrors) { this.outErrors = outErrors; }
        
        public long getOutQLen() { return outQLen; }
        public void setOutQLen(long outQLen) { this.outQLen = outQLen; }
        
        public String getDescription() { return description; }
        public void setDescription(String description) { this.description = description; }
        
        @Override
        public String toString() {
            HexFormat hex = HexFormat.of().withDelimiter(":");
            StringBuilder sb = new StringBuilder();
            sb.append("Interface: ").append(name).append("\n");
            sb.append("  Index: ").append(index).append("\n");
            sb.append("  Type: ").append(getTypeName(type)).append(" (").append(type).append(")\n");
            sb.append("  MTU: ").append(mtu).append("\n");
            sb.append("  Speed: ").append(formatSpeed(speed)).append("\n");
            if (physAddr != null && physAddr.length > 0) {
                sb.append("  MAC: ").append(hex.formatHex(physAddr)).append("\n");
            }
            sb.append("  Admin Status: ").append(getAdminStatusName(adminStatus)).append("\n");
            sb.append("  Oper Status: ").append(getOperStatusName(operStatus)).append("\n");
            sb.append("  Description: ").append(description).append("\n");
            sb.append("  Statistics:\n");
            sb.append("    In:  ").append(formatBytes(inOctets)).append(", ")
              .append(inUcastPkts).append(" unicast, ")
              .append(inNUcastPkts).append(" non-unicast\n");
            sb.append("    Out: ").append(formatBytes(outOctets)).append(", ")
              .append(outUcastPkts).append(" unicast, ")
              .append(outNUcastPkts).append(" non-unicast\n");
            return sb.toString();
        }
        
        private String formatSpeed(long speed) {
            if (speed >= 1_000_000_000L) {
                return String.format("%.1f Gbps", speed / 1_000_000_000.0);
            } else if (speed >= 1_000_000L) {
                return String.format("%.1f Mbps", speed / 1_000_000.0);
            } else if (speed >= 1_000L) {
                return String.format("%.1f Kbps", speed / 1_000.0);
            } else {
                return speed + " bps";
            }
        }
        
        private String formatBytes(long bytes) {
            if (bytes >= 1_073_741_824L) { // 1 GiB
                return String.format("%.2f GiB", bytes / 1_073_741_824.0);
            } else if (bytes >= 1_048_576L) { // 1 MiB
                return String.format("%.2f MiB", bytes / 1_048_576.0);
            } else if (bytes >= 1_024L) { // 1 KiB
                return String.format("%.2f KiB", bytes / 1_024.0);
            } else {
                return bytes + " bytes";
            }
        }
    }
    
    /**
     * 获取接口信息
     * @param ifIndex 接口索引
     * @return 接口信息对象
     */
    public static MibIfRow getIfEntry(int ifIndex) {
        try (Arena arena = Arena.ofConfined()) {
            // 分配 MIB_IFROW 结构体
            MemorySegment ifRow = arena.allocate(MIB_IFROW_LAYOUT);
            
            // 清零初始化
            ifRow.fill((byte)0);
            
            // 设置接口索引 (dwIndex)
            ifRow.set(DWORD, 512, ifIndex);
            
            // 调用 GetIfEntry
            int result = (int) GET_IF_ENTRY.invokeExact(ifRow);
            
            if (result != NO_ERROR) {
                throw new WindowsAPIException("GetIfEntry failed", result);
            }
            
            // 解析结构体为 Java 对象
            return parseMibIfRow(ifRow);
            
        } catch (Throwable e) {
            throw new RuntimeException("Error getting interface entry", e);
        }
    }
    
    /**
     * 设置接口信息 (主要用来修改管理状态)
     * @param ifRow 接口信息对象
     * @return 操作结果 (0 = 成功)
     */
    public static int setIfEntry(MibIfRow ifRow) {
        try (Arena arena = Arena.ofConfined()) {
            // 分配 MIB_IFROW 结构体
            MemorySegment ifRowSegment = arena.allocate(MIB_IFROW_LAYOUT);
            
            // 清零初始化
            ifRowSegment.fill((byte)0);
            
            // 填充结构体
            fillMibIfRow(ifRowSegment, ifRow, arena);
            
            // 调用 SetIfEntry
            return (int) SET_IF_ENTRY.invokeExact(ifRowSegment);
            
        } catch (Throwable e) {
            throw new RuntimeException("Error setting interface entry", e);
        }
    }
    
    /**
     * 启用接口 (设置管理状态为 UP)
     * @param ifIndex 接口索引
     * @return 操作结果 (0 = 成功)
     */
    public static int enableInterface(int ifIndex) {
        MibIfRow ifRow = new MibIfRow();
        ifRow.setIndex(ifIndex);
        ifRow.setAdminStatus(MIB_IF_ADMIN_STATUS_UP);
        return setIfEntry(ifRow);
    }
    
    /**
     * 禁用接口 (设置管理状态为 DOWN)
     * @param ifIndex 接口索引
     * @return 操作结果 (0 = 成功)
     */
    public static int disableInterface(int ifIndex) {
        MibIfRow ifRow = new MibIfRow();
        ifRow.setIndex(ifIndex);
        ifRow.setAdminStatus(MIB_IF_ADMIN_STATUS_DOWN);
        return setIfEntry(ifRow);
    }
    
    /**
     * 解析 MIB_IFROW 结构体为 Java 对象
     */
    private static MibIfRow parseMibIfRow(MemorySegment ifRow) {
        MibIfRow result = new MibIfRow();
        
        // 1. 解析接口名称 (宽字符串)
        String name = readWideString(ifRow, 0, MAX_INTERFACE_NAME_LEN);
        result.setName(name);
        
        // 2. 读取基本字段
        result.setIndex(ifRow.get(DWORD, 512));
        result.setType(ifRow.get(DWORD, 516));
        result.setMtu(ifRow.get(DWORD, 520));
        
        // 3. 速度需要处理为无符号
        result.setSpeed(Integer.toUnsignedLong(ifRow.get(DWORD, 524)));
        
        // 4. 物理地址
        int physAddrLen = ifRow.get(DWORD, 528);
        if (physAddrLen > 0 && physAddrLen <= MAXLEN_PHYSADDR) {
            byte[] physAddr = new byte[physAddrLen];
            MemorySegment.copy(ifRow, 532, MemorySegment.ofArray(physAddr), 0, physAddrLen);
            result.setPhysAddr(physAddr);
        }
        
        // 5. 状态信息
        result.setAdminStatus(ifRow.get(DWORD, 564));
        result.setOperStatus(ifRow.get(DWORD, 568));
        result.setLastChange(Integer.toUnsignedLong(ifRow.get(DWORD, 572)));
        
        // 6. 输入统计 (需要处理为无符号)
        result.setInOctets(Integer.toUnsignedLong(ifRow.get(DWORD, 576)));
        result.setInUcastPkts(Integer.toUnsignedLong(ifRow.get(DWORD, 580)));
        result.setInNUcastPkts(Integer.toUnsignedLong(ifRow.get(DWORD, 584)));
        result.setInDiscards(Integer.toUnsignedLong(ifRow.get(DWORD, 588)));
        result.setInErrors(Integer.toUnsignedLong(ifRow.get(DWORD, 592)));
        result.setInUnknownProtos(Integer.toUnsignedLong(ifRow.get(DWORD, 596)));
        
        // 7. 输出统计
        result.setOutOctets(Integer.toUnsignedLong(ifRow.get(DWORD, 600)));
        result.setOutUcastPkts(Integer.toUnsignedLong(ifRow.get(DWORD, 604)));
        result.setOutNUcastPkts(Integer.toUnsignedLong(ifRow.get(DWORD, 608)));
        result.setOutDiscards(Integer.toUnsignedLong(ifRow.get(DWORD, 612)));
        result.setOutErrors(Integer.toUnsignedLong(ifRow.get(DWORD, 616)));
        result.setOutQLen(Integer.toUnsignedLong(ifRow.get(DWORD, 620)));
        
        // 8. 接口描述
        int descrLen = ifRow.get(DWORD, 624);
        if (descrLen > 0 && descrLen <= MAXLEN_IFDESCR) {
            byte[] descrBytes = new byte[descrLen];
            MemorySegment.copy(ifRow, 628, MemorySegment.ofArray(descrBytes), 0, descrLen);
            result.setDescription(new String(descrBytes, java.nio.charset.StandardCharsets.UTF_8));
        }
        
        return result;
    }
    
    /**
     * 填充 MIB_IFROW 结构体
     */
    private static void fillMibIfRow(MemorySegment ifRow, MibIfRow data, Arena arena) {
        // 1. 设置接口索引 (必须)
        ifRow.set(DWORD, 512, data.getIndex());
        
        // 2. 设置接口名称 (如果需要)
        if (data.getName() != null) {
            writeWideString(ifRow, 0, data.getName(), MAX_INTERFACE_NAME_LEN);
        }
        
        // 3. 设置接口类型 (如果需要)
        ifRow.set(DWORD, 516, data.getType());
        
        // 4. 设置 MTU (如果需要)
        ifRow.set(DWORD, 520, data.getMtu());
        
        // 5. 设置速度 (如果需要)
        ifRow.set(DWORD, 524, (int)Math.min(data.getSpeed(), 0xFFFFFFFFL));
        
        // 6. 设置物理地址 (如果需要)
        if (data.getPhysAddr() != null && data.getPhysAddr().length > 0) {
            int len = Math.min(data.getPhysAddr().length, MAXLEN_PHYSADDR);
            ifRow.set(DWORD, 528, len);
            MemorySegment.copy(MemorySegment.ofArray(data.getPhysAddr()), 0, ifRow, 532, len);
        }
        
        // 7. 设置管理状态 (主要用途)
        ifRow.set(DWORD, 564, data.getAdminStatus());
        
        // 8. 设置操作状态 (通常只读，但这里也设置)
        ifRow.set(DWORD, 568, data.getOperStatus());
        
        // 9. 设置接口描述 (如果需要)
        if (data.getDescription() != null && !data.getDescription().isEmpty()) {
            byte[] descrBytes = data.getDescription().getBytes(java.nio.charset.StandardCharsets.UTF_8);
            int len = Math.min(descrBytes.length, MAXLEN_IFDESCR);
            ifRow.set(DWORD, 624, len);
            MemorySegment.copy(MemorySegment.ofArray(descrBytes), 0, ifRow, 628, len);
        }
    }
    
    /**
     * 读取宽字符串
     */
    private static String readWideString(MemorySegment segment, long offset, int maxChars) {
        try {
            // 查找 null 终止符
            long length = 0;
            while (length < maxChars) {
                short ch = segment.get(WORD, offset + length * 2);
                if (ch == 0) {
                    break;
                }
                length++;
            }
            
            if (length == 0) {
                return "";
            }
            
            // 读取字符串数据
            byte[] bytes = new byte[(int)(length * 2)];
            MemorySegment.copy(segment, offset, MemorySegment.ofArray(bytes), 0, bytes.length);
            
            return new String(bytes, java.nio.charset.StandardCharsets.UTF_16LE);
        } catch (Exception e) {
            return "";
        }
    }
    
    /**
     * 写入宽字符串
     */
    private static void writeWideString(MemorySegment segment, long offset, String str, int maxChars) {
        if (str == null || str.isEmpty()) {
            return;
        }
        
        byte[] utf16Bytes = str.getBytes(java.nio.charset.StandardCharsets.UTF_16LE);
        int copyLen = Math.min(utf16Bytes.length, (maxChars - 1) * 2);
        
        if (copyLen > 0) {
            MemorySegment.copy(MemorySegment.ofArray(utf16Bytes), 0, segment, offset, copyLen);
        }
        
        // 添加 null 终止符
        segment.set(WORD, offset + copyLen, (short)0);
    }
    
    /**
     * 获取接口类型名称
     */
    private static String getTypeName(int type) {
        switch (type) {
            case IF_TYPE_ETHERNET_CSMACD: return "Ethernet";
            case IF_TYPE_ISO88025_TOKENRING: return "Token Ring";
            case IF_TYPE_PPP: return "PPP";
            case IF_TYPE_SOFTWARE_LOOPBACK: return "Loopback";
            case IF_TYPE_ATM: return "ATM";
            case IF_TYPE_IEEE80211: return "WiFi";
            case IF_TYPE_TUNNEL: return "Tunnel";
            case IF_TYPE_IEEE1394: return "FireWire";
            default: return "Unknown (" + type + ")";
        }
    }
    
    /**
     * 获取管理状态名称
     */
    private static String getAdminStatusName(int status) {
        switch (status) {
            case MIB_IF_ADMIN_STATUS_UP: return "UP";
            case MIB_IF_ADMIN_STATUS_DOWN: return "DOWN";
            case MIB_IF_ADMIN_STATUS_TESTING: return "TESTING";
            default: return "UNKNOWN (" + status + ")";
        }
    }
    
    /**
     * 获取操作状态名称
     */
    private static String getOperStatusName(int status) {
        switch (status) {
            case IF_OPER_STATUS_NON_OPERATIONAL: return "NON_OPERATIONAL";
            case IF_OPER_STATUS_UNREACHABLE: return "UNREACHABLE";
            case IF_OPER_STATUS_DISCONNECTED: return "DISCONNECTED";
            case IF_OPER_STATUS_CONNECTING: return "CONNECTING";
            case IF_OPER_STATUS_CONNECTED: return "CONNECTED";
            case IF_OPER_STATUS_OPERATIONAL: return "OPERATIONAL";
            default: return "UNKNOWN (" + status + ")";
        }
    }
    
   
    /**
     * 测试方法
     */
    public static void main(String[] args) {
        try {
            System.out.println("Windows Interface Manager");
            System.out.println("========================\n");
            
            // 测试获取所有接口（需要先获取接口表，这里简化测试）
            System.out.println("Testing GetIfEntry for interface index 1:");
            
            try {
                MibIfRow ifRow = getIfEntry(1);
                System.out.println(ifRow);
            } catch (Exception e) {
                System.out.println("Failed to get interface 1: " + e.getMessage());
            }
            
            // 测试获取环回接口（通常是索引 1）
            System.out.println("\nTesting with common interface indices:");
            
            // 常见的接口索引范围
            for (int i = 1; i <= 100; i++) {
                try {
                    MibIfRow ifRow = getIfEntry(i);
                    System.out.println("Interface " + i + ": " + ifRow.getName());
                    
                    // 如果是 Wintun 接口，可以尝试启用/禁用
                    if (ifRow.getName().contains("Wintun") || ifRow.getType() == IF_TYPE_TUNNEL) {
                        System.out.println("  Found Wintun/tunnel interface!");
                        
                        // 示例：启用接口
                        // int result = enableInterface(i);
                        // System.out.println("  Enable result: " + result);
                    }
                } catch (Exception e) {
                    // 接口不存在是正常的
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}