/**
 * @file    comm_internal.h
 * @brief   libcomm 内部共享定义
 * @details 结构体、全局变量、内部函数声明，供 comm_core/tcp/udp/uart.cpp 共享。
 *          不对外暴露。
 */
#ifndef _COMM_INTERNAL_H_
#define _COMM_INTERNAL_H_

#include "myComm.h"
#include "myLog.h"

#include <map>
#include <vector>
#include <mutex>
#include <thread>
#include <atomic>
#include <cstring>

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/epoll.h>

/* === 常量 === */
#define COMM_MAX_EVENTS    64
#define COMM_RECV_BUF_SIZE 4096
#define COMM_BACKLOG       128

/* === 内部 fd 信息 === */
typedef struct
{
    int fd;
    int is_listen;
    int instance_id;
} stru_comm_fd_info;

/* === 内部通讯实例 === */
typedef struct
{
    int id;
    int type;
    int debug;
    int state;
    int listen_fd;
    int local_fd;

    char local_ip[64];
    int  local_port;
    char remote_ip[64];
    int  remote_port;
    char uart_device[128];
    int  uart_baudrate;
    int  uart_data_bits;
    int  uart_stop_bits;
    char uart_parity;

    comm_recv_cb  recv_cb;
    comm_state_cb state_cb;

    std::vector<int> client_fds;
} stru_comm_instance;

/* === 全局状态（定义在 comm_core.cpp） === */
extern std::map<int, stru_comm_instance *> g_instances;
extern std::map<int, stru_comm_fd_info>    g_fd_map;
extern std::mutex        g_mutex;
extern std::atomic<bool> g_running;
extern int               g_epoll_fd;
extern int               g_next_id;
extern int               g_stop_event_fd;

/* === 内部函数声明 === */
int  comm_epoll_init(void);
int  set_nonblock(int fd);
void notify_state(stru_comm_instance *inst, int fd, int state);
int  epoll_add_fd(int fd, int instance_id, int is_listen);
int  epoll_del_fd(int fd);
void close_client_fd(stru_comm_instance *inst, int fd);
void handle_write(int fd);
void handle_error(stru_comm_instance *inst, int fd);

/* comm_tcp.cpp */
void handle_accept(stru_comm_instance *inst);
int  tcp_server_bind(stru_comm_instance *inst);
int  tcp_client_connect(stru_comm_instance *inst);

/* comm_udp.cpp */
void handle_udp_read(stru_comm_instance *inst, int fd);
int  udp_bind(stru_comm_instance *inst);
int  udp_sendto(stru_comm_instance *inst, int fd, const unsigned char *data, int len);

/* comm_uart.cpp */
void handle_uart_read(stru_comm_instance *inst, int fd);
int  uart_open(stru_comm_instance *inst);
void uart_close(stru_comm_instance *inst);

#endif
