#include "server.h"
#include "config/server_config.h"
#include <iostream>
#include <csignal>
#include <memory>

static std::unique_ptr<scar::Server> g_server;

void signalHandler(int signum) {
    std::cout << "\nShutting down server..." << std::endl;
    if (g_server) {
        g_server->stop();
    }
}

void printUsage(const char* program_name) {
    std::cout << "Usage: " << program_name << " [OPTIONS]\n"
              << "\nOptions:\n"
              << "  --db <path>      Path to SQLite database (default: scarchat.db)\n"
              << "  --cert <path>    Path to SSL certificate (default: server.pem)\n"
              << "  --key <path>     Path to SSL private key (default: server.key)\n"
              << "  --help           Show this help message\n"
              << std::endl;
}

int main(int argc, char* argv[]) {
    std::cout << "SCAR Chat Server v1.0.0" << std::endl;
    std::cout << "=======================" << std::endl;
    
    // Parse command-line arguments
    scar::ServerConfig config;
    config.load();
    
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        
        if (arg == "--help") {
            printUsage(argv[0]);
            return 0;
        } else if (arg == "--db" && i + 1 < argc) {
            config.setDbPath(argv[++i]);
        } else if (arg == "--cert" && i + 1 < argc) {
            config.setCertPath(argv[++i]);
        } else if (arg == "--key" && i + 1 < argc) {
            config.setKeyPath(argv[++i]);
        } else {
            std::cerr << "Unknown option: " << arg << std::endl;
            printUsage(argv[0]);
            return 1;
        }
    }
    
    // Display configuration
    std::cout << "\nConfiguration:\n"
              << "  Database: " << config.dbPath() << "\n"
              << "  SSL Cert: " << config.certPath() << "\n"
              << "  SSL Key:  " << config.keyPath() << "\n"
              << "  Host:     " << config.host() << "\n"
              << "  Port:     " << config.port() << "\n"
              << std::endl;
    
    try {
        // Setup signal handlers
        std::signal(SIGINT, signalHandler);
        std::signal(SIGTERM, signalHandler);
        
        // Create and run server
        g_server = std::make_unique<scar::Server>(config);
        g_server->run();
        
    } catch (const std::exception& e) {
        std::cerr << "Server error: " << e.what() << std::endl;
        return 1;
    }
    
    std::cout << "Server stopped." << std::endl;
    return 0;
}
