#include <iostream>
#include <signal.h>
#include <thread>
#include <chrono>
#include "http_server.h"

using namespace jtjai_media;

// 全局HTTP服务器实例
static std::unique_ptr<HttpServer> g_http_server;
static std::atomic<bool> g_interrupted(false);

// 信号处理函数
void signal_handler(int signal) {
    std::cout << "\n接收到信号 " << signal << "，正在停止服务器..." << std::endl;
    g_interrupted.store(true);
    if (g_http_server) {
        g_http_server->stop();
    }
}

int main(int argc, char* argv[]) {
    std::cout << "========================================" << std::endl;
    std::cout << "RTSP视频流管理HTTP服务器" << std::endl;
    std::cout << "========================================" << std::endl;
    
    // 注册信号处理器
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);
    
    // 解析命令行参数
    std::string output_directory = "./output";
    int port = 8080;
    
    if (argc > 1) {
        output_directory = argv[1];
    }
    if (argc > 2) {
        port = std::atoi(argv[2]);
    }
    
    std::cout << "输出目录: " << output_directory << std::endl;
    std::cout << "监听端口: " << port << std::endl;
    
    try {
        // 创建HTTP服务器
        g_http_server = std::make_unique<HttpServer>(output_directory, port);
        
        // 启动服务器
        if (!g_http_server->start()) {
            std::cerr << "启动HTTP服务器失败" << std::endl;
            return 1;
        }
        
        std::cout << "\nHTTP服务器已启动，按 Ctrl+C 停止服务器\n" << std::endl;
        
        // 保持主线程运行
        while (!g_interrupted.load()) {
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        
        std::cout << "\n服务器已停止" << std::endl;
        
    } catch (const std::exception& e) {
        std::cerr << "服务器异常: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}
