// main.cpp
// vehicle_agent_windows 入口。
// 启动底盘域（默认 9001）和运控域（默认 9002）两个 TCP 服务线程。
//
// 用法：
//   vehicle_agent_windows [--chassis-port <port>] [--control-port <port>]

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <thread>
#include <csignal>
#include <atomic>

#include "chassis_domain_server.hpp"
#include "control_domain_server.hpp"
#include "chassis_handler.hpp"
#include "control_handler.hpp"

static std::atomic<bool> g_shutdown{false};

static void sig_handler(int) { g_shutdown = true; }

int main(int argc, char* argv[])
{
    uint16_t chassis_port = 9001;
    uint16_t control_port = 9002;

    // 简单命令行解析
    for (int i = 1; i < argc; ++i) {
        if (std::strcmp(argv[i], "--chassis-port") == 0 && i + 1 < argc)
            chassis_port = static_cast<uint16_t>(std::atoi(argv[++i]));
        else if (std::strcmp(argv[i], "--control-port") == 0 && i + 1 < argc)
            control_port = static_cast<uint16_t>(std::atoi(argv[++i]));
    }

    std::signal(SIGINT,  sig_handler);
    std::signal(SIGTERM, sig_handler);

    // 默认 stub handler，子类化后可接入真实硬件
    vaw::ChassisHandler chassis_handler;
    vaw::ControlHandler control_handler;

    vaw::ChassisDomainServer chassis_server(chassis_port, &chassis_handler);
    vaw::ControlDomainServer control_server(control_port, &control_handler);

    std::thread t_chassis([&]() {
        try { chassis_server.run(); }
        catch (const std::exception& e)
        { std::fprintf(stderr, "[chassis] 启动失败: %s\n", e.what()); }
    });

    std::thread t_control([&]() {
        try { control_server.run(); }
        catch (const std::exception& e)
        { std::fprintf(stderr, "[control] 启动失败: %s\n", e.what()); }
    });

    std::printf("vehicle_agent_windows 已启动，按 Ctrl+C 退出。\n");

    // 等待退出信号
    while (!g_shutdown)
        std::this_thread::sleep_for(std::chrono::milliseconds(200));

    std::printf("\n正在关闭...\n");
    chassis_server.stop();
    control_server.stop();

    t_chassis.join();
    t_control.join();

    std::printf("已退出。\n");
    return 0;
}
