// main.cpp
#include "app_config.hpp"
#include "rtsp_manager.hpp"
#include "logger.hpp"
#include "mqtt_client_wrapper.hpp"
#include <thread>
#include <atomic>
#include <csignal>

std::atomic<bool> g_running(true);

void signalHandler(int signum)
{
    g_running = false;
    RTSPManager::stop();
}

int main()
{
    signal(SIGINT, [](int)
           { g_running = false; RTSPManager::stop(); });
    signal(SIGPIPE, SIG_IGN);

    // 初始化日志文件
    Logger::set_log_to_file(get_executable_dir_file_path("app.log"));

    try
    {
        // 从可执行文件所在目录读取配置文件
        g_app_config = AppConfig::load_from_file(get_executable_dir_file_path("config.json"));
    }
    catch (const std::exception &e)
    {
        LOG_ERROR(std::string("Failed to load config: ") + e.what());
        return -1;
    }

    // 先在主线程初始化 GStreamer
    RTSPManager::init();

    // 启动 RTSP server（loop 可在子线程）
    std::thread rtsp_thread([&]()
                            { RTSPManager::start(g_app_config.cameras); });

    // 启动 MQTT 客户端线程
    std::thread mqtt_thread(mqtt_client_thread_func);

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

    // 等待退出信号
    if (rtsp_thread.joinable())
        rtsp_thread.join();
    if (mqtt_thread.joinable())
        mqtt_thread.join();

    LOG_INFO("[MAIN] Program exited cleanly.");
    return 0;
}