// main.cpp
// vehicle_agent_windows 入口。
// 启动统一 gateway（默认 9000）、底盘域（默认 9001）和运控域（默认 9002）服务线程。
//
// 用法：
//   vehicle_agent_windows [--gateway-port <port>] [--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"
#include "external_pose_store.hpp"
#include "vehicle_gateway_server.hpp"

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

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

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

    // 简单命令行解析
    for (int i = 1; i < argc; ++i) {
        if (std::strcmp(argv[i], "--gateway-port") == 0 && i + 1 < argc)
            gateway_port = static_cast<uint16_t>(std::atoi(argv[++i]));
        else 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);

    // 默认安全 handler：未注入真实底盘驱动适配器时，readiness 返回未就绪，动作请求会被拒绝。
    vaw::ChassisHandler chassis_handler;
    vaw::ControlHandler control_handler;
    vaw::ExternalPoseStore external_pose_store;
    control_handler.set_external_pose_store(&external_pose_store);

    vaw::VehicleGatewayServer gateway_server(
        gateway_port,
        &chassis_handler,
        &control_handler,
        &external_pose_store);
    vaw::ChassisDomainServer chassis_server(chassis_port, &chassis_handler);
    vaw::ControlDomainServer control_server(control_port, &control_handler);

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

    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 已启动，gateway=%u, chassis=%u, control=%u，按 Ctrl+C 退出。\n",
        gateway_port,
        chassis_port,
        control_port);

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

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

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

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