/********************************************************************************
 * @file       net_interface.c
 * @brief      网络接口抽象层实现源文件
 * @details    实现net_interface.h定义的所有跨平台网络接口，封装ETH/ES底层驱动细节、线程安全的接收队列、端口管理、套接字创建/关闭等核心逻辑
 * @copyright  Copyright (C) 2026 芯祥联科技 All rights reserved.
 * @website    www.xxltech.cn
 * @email      hezuo@xxltech.cn
 * @author     芯祥联科技研发部
 * @version    V1.0.0
 * @date       2026-01-09
 * @note       1. 纯抽象层无任何Windows/Linux平台相关代码，完全解耦
 *             2. 内部队列使用互斥锁+信号量保证线程安全，无数据竞争
 *             3. 新增TCP独立接口，完美兼容MQTT TCP/UDP双协议
 *             4. 所有平台相关实现全部转发到对应平台适配层
 ********************************************************************************/
// 头文件包含顺序：基础类型 → 平台接口 → 自身接口 → 工具库
#include "type.h"
#include "platform.h"
#include "net_interface.h"
#include "agent_log.h"
#include "net_eth_win.h"
#include "net_eth_linux.h"
#include "net_eth_stm32.h"
#include <string.h>
#include <stdlib.h>


// --------------- 内部隐藏结构体 定义（完全隐藏，不暴露）
typedef struct InternalRecvNode {
    uint8_xxl data[MAX_MSG_LEN];
    uint32_xxl len;
    char_xxl src_ip[API_IP_LEN];
    uint16_xxl src_port;
    struct InternalRecvNode* next;
} InternalRecvNode;

typedef struct {
    InternalRecvNode* head;
    InternalRecvNode* tail;
    uint32_xxl count;
    uint32_xxl max_count;
    PlatformMutex* mutex;
    PlatformSem* sem;
} InternalRecvQueue;

#if 1
// 全局静态变量（抽象层内部使用）
static NetInterface g_registered_ifaces[NET_IFACE_MAX] = {0};
static NetInterfaceType g_current_type = NET_IFACE_ETH;
static NetInterface* g_current_iface = NULL;
static InternalRecvQueue g_recv_queue;
static NetRecvCallback g_recv_callback = NULL;
static void* g_callback_user_data = NULL;
static bool_xxl g_is_inited = false;

// UDP套接字创建（跨平台转发）
PlatformSocket net_udp_socket_create(void) {
#ifdef WIN32
    return net_udp_socket_create_win32();
#elif defined(LINUX)
    return net_udp_socket_create_linux();
#elif defined(STM32)
    return net_udp_socket_create_stm32();
#else
    return PLATFORM_SOCKET_INVALID;
#endif
}

// 创建信号量（跨平台转发）
static PlatformSem net_sem_create(int initial_count, int max_count) {
#ifdef WIN32
    return platform_sem_create_win32(initial_count, max_count);
#elif defined(LINUX)
    return platform_sem_create_linux(initial_count, max_count);
#elif defined(STM32)
    return platform_sem_create_stm32(initial_count, max_count);
#else
    return NULL;
#endif
}

// 发送信号量（跨平台转发）
static int32_xxl net_sem_post(PlatformSem sem) {
#ifdef WIN32
    return platform_sem_post_win32(sem);
#elif defined(LINUX)
    return platform_sem_post_linux(sem);
#elif defined(STM32)
    return platform_sem_post_stm32(sem);
#else
    return -1;
#endif
}

/**
 * 初始化接收队列（线程安全）
 */
static void net_interface_init_queue(uint32_xxl max_count)
{
    if (max_count == 0) max_count = 100;
    g_recv_queue.head = NULL;
    g_recv_queue.tail = NULL;
    g_recv_queue.count = 0;
    g_recv_queue.max_count = max_count;

    g_recv_queue.mutex = platform_mutex_create();
    if (!g_recv_queue.mutex) {  // <-- 修复
        agent_log_error("[queue] create mutex failed");
        return;
    }

    g_recv_queue.sem = net_sem_create(0, max_count);
    if (!g_recv_queue.sem) {   // <-- 原有
        agent_log_error("[queue] create sem failed");
        return;
    }
}

/**
 * 数据入队（内部线程安全函数）
 */
static NetErr net_queue_enqueue(const uint8_xxl* data, uint32_xxl len, const char* src_ip, uint16_xxl src_port) {
    if (!data || len == 0 || !src_ip || len > MAX_MSG_LEN) {
        agent_log_error("[%s] 入队失败：无效参数", __func__);
        return NET_ERR_PARAM;
    }

    platform_mutex_lock(g_recv_queue.mutex);
    if (g_recv_queue.count >= g_recv_queue.max_count) {
        platform_mutex_unlock(g_recv_queue.mutex);
        agent_log_warn("[%s] 接收队列已满，丢弃数据", __func__);
        return NET_ERR_RESOURCE;
    }

    InternalRecvNode* node = (InternalRecvNode*)malloc(sizeof(InternalRecvNode));
    if (!node) {
        platform_mutex_unlock(g_recv_queue.mutex);
        agent_log_error("[%s] 内存分配失败", __func__);
        return NET_ERR_MEM;
    }

    memcpy(node->data, data, len);
    node->len = len;
    platform_strcpy_s(node->src_ip, API_IP_LEN, src_ip);
    node->src_port = src_port;
    node->next = NULL;

    if (!g_recv_queue.head) {
        g_recv_queue.head = node;
        g_recv_queue.tail = node;
    } else {
        g_recv_queue.tail->next = node;
        g_recv_queue.tail = node;
    }
    g_recv_queue.count++;

    platform_mutex_unlock(g_recv_queue.mutex);
    net_sem_post(g_recv_queue.sem);

    agent_log_debug("[%s] 数据入队成功（长度：%u，来源：%s:%d）", __func__, len, src_ip, src_port);
    return NET_OK;
}

/**
 * 数据出队（对外接口，线程安全）
 */
NetErr net_interface_dequeue(NetRecvNode* node, uint32_xxl timeout) {
    if (!node || !g_is_inited) {
        agent_log_error("[%s] 出队失败：无效参数或未初始化", __func__);
        return NET_ERR_PARAM;
    }

    if (platform_sem_timedwait(g_recv_queue.sem, timeout) != 0) {
        return NET_ERR_TIMEOUT;
    }

    platform_mutex_lock(g_recv_queue.mutex);
    InternalRecvNode* temp = g_recv_queue.head;
    if (!temp) {
        platform_mutex_unlock(g_recv_queue.mutex);
        return NET_ERR_EMPTY;
    }

    memcpy(node->data, temp->data, temp->len);
    node->len = temp->len;
    platform_strcpy_s(node->src_ip, API_IP_LEN, temp->src_ip);
    node->src_port = temp->src_port;

    g_recv_queue.head = temp->next;
    if (!g_recv_queue.head) g_recv_queue.tail = NULL;
    g_recv_queue.count--;

    free(temp);
    platform_mutex_unlock(g_recv_queue.mutex);

    return NET_OK;
}

/**
 * 数据入队（对外接口）
 */
NetErr net_interface_enqueue(const NetRecvNode* node) {
    if (!node || !g_is_inited || node->len == 0 || node->len > MAX_MSG_LEN) {
        agent_log_error("[%s] 入队失败：无效参数", __func__);
        return NET_ERR_PARAM;
    }
    return net_queue_enqueue(node->data, node->len, node->src_ip, node->src_port);
}

/**
 * 检查端口是否冲突
 */
static bool_xxl check_port_conflict(uint16_xxl port) {
    for (int i = 0; i < NET_IFACE_MAX; i++) {
        if (g_registered_ifaces[i].local_port == port && g_registered_ifaces[i].net_send != NULL) {
            return true;
        }
    }
    return false;
}

/**
 * 注册网络接口
 */
NetErr net_interface_register(const NetInterface* iface) {
    if (!iface || iface->type >= NET_IFACE_MAX) {
        agent_log_error("[%s] 无效接口参数", __func__);
        return NET_ERR_PARAM;
    }
    if (!iface->net_send || !iface->net_recv) {
        agent_log_error("[%s] 接口未实现收发函数", __func__);
        return NET_ERR_IFACE;
    }

    if (iface->local_port != 0U && check_port_conflict(iface->local_port)) {
        agent_log_error("[%s] 端口冲突：%u", __func__, iface->local_port);
        return NET_ERR_PORT;
    }

    g_registered_ifaces[iface->type] = *iface;
    agent_log_info("[%s] 接口注册成功（类型：%d，端口：%u）", __func__, iface->type, iface->local_port);
    return NET_OK;
}

/**
 * 切换当前网络接口类型
 */
NetErr net_interface_set_current_type(NetInterfaceType type) {
    if (!g_is_inited || type >= NET_IFACE_MAX) {
        agent_log_error("[%s] 无效接口类型", __func__);
        return NET_ERR_PARAM;
    }

    if (g_registered_ifaces[type].net_send == NULL || g_registered_ifaces[type].net_recv == NULL) {
        agent_log_error("[%s] 接口未注册", __func__);
        return NET_ERR_IFACE;
    }

    if (g_current_iface && g_current_iface->destroy && type != g_current_type) {
        g_current_iface->destroy();
    }

    g_current_type = type;
    g_current_iface = &g_registered_ifaces[type];
    agent_log_info("[%s] 切换到接口类型：%d", __func__, type);
    return NET_OK;
}

// 销毁信号量（跨平台转发）
static void net_sem_destroy(PlatformSem sem) {
#ifdef WIN32
    platform_sem_destroy_win32(sem);
#elif defined(LINUX)
    platform_sem_destroy_linux(sem);
#elif defined(STM32)
    platform_sem_destroy_stm32(sem);
#endif
}

/**
 * 初始化网络模块（主入口）
 */
NetErr net_interface_init(void) {
    if (g_is_inited) {
        agent_log_warn("[%s] 网络模块已初始化", __func__);
        return NET_OK;
    }

    if (!platform_init()) {
        agent_log_error("[%s] 平台初始化失败", __func__);
        return NET_ERR_INIT;
    }

    net_interface_init_queue(100U);
    if (!g_recv_queue.mutex || !g_recv_queue.sem) {
        agent_log_error("[%s] 队列初始化失败", __func__);
        platform_deinit();
        return NET_ERR_INIT;
    }

    eth_socket_set_init();

    NetErr err;
#ifdef LINUX
    err = net_eth_linux_init();
#elif defined(STM32)
    err = net_eth_stm32_init();
#else
    err = net_eth_win_init();
#endif

    if (err != NET_OK) {
        agent_log_error("[%s] ETH接口初始化失败", __func__);
        net_interface_deinit();
        return err;
    }

//    err = net_es_init();
//    if (err != nil) {
//        agent_log_warn("[%s] ES接口初始化失败（非致命）", __func__);
//    }

    g_current_type = NET_IFACE_ETH;
    g_current_iface = &g_registered_ifaces[NET_IFACE_ETH];
    g_is_inited = true;
    agent_log_info("[%s] 网络模块初始化完成", __func__);
    return NET_OK;
}

/**
 * 反初始化网络模块
 */
void net_interface_deinit(void) {
    if (!g_is_inited) return;

    if (g_current_iface && g_current_iface->destroy) {
        g_current_iface->destroy();
    }

    // 清空队列
    if (g_recv_queue.mutex) {
        platform_mutex_lock(g_recv_queue.mutex);
        InternalRecvNode* node = g_recv_queue.head;
        while (node) {
            InternalRecvNode* temp = node;
            node = node->next;
            free(temp);
        }
        g_recv_queue.head = NULL;
        g_recv_queue.tail = NULL;
        g_recv_queue.count = 0U;
        platform_mutex_unlock(g_recv_queue.mutex);

        // ================= 重要 =================
        // 锁 不销毁！不销毁！不销毁！
        // ========================================
    }

    if (g_recv_queue.sem) {
        net_sem_destroy(g_recv_queue.sem);
        g_recv_queue.sem = NULL;
    }

    memset(g_registered_ifaces, 0, sizeof(g_registered_ifaces));
    g_current_iface = NULL;
    g_recv_callback = NULL;
    g_callback_user_data = NULL;
    g_is_inited = false;

    platform_deinit();
    agent_log_info("[%s] 网络模块反初始化完成", __func__);
}

/**
 * 创建UDP套接字
 */
PlatformSocket net_interface_create_udp_socket(void) {
    if (!g_is_inited || g_current_type != NET_IFACE_ETH) {
        agent_log_error("[%s] 创建失败：未初始化或非ETH模式", __func__);
        return PLATFORM_SOCKET_INVALID;
    }

    PlatformSocket sock = net_udp_socket_create();
    if (sock == PLATFORM_SOCKET_INVALID) {
        agent_log_error("[%s] 创建UDP套接字失败", __func__);
        return PLATFORM_SOCKET_INVALID;
    }

    eth_socket_set_add((int32_xxl)sock);
    agent_log_debug("[%s] 创建UDP套接字成功：%d", __func__, sock);
    return sock;
}

/**
 * 创建TCP套接字
 */
PlatformSocket net_interface_create_tcp_socket(void) {
    if (!g_is_inited || g_current_type != NET_IFACE_ETH) {
        agent_log_error("[%s] 创建失败：未初始化或非ETH模式", __func__);
        return PLATFORM_SOCKET_INVALID;
    }

    PlatformSocket sock;
#ifdef WIN32
    sock = net_tcp_socket_create_win32();
#elif defined(LINUX)
    sock = net_tcp_socket_create_linux();
#elif defined(STM32)
    sock = net_tcp_socket_create_stm32();
#else
    sock = PLATFORM_SOCKET_INVALID;
#endif
    if (sock == PLATFORM_SOCKET_INVALID) {
        agent_log_error("[%s] 创建TCP套接字失败", __func__);
        return PLATFORM_SOCKET_INVALID;
    }

    eth_socket_set_add((int32_xxl)sock);
    eth_set_mqtt_tcp_socket(sock);
    agent_log_debug("[%s] 创建TCP套接字成功：%d", __func__, sock);
    return sock;
}

/**
 * 检查端口是否被占用
 */
static bool_xxl platform_check_port_in_use(uint16_xxl port) {
#ifdef WIN32
    return platform_check_port_in_use_win32(port);
#elif defined(LINUX)
    return platform_check_port_in_use_linux(port);
#elif defined(STM32)
    return platform_check_port_in_use_stm32(port);
#else
    return false;
#endif
}

/**
 * 绑定端口
 */
NetErr net_interface_bind(int32_xxl sock_fd, uint16_xxl port) {
    if (!g_is_inited || g_current_type != NET_IFACE_ETH || sock_fd == PLATFORM_SOCKET_INVALID) {
        agent_log_error("[%s] 绑定失败：无效参数", __func__);
        return NET_ERR_PARAM;
    }

    if (port != 0U && platform_check_port_in_use(port)) {
        agent_log_error("[%s] 端口被占用：%u", __func__, port);
        return NET_ERR_PORT;
    }

    bool_xxl bind_ok = false;
#ifdef LINUX
    bind_ok = net_udp_bind_linux((PlatformSocket)sock_fd, port);
#elif defined(STM32)
    bind_ok = net_udp_bind_stm32((PlatformSocket)sock_fd, port);
#else
    bind_ok = net_udp_bind((PlatformSocket)sock_fd, port);
#endif
    if (!bind_ok) {
    // ======================================================
        agent_log_error("[%s] 绑定失败：%d -> %u", __func__, sock_fd, port);
        return NET_ERR_NETWORK;
    }

    agent_log_info("[%s] 绑定成功：%d -> %u", __func__, sock_fd, port);
    return NET_OK;
}

/**
 * TCP连接目标地址
 */
NetErr net_interface_tcp_connect(int32_xxl sock_fd, const char* ip, uint16_xxl port) {
    if (!g_is_inited || g_current_type != NET_IFACE_ETH || sock_fd == PLATFORM_SOCKET_INVALID || !ip) {
        agent_log_error("[%s] 连接失败：无效参数", __func__);
        return NET_ERR_PARAM;
    }

#ifdef WIN32
    if (net_tcp_connect_win32((PlatformSocket)sock_fd, ip, port)) {
        agent_log_info("[%s] TCP连接成功：%s:%d", __func__, ip, port);
        return NET_OK;
    }
#elif defined(LINUX)
    if (net_tcp_connect_linux((PlatformSocket)sock_fd, ip, port)) {
        agent_log_info("[%s] TCP连接成功：%s:%d", __func__, ip, port);
        return NET_OK;
    }
#elif defined(STM32)
    if (net_tcp_connect_stm32((PlatformSocket)sock_fd, ip, port)) {
        agent_log_info("[%s] TCP连接成功：%s:%d", __func__, ip, port);
        return NET_OK;
    }
#endif
    agent_log_error("[%s] TCP连接失败：%s:%d", __func__, ip, port);
    return NET_ERR_NETWORK;
}

/**
 * TCP数据接收
 */
NetErr net_interface_tcp_recv(int32_xxl sock_fd, uint8_xxl* buf, uint32_xxl buf_len, uint32_xxl* actual_len, uint32_xxl timeout_ms)
{
    if(sock_fd == PLATFORM_SOCKET_INVALID || buf == NULL || actual_len == NULL || buf_len == 0U)
    {
        agent_log_error("[%s] 参数无效", __func__);
        *actual_len = 0U;
        return NET_ERR_PARAM;
    }

    *actual_len = 0U;
    int32_xxl recv_len = 0;

#ifdef WIN32
    recv_len = net_tcp_recv_win32((PlatformSocket)sock_fd, buf, buf_len, timeout_ms);
#elif defined(LINUX)
    recv_len = net_tcp_recv_linux((PlatformSocket)sock_fd, buf, buf_len, timeout_ms);
#elif defined(STM32)
    recv_len = net_tcp_recv_stm32((PlatformSocket)sock_fd, buf, buf_len, timeout_ms);
#endif

    if(recv_len > 0)
    {
        *actual_len = (uint32_xxl)recv_len;
        return NET_OK;
    }
    else if(recv_len == 0)
    {
        return NET_ERR_TIMEOUT;
    }
    return NET_ERR_NETWORK;
}

/**
 * 发送数据（UDP/TCP通用）
 */
NetErr net_interface_send_to(int32_xxl sock_fd, const char* ip, uint16_xxl port, const uint8_xxl* data, uint32_xxl len) {
    if (!g_is_inited || !ip || !data || len == 0U || len > MAX_MSG_LEN) {
        agent_log_error("[%s] 发送失败：无效参数", __func__);
        return NET_ERR_PARAM;
    }

    int32_xxl ret = -1;
#ifdef WIN32
    ret = net_tcp_send_win32((PlatformSocket)sock_fd, data, len);
#elif defined(LINUX)
    ret = net_tcp_send_linux((PlatformSocket)sock_fd, data, len);
#elif defined(STM32)
    ret = net_tcp_send_stm32((PlatformSocket)sock_fd, data, len);
#endif
    if (ret > 0) {
        agent_log_debug("[%s] 发送成功：%u字节 -> %s:%d", __func__, len, ip, port);
        return NET_OK;
    }

    agent_log_error("[%s] 发送失败", __func__);
    return NET_ERR_NETWORK;
}

/**
 * 关闭套接字
 */
void net_interface_close(int32_xxl sock_fd) {
    if (!g_is_inited || g_current_type != NET_IFACE_ETH || sock_fd == PLATFORM_SOCKET_INVALID) {
        agent_log_debug("[%s] 关闭失败：无效参数", __func__);
        return;
    }

#ifdef LINUX
    net_socket_close_linux((PlatformSocket)sock_fd);
#elif defined(STM32)
    net_socket_close_stm32((PlatformSocket)sock_fd);
#else
    net_socket_close((PlatformSocket)sock_fd);
#endif
    // ======================================================

    eth_socket_set_remove(sock_fd);
    agent_log_info("[%s] 套接字已关闭：%d", __func__, sock_fd);
}

/**
 * 中断数据处理
 */
NetErr net_interface_on_interrupt(uint8_xxl* buf, uint32_xxl buf_len) {
    if (!g_is_inited || !buf || buf_len == 0U || buf_len > MAX_MSG_LEN) {
        agent_log_error("[%s] 处理失败：无效参数", __func__);
        return NET_ERR_PARAM;
    }

    char_xxl src_ip[API_IP_LEN] = {0};
    uint16_xxl src_port = 0U;
    uint32_xxl recv_len = 0U;
    NetErr err = g_current_iface->net_recv(buf, buf_len, &recv_len, src_ip, &src_port);
    if (err != NET_OK) {
        agent_log_error("[%s] 数据接收失败", __func__);
        return err;
    }

    NetRecvNode node;
    memcpy(node.data, buf, recv_len);
    node.len = recv_len;
    platform_strcpy_s(node.src_ip, API_IP_LEN, src_ip);
    node.src_port = src_port;
    return net_interface_enqueue(&node);
}
// 新增：程序最终退出时调用，销毁全局锁
void net_interface_final_destroy(void)
{
    if (g_recv_queue.mutex != NULL) {
        platform_mutex_destroy(g_recv_queue.mutex);
        g_recv_queue.mutex = NULL;
        agent_log_info("[net_interface] 全局队列锁已最终销毁");
    }
}

#endif
