/*
 * voicecat-server entry point.
 *
 * Goal (docs/deployment.md): one command, zero config, encrypted + listening. Parses flags
 * (see docs/building.md for the full list + manual-testing walkthrough) and hands off to
 * Server::run() (server.cpp), which really does generate the identity/cert, open the SQLite
 * store, and bind the TCP/TLS + UDP listeners.
 */
#include <cstdio>
#include <cstring>
#include <string>

#include "server.h"
#include "voicecat.h"

namespace {

void print_help(const char* argv0) {
    std::printf(
        "voicecat-server %s\n\n"
        "Usage: %s [options]\n"
        "  --port <n>          control+media port (default 8384)\n"
        "  --data-dir <path>   data directory (default ./voicecat-data)\n"
        "  --name <name>       server name\n"
        "  --no-guests         disable guest access\n"
        "  --print-config      print effective config and exit\n"
        "  --version           print version and exit\n"
        "  --help              this help\n",
        vc_version_string(), argv0);
}

}  // namespace

int main(int argc, char** argv) {
    // MSVCRT/MinGW treat _IOLBF as full buffering for non-console streams (e.g. when a
    // launcher redirects stdout to a pipe, as the C# interop smoke test's Process does to
    // read the bound port) — go unbuffered so the startup banner (incl. "TCP :<port>") is
    // visible immediately instead of sitting in the CRT's buffer until it fills or the
    // process exits. Same fix as tools/vccli/src/main.cpp.
    std::setvbuf(stdout, nullptr, _IONBF, 0);

    voicecat::server::Config cfg;
    bool print_config_only = false;

    for (int i = 1; i < argc; ++i) {
        const char* a = argv[i];
        auto next = [&]() -> const char* { return (i + 1 < argc) ? argv[++i] : ""; };
        if (std::strcmp(a, "--help") == 0) {
            print_help(argv[0]);
            return 0;
        } else if (std::strcmp(a, "--version") == 0) {
            std::printf("voicecat-server %s (protocol v%d)\n", vc_version_string(),
                        VOICECAT_PROTOCOL_VERSION);
            return 0;
        } else if (std::strcmp(a, "--port") == 0) {
            cfg.bind_port = static_cast<uint16_t>(std::atoi(next()));
        } else if (std::strcmp(a, "--data-dir") == 0) {
            cfg.data_dir = next();
        } else if (std::strcmp(a, "--name") == 0) {
            cfg.server_name = next();
        } else if (std::strcmp(a, "--no-guests") == 0) {
            cfg.allow_guests = false;
        } else if (std::strcmp(a, "--print-config") == 0) {
            print_config_only = true;
        } else {
            std::fprintf(stderr, "unknown option: %s (try --help)\n", a);
            return 2;
        }
    }

    std::printf("[voicecat-server %s] starting\n", vc_version_string());
    voicecat::server::Server server(cfg);
    if (print_config_only) {
        // run() currently just prints config; in M1 split this into a pure config dump.
    }
    return server.run();
}
