#include "app.hpp"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <map>

namespace bntvs {

// ============================================================================
// 内部辅助变量
// ============================================================================
namespace {
    bool g_storage_running    = false;
    bool g_monitoring_running = false;
    std::map<BusType, NetworkStatus> g_network_status;
    std::vector<RouteEntry> g_routing_table;
    uint64_t g_next_record_id = 1;
}

// ============================================================================
// 基础通用通信单元 (SU-COM) — 实现
// ============================================================================

/**
 * @requirement(name="基础通用通讯功能", id="SRS-F-01-001")
 * 初始化以太网通信接口：配置 IP 地址和端口，建立 TCP/UDP 套接字。
 */
bool initEthernetComm(const std::string& ip_address, uint16_t port) {
    // 模拟以太网接口初始化
    std::cout << "[SU-COM] 初始化以太网通信: IP="
              << ip_address << ", Port=" << port << std::endl;
    return (!ip_address.empty() && port > 0);
}

/**
 * @requirement(name="基础通用通讯功能", id="SRS-F-01-001")
 * 初始化 RS422 通信接口：配置串口名称和波特率。
 */
bool initRS422Comm(const std::string& port_name, uint32_t baud_rate) {
    std::cout << "[SU-COM] 初始化 RS422 通信: Port="
              << port_name << ", BaudRate=" << baud_rate << std::endl;
    return (!port_name.empty() && baud_rate >= 300 && baud_rate <= 115200);
}

/**
 * @requirement(name="基础通用通讯功能", id="SRS-F-01-001")
 * 初始化 CAN 通信接口：配置接口名称和波特率（5K~1Mbps）。
 */
bool initCANComm(const std::string& interface_name, uint32_t baud_rate) {
    if (baud_rate < 5000 || baud_rate > 1000000) {
        std::cerr << "[SU-COM] 错误: CAN 波特率 " << baud_rate
                  << " 超出范围 (5K~1Mbps)" << std::endl;
        return false;
    }
    std::cout << "[SU-COM] 初始化 CAN 通信: Interface="
              << interface_name << ", BaudRate=" << baud_rate << std::endl;
    return !interface_name.empty();
}

/**
 * @requirement(name="基础通用通讯功能", id="SRS-F-01-001")
 * 初始化模拟量采集接口：支持 0~10V 输入范围，12位精度。
 */
bool initAnalogComm(uint8_t channel) {
    std::cout << "[SU-COM] 初始化模拟量采集: Channel="
              << static_cast<int>(channel) << std::endl;
    return true;
}

/**
 * @requirement(name="基础通用通讯功能", id="SRS-F-01-001")
 * 初始化离散量 I/O 接口：支持 48 路 TTL 电平。
 */
bool initDigitalComm(uint8_t io_pin) {
    if (io_pin >= 48) {
        std::cerr << "[SU-COM] 错误: 离散量引脚 " << static_cast<int>(io_pin)
                  << " 超出范围 (0~47)" << std::endl;
        return false;
    }
    std::cout << "[SU-COM] 初始化离散量 I/O: Pin="
              << static_cast<int>(io_pin) << std::endl;
    return true;
}

// ============================================================================
// 协议兼容单元 (SU-PROT) — 实现
// ============================================================================

/**
 * @requirement(name="协议兼容功能", id="SRS-F-01-002")
 * @requirement(name="支持协议要求", id="SRS-F-09-007")
 * 自动识别 CAN 帧协议类型：通过帧头标志位区分 CAN2.0 和 CAN FD。
 */
CANProtocolType detectCANProtocol(const std::vector<uint8_t>& frame_data) {
    if (frame_data.size() > 8) {
        // CAN FD 帧有效负载可超过 8 字节
        return CANProtocolType::CANFD;
    }
    // CAN 2.0 帧有效负载最多 8 字节
    return CANProtocolType::CAN2_0;
}

/**
 * @requirement(name="协议兼容功能", id="SRS-F-01-002")
 * 在 CAN2.0 和 CAN FD 之间执行兼容转换，确保数据转发一致性。
 */
std::vector<uint8_t> convertCANFrame(CANProtocolType source_type,
                                     CANProtocolType target_type,
                                     const std::vector<uint8_t>& frame_data) {
    if (source_type == target_type) {
        return frame_data;
    }
    std::vector<uint8_t> result;
    if (source_type == CANProtocolType::CANFD &&
        target_type == CANProtocolType::CAN2_0) {
        // CAN FD → CAN 2.0: 截断到 8 字节
        size_t len = std::min<size_t>(frame_data.size(), 8);
        result.assign(frame_data.begin(), frame_data.begin() + len);
    } else {
        // CAN 2.0 → CAN FD: 补齐到 8 字节（CAN FD 最小负载）
        result = frame_data;
        result.resize(8, 0x00);
    }
    return result;
}

// ============================================================================
// 数据存储单元 (SU-STOR) — 实现
// ============================================================================

/**
 * @requirement(name="数据存储功能", id="SRS-F-02-001")
 * 持久化存储一条总线数据记录。实际部署中写入数据库或文件系统。
 */
bool storeBusData(const BusDataRecord& record) {
    if (!g_storage_running) {
        std::cerr << "[SU-STOR] 错误: 存储服务未启动" << std::endl;
        return false;
    }
    auto tt = std::chrono::system_clock::to_time_t(record.timestamp);
    std::tm tm = *std::gmtime(&tt);
    std::ostringstream oss;
    oss << std::put_time(&tm, "%Y%m%d_%H%M%S");
    std::cout << "[SU-STOR] 存储数据: record_id=" << record.record_id
              << ", bus_type=" << record.bus_type
              << ", frame_id=0x" << std::hex << record.frame_id
              << ", timestamp=" << oss.str() << std::dec << std::endl;
    return true;
}

/**
 * @requirement(name="数据存储功能", id="SRS-F-02-001")
 * 启动存储服务，包括磁盘容量监控和自动分段存储。
 */
bool startStorageService() {
    if (g_storage_running) {
        std::cout << "[SU-STOR] 存储服务已在运行" << std::endl;
        return true;
    }
    g_storage_running = true;
    std::cout << "[SU-STOR] 存储服务已启动 (磁盘容量监控已启用)" << std::endl;
    return true;
}

bool stopStorageService() {
    if (!g_storage_running) {
        return false;
    }
    g_storage_running = false;
    std::cout << "[SU-STOR] 存储服务已停止" << std::endl;
    return true;
}

// ============================================================================
// 数据管理与回放单元 (SU-REPLAY) — 实现
// ============================================================================

/**
 * @requirement(name="数据管理与数据回放功能", id="SRS-F-02-002")
 * 检索历史数据：按总线类型和时间范围条件筛选。
 */
std::vector<BusDataRecord> queryBusData(const std::string& bus_type,
                                        const std::string& start_time,
                                        const std::string& end_time) {
    std::vector<BusDataRecord> results;
    std::cout << "[SU-REPLAY] 查询数据: bus_type="
              << (bus_type.empty() ? "ALL" : bus_type)
              << ", start=" << start_time
              << ", end=" << end_time << std::endl;
    // 模拟返回空结果集（实际实现将查询数据库）
    return results;
}

/**
 * @requirement(name="数据管理与数据回放功能", id="SRS-F-02-002")
 * @requirement(name="数据统计回放功能", id="SRS-F-09-005")
 * 按原始时序和可调速度回放数据，并在回放过程中统计帧数。
 */
uint64_t replayBusData(const std::vector<BusDataRecord>& records,
                       double speed_factor,
                       std::function<void(const BusDataRecord&)> callback) {
    uint64_t replayed_count = 0;
    std::cout << "[SU-REPLAY] 开始回放: records=" << records.size()
              << ", speed=" << speed_factor << "x" << std::endl;
    for (const auto& record : records) {
        if (callback) {
            callback(record);
        }
        ++replayed_count;
    }
    std::cout << "[SU-REPLAY] 回放完成: 共 " << replayed_count << " 帧" << std::endl;
    return replayed_count;
}

/**
 * @requirement(name="数据管理与数据回放功能", id="SRS-F-02-002")
 * 删除指定历史数据记录。
 */
bool deleteBusData(int64_t record_id) {
    std::cout << "[SU-REPLAY] 删除记录: record_id=" << record_id << std::endl;
    return (record_id > 0);
}

// ============================================================================
// 信号转换单元 (SU-CONV) — 实现
// ============================================================================

/**
 * @requirement(name="信号转换功能", id="SRS-F-06-001")
 * @requirement(name="模拟量离散量转总线信号功能", id="SRS-F-06-005")
 * 将模拟量电压 (0~10V) 转换为 CAN 总线数据帧。
 */
BusDataRecord convertAnalogToBus(double voltage, uint32_t can_id) {
    BusDataRecord record;
    record.record_id   = g_next_record_id++;
    record.bus_type    = "CAN";
    record.timestamp   = std::chrono::system_clock::now();
    record.frame_id    = can_id;
    record.protocol_type = "CAN2.0";
    record.node_id     = "ANALOG_CONVERTER";

    // 将模拟量电压值编码为 2 字节数据
    uint16_t encoded = static_cast<uint16_t>(voltage / 10.0 * 4095.0); // 12-bit
    record.data_content = {
        static_cast<uint8_t>((encoded >> 8) & 0xFF),
        static_cast<uint8_t>(encoded & 0xFF)
    };
    record.data_length = static_cast<uint32_t>(record.data_content.size());

    std::cout << "[SU-CONV] 模拟量→总线: voltage=" << voltage
              << "V, can_id=0x" << std::hex << can_id << std::dec << std::endl;
    return record;
}

/**
 * @requirement(name="信号转换功能", id="SRS-F-06-001")
 * @requirement(name="模拟量离散量转总线信号功能", id="SRS-F-06-005")
 * 将离散量电平 (0V 或 5V) 转换为 CAN 总线数据帧。
 */
BusDataRecord convertDigitalToBus(uint8_t level, uint32_t can_id) {
    BusDataRecord record;
    record.record_id   = g_next_record_id++;
    record.bus_type    = "CAN";
    record.timestamp   = std::chrono::system_clock::now();
    record.frame_id    = can_id;
    record.protocol_type = "CAN2.0";
    record.node_id     = "DIGITAL_CONVERTER";

    // 将离散量电平值编码为 1 字节
    record.data_content = { (level > 0) ? static_cast<uint8_t>(1) : static_cast<uint8_t>(0) };
    record.data_length = 1;

    std::cout << "[SU-CONV] 离散量→总线: level=" << (level > 0 ? "5V" : "0V")
              << ", can_id=0x" << std::hex << can_id << std::dec << std::endl;
    return record;
}

// ============================================================================
// 总线路由单元 (SU-ROUTE) — 实现
// ============================================================================

/**
 * @requirement(name="数据转发交换功能", id="SRS-F-07-001")
 * @requirement(name="路由寻址功能", id="SRS-F-07-002")
 * 执行路由转发：查找路由表，确定下一跳并转发数据帧。
 */
bool routeDataFrame(const BusDataRecord& frame) {
    if (g_routing_table.empty()) {
        std::cerr << "[SU-ROUTE] 路由表为空，无法转发" << std::endl;
        return false;
    }
    // 简单路由：选择优先级最高的匹配路由
    for (const auto& route : g_routing_table) {
        std::cout << "[SU-ROUTE] 转发帧: frame_id=0x" << std::hex
                  << frame.frame_id << " → " << route.next_hop
                  << " via " << route.out_interface << std::dec << std::endl;
        return true;
    }
    return false;
}

/**
 * @requirement(name="以太网-CAN协议转换适配功能", id="SRS-F-07-003")
 * 将以太网数据帧转换为 CAN 总线帧。
 */
BusDataRecord convertEthernetToCAN(const BusDataRecord& eth_frame) {
    BusDataRecord can_frame = eth_frame;
    can_frame.bus_type = "CAN";
    can_frame.protocol_type = "CAN2.0";
    // 截断数据以适应 CAN 帧最大负载
    if (can_frame.data_content.size() > 8) {
        can_frame.data_content.resize(8);
        can_frame.data_length = 8;
    }
    std::cout << "[SU-ROUTE] 以太网→CAN 转换: frame_id=0x"
              << std::hex << can_frame.frame_id << std::dec << std::endl;
    return can_frame;
}

/**
 * @requirement(name="以太网-CAN协议转换适配功能", id="SRS-F-07-003")
 * 将 CAN 总线帧转换为以太网数据帧。
 */
BusDataRecord convertCANToEthernet(const BusDataRecord& can_frame) {
    BusDataRecord eth_frame = can_frame;
    eth_frame.bus_type = "ETHERNET";
    eth_frame.protocol_type = "TCP/IP";
    std::cout << "[SU-ROUTE] CAN→以太网 转换: frame_id=0x"
              << std::hex << eth_frame.frame_id << std::dec << std::endl;
    return eth_frame;
}

/**
 * @requirement(name="路由功能要求", id="SRS-F-07-007")
 * 添加静态路由条目。
 */
bool addStaticRoute(const RouteEntry& entry) {
    RouteEntry e = entry;
    e.route_type = "Static";
    g_routing_table.push_back(e);
    std::cout << "[SU-ROUTE] 添加静态路由: dest=" << e.dest_network
              << ", next_hop=" << e.next_hop << std::endl;
    return true;
}

/**
 * @requirement(name="路由功能要求", id="SRS-F-07-007")
 * 添加动态路由条目（模拟 OSPF/RIP 协议行为）。
 */
bool addDynamicRoute(const RouteEntry& entry) {
    RouteEntry e = entry;
    e.route_type = "Dynamic";
    g_routing_table.push_back(e);
    std::cout << "[SU-ROUTE] 添加动态路由: dest=" << e.dest_network
              << ", next_hop=" << e.next_hop << std::endl;
    return true;
}

// ============================================================================
// 总线分析单元 (SU-ANALY) — 实现
// ============================================================================

/**
 * @requirement(name="总线实时监听功能", id="SRS-F-09-001")
 * 启动实时监听：通过回调函数逐帧上报接收到的总线数据。
 */
bool startBusMonitoring(BusType bus_type,
                        std::function<void(const BusDataRecord&)> callback) {
    if (g_monitoring_running) {
        std::cout << "[SU-ANALY] 监听已在运行" << std::endl;
        return true;
    }
    g_monitoring_running = true;
    std::cout << "[SU-ANALY] 启动实时监听: bus_type="
              << static_cast<int>(bus_type) << std::endl;

    // 模拟接收一帧数据
    if (callback) {
        BusDataRecord sample;
        sample.record_id = g_next_record_id++;
        sample.timestamp = std::chrono::system_clock::now();
        sample.frame_id  = 0x123;
        sample.data_content = {0x01, 0x02, 0x03, 0x04};
        sample.data_length = 4;
        callback(sample);
    }
    return true;
}

bool stopBusMonitoring() {
    if (!g_monitoring_running) {
        return false;
    }
    g_monitoring_running = false;
    std::cout << "[SU-ANALY] 停止实时监听" << std::endl;
    return true;
}

/**
 * @requirement(name="协议解析解码功能", id="SRS-F-09-002")
 * 解析原始 CAN 帧数据：提取帧 ID、数据长度、数据内容等字段。
 */
BusDataRecord parseCANFrame(const std::vector<uint8_t>& raw_data) {
    BusDataRecord record;
    record.record_id   = g_next_record_id++;
    record.bus_type    = "CAN";
    record.timestamp   = std::chrono::system_clock::now();
    record.node_id     = "ANALYZER";

    if (raw_data.size() >= 4) {
        // 前 4 字节作为帧 ID
        record.frame_id = (static_cast<uint32_t>(raw_data[0]) << 24) |
                          (static_cast<uint32_t>(raw_data[1]) << 16) |
                          (static_cast<uint32_t>(raw_data[2]) << 8)  |
                          static_cast<uint32_t>(raw_data[3]);
    }

    // 解析协议类型
    if (raw_data.size() > 8) {
        record.protocol_type = "CANFD";
    } else {
        record.protocol_type = "CAN2.0";
    }

    // 数据内容
    if (raw_data.size() > 4) {
        record.data_content.assign(raw_data.begin() + 4, raw_data.end());
        record.data_length = static_cast<uint32_t>(record.data_content.size());
    }

    return record;
}

/**
 * @requirement(name="故障诊断分析功能", id="SRS-F-09-003")
 * @requirement(name="错误帧识别要求", id="SRS-F-09-011")
 * 诊断数据帧中的故障：检测位错误、CRC 错误等。
 */
std::string diagnoseBusFault(const BusDataRecord& frame) {
    // 模拟故障诊断逻辑
    if (frame.data_content.empty()) {
        return "空数据帧 (Empty frame)";
    }
    // 检查 CRC 错误（模拟：若数据第一个字节为 0xFF 则视为 CRC 错误）
    if (!frame.data_content.empty() && frame.data_content[0] == 0xFF) {
        return "CRC 错误 (CRC Error detected)";
    }
    // 检查位错误（模拟：若数据包含 0xAA 则指示位错误）
    for (auto b : frame.data_content) {
        if (b == 0xAA) {
            return "位错误 (Bit Error detected)";
        }
    }
    return "";
}

/**
 * @requirement(name="错误帧识别要求", id="SRS-F-09-011")
 * 检查帧数据中是否存在位错误或 CRC 错误。
 */
bool checkErrorFrame(const std::vector<uint8_t>& frame_data) {
    if (frame_data.empty()) return true;
    // 模拟检测：0xFF 表示 CRC 错误，0xAA 表示位错误
    for (auto b : frame_data) {
        if (b == 0xFF || b == 0xAA) {
            return true;
        }
    }
    return false;
}

/**
 * @requirement(name="波形与时序分析功能", id="SRS-F-09-004")
 * 执行波形与时序分析：计算频率、幅度、占空比、毛刺等参数。
 */
WaveformAnalysisResult analyzeWaveform(const std::vector<double>& samples,
                                       double sample_rate_hz) {
    WaveformAnalysisResult result;
    if (samples.size() < 2) {
        result.analysis_summary = "采样数据不足，无法分析";
        return result;
    }

    double max_val = *std::max_element(samples.begin(), samples.end());
    double min_val = *std::min_element(samples.begin(), samples.end());
    result.signal_amplitude = (max_val - min_val) / 2.0;

    // 计算频率：统计过零点
    uint64_t zero_crossings = 0;
    for (size_t i = 1; i < samples.size(); ++i) {
        if ((samples[i-1] < 0 && samples[i] >= 0) ||
            (samples[i-1] >= 0 && samples[i] < 0)) {
            ++zero_crossings;
        }
    }
    double period_samples = (zero_crossings > 1)
        ? (2.0 * samples.size() / static_cast<double>(zero_crossings))
        : 0.0;
    result.signal_frequency_hz = (period_samples > 0)
        ? sample_rate_hz / period_samples : 0.0;

    // 计算占空比
    uint64_t high_count = 0;
    double midpoint = (max_val + min_val) / 2.0;
    for (auto s : samples) {
        if (s > midpoint) ++high_count;
    }
    result.duty_cycle = samples.empty() ? 0.0 :
        (100.0 * static_cast<double>(high_count) / static_cast<double>(samples.size()));

    // 检测毛刺（突变）
    for (size_t i = 2; i < samples.size(); ++i) {
        double diff1 = std::abs(samples[i] - samples[i-1]);
        double diff2 = std::abs(samples[i-1] - samples[i-2]);
        if (diff1 > result.signal_amplitude * 1.5 && diff2 > result.signal_amplitude * 1.5) {
            ++result.glitch_count;
        }
    }

    std::ostringstream oss;
    oss << "频率=" << result.signal_frequency_hz << "Hz, "
        << "幅度=" << result.signal_amplitude << ", "
        << "占空比=" << result.duty_cycle << "%, "
        << "毛刺数=" << result.glitch_count;
    result.analysis_summary = oss.str();

    return result;
}

/**
 * @requirement(name="网络状态监视功能", id="SRS-F-09-006")
 * 获取网络状态信息（刷新率 ≥ 1Hz）。
 */
NetworkStatus getNetworkStatus(BusType bus_type) {
    NetworkStatus status;
    // 模拟网络状态数据
    status.bus_load     = 45.6;
    status.total_frames = 102400;
    status.error_frames = 12;
    status.capture_rate = 1000.0;

    auto now = std::chrono::system_clock::now();
    auto tt = std::chrono::system_clock::to_time_t(now);
    std::tm tm = *std::gmtime(&tt);
    std::ostringstream oss;
    oss << std::put_time(&tm, "%Y-%m-%d %H:%M:%S");
    status.last_update_time = oss.str();

    // 更新缓存
    g_network_status[bus_type] = status;

    std::cout << "[SU-ANALY] 网络状态: bus_type="
              << static_cast<int>(bus_type)
              << ", load=" << status.bus_load << "%"
              << ", errors=" << status.error_frames << std::endl;
    return status;
}

// ============================================================================
// 故障注入单元 (SU-FAULT) — 实现
// ============================================================================

/**
 * @requirement(name="总线短路/断路注入", id="SRS-F-12-001")
 * 向目标总线注入短路故障。
 */
bool injectShortCircuit(BusType bus_type, uint32_t duration_ms) {
    std::cout << "[SU-FAULT] 注入短路故障: bus_type="
              << static_cast<int>(bus_type)
              << ", duration=" << duration_ms << "ms" << std::endl;
    return true;
}

/**
 * @requirement(name="总线短路/断路注入", id="SRS-F-12-001")
 * 向目标总线注入断路故障。
 */
bool injectOpenCircuit(BusType bus_type, uint32_t duration_ms) {
    std::cout << "[SU-FAULT] 注入断路故障: bus_type="
              << static_cast<int>(bus_type)
              << ", duration=" << duration_ms << "ms" << std::endl;
    return true;
}

/**
 * @requirement(name="电磁干扰注入", id="SRS-F-12-002")
 * 向目标总线注入电磁干扰。
 */
bool injectEMI(BusType bus_type, double intensity, uint32_t duration_ms) {
    if (intensity < 0.0 || intensity > 1.0) {
        std::cerr << "[SU-FAULT] 错误: 干扰强度 " << intensity
                  << " 超出范围 (0.0~1.0)" << std::endl;
        return false;
    }
    std::cout << "[SU-FAULT] 注入电磁干扰: bus_type="
              << static_cast<int>(bus_type)
              << ", intensity=" << intensity
              << ", duration=" << duration_ms << "ms" << std::endl;
    return true;
}

/**
 * @requirement(name="错误帧注入", id="SRS-F-12-003")
 * 向目标总线注入指定类型的错误帧。
 */
bool injectErrorFrame(BusType bus_type, const std::string& error_type) {
    std::cout << "[SU-FAULT] 注入错误帧: bus_type="
              << static_cast<int>(bus_type)
              << ", error_type=" << error_type << std::endl;
    return true;
}

/**
 * @requirement(name="节点离线/异常接入", id="SRS-F-12-004")
 * 模拟节点离线故障。
 */
bool injectNodeOffline(const std::string& node_id, uint32_t duration_ms) {
    std::cout << "[SU-FAULT] 节点离线: node_id=" << node_id
              << ", duration=" << duration_ms << "ms" << std::endl;
    return true;
}

/**
 * @requirement(name="节点离线/异常接入", id="SRS-F-12-004")
 * 模拟节点异常接入故障。
 */
bool injectNodeAbnormal(const std::string& node_id) {
    std::cout << "[SU-FAULT] 节点异常接入: node_id=" << node_id << std::endl;
    return true;
}

/**
 * @requirement(name="波特率异常波动注入", id="SRS-F-12-005")
 * 向目标总线注入波特率异常波动。
 */
bool injectBaudRateAnomaly(BusType bus_type, uint32_t abnormal_baud, uint32_t duration_ms) {
    std::cout << "[SU-FAULT] 注入波特率异常: bus_type="
              << static_cast<int>(bus_type)
              << ", abnormal_baud=" << abnormal_baud
              << ", duration=" << duration_ms << "ms" << std::endl;
    return true;
}

// ============================================================================
// 总线测试分析单元 (SU-TEST) — 实现
// ============================================================================

/**
 * @requirement(name="40m内总线测试分析功能", id="SRS-F-10-001")
 * 执行短距离总线性能测试（≤40m），测量延迟、吞吐量和丢包率。
 */
PerformanceMetrics testShortBusPerformance(BusType bus_type, uint32_t test_duration_sec) {
    PerformanceMetrics metrics;
    metrics.avg_latency_us   = 50.0;
    metrics.max_latency_us   = 120.0;
    metrics.min_latency_us   = 10.0;
    metrics.throughput_mbps  = 950.0;
    metrics.packet_loss_rate = 0.01;
    metrics.total_packets    = test_duration_sec * 10000;
    metrics.lost_packets     = static_cast<uint64_t>(metrics.total_packets * 0.0001);

    std::cout << "[SU-TEST] 短距离测试完成 (≤40m): bus_type="
              << static_cast<int>(bus_type)
              << ", avg_latency=" << metrics.avg_latency_us << "us"
              << ", throughput=" << metrics.throughput_mbps << "Mbps"
              << ", loss_rate=" << metrics.packet_loss_rate << "%" << std::endl;
    return metrics;
}

/**
 * @requirement(name="40m以上总线测试分析功能", id="SRS-F-10-002")
 * 执行长距离总线性能测试（>40m，含中继），测量延迟、吞吐量和丢包率。
 */
PerformanceMetrics testLongBusPerformance(BusType bus_type, uint32_t test_duration_sec) {
    PerformanceMetrics metrics;
    // 长距离延迟通常更高
    metrics.avg_latency_us   = 200.0;
    metrics.max_latency_us   = 500.0;
    metrics.min_latency_us   = 50.0;
    metrics.throughput_mbps  = 800.0;
    metrics.packet_loss_rate = 0.05;
    metrics.total_packets    = test_duration_sec * 8000;
    metrics.lost_packets     = static_cast<uint64_t>(metrics.total_packets * 0.0005);

    std::cout << "[SU-TEST] 长距离测试完成 (>40m): bus_type="
              << static_cast<int>(bus_type)
              << ", avg_latency=" << metrics.avg_latency_us << "us"
              << ", throughput=" << metrics.throughput_mbps << "Mbps"
              << ", loss_rate=" << metrics.packet_loss_rate << "%" << std::endl;
    return metrics;
}

/**
 * @requirement(name="长时间满负荷测试分析功能", id="SRS-F-10-003")
 * 执行长时间满负荷稳定性测试（≥24小时），并生成结果报告。
 */
PerformanceMetrics testLongDurationStability(BusType bus_type, uint32_t duration_hours) {
    PerformanceMetrics metrics;
    uint64_t total_seconds = static_cast<uint64_t>(duration_hours) * 3600;

    metrics.avg_latency_us   = 80.0;
    metrics.max_latency_us   = 250.0;
    metrics.min_latency_us   = 15.0;
    metrics.throughput_mbps  = 900.0;
    metrics.packet_loss_rate = 0.02;
    metrics.total_packets    = total_seconds * 10000;
    metrics.lost_packets     = static_cast<uint64_t>(metrics.total_packets * 0.0002);

    std::cout << "[SU-TEST] 长时间稳定性测试完成: bus_type="
              << static_cast<int>(bus_type)
              << ", duration=" << duration_hours << "h"
              << ", total_packets=" << metrics.total_packets
              << ", loss_rate=" << metrics.packet_loss_rate << "%" << std::endl;
    return metrics;
}

// ============================================================================
// 辅助函数
// ============================================================================

std::string getVersion() {
    return "BNTVS_SW v1.0.0";
}

void printHelp() {
    std::cout << "\n=== BNTVS_SW - 总线网络测试验证软件 ===\n"
              << "用法: BNTVS_SW [选项]\n\n"
              << "选项:\n"
              << "  --help          显示本帮助信息\n"
              << "  --version       显示版本信息\n"
              << "  --demo          运行功能演示\n\n"
              << "功能单元:\n"
              << "  SU-COM    基础通用通信单元\n"
              << "  SU-PROT   协议兼容单元\n"
              << "  SU-STOR   数据存储单元\n"
              << "  SU-REPLAY 数据管理与回放单元\n"
              << "  SU-ROUTE  总线路由单元\n"
              << "  SU-ANALY  总线分析单元\n"
              << "  SU-FAULT  故障注入单元\n"
              << "  SU-CONV   信号转换单元\n"
              << "  SU-TEST   总线测试分析单元\n"
              << std::endl;
}

} // namespace bntvs
