/*
 * HDGL Analog NetCat Implementation - C Module
 * Dₙ(r) Consensus-Based Network Communication Tool
 *
 * Features:
 * - Analog dimension-based encryption using Dₙ(r) formula
 * - Phase synchronization for secure channels
 * - Real-time entropy generation from bridge state
 * - Multi-mode operation (client, server, both)
 * - Connection logging and monitoring
 * - Integration with HDGL Bridge v40 state
 */

#define _POSIX_C_SOURCE 199309L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>
#include <math.h>
#include <fcntl.h>
#include <sys/select.h>

// Math constants
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

// Bridge globals integration
#include "bridge_globals.h"

#define MAX_MESSAGE_SIZE 4096
#define MAX_CLIENTS 10
#define DEFAULT_NETCAT_PORT 9095
#define ANALOG_DIMENSIONS 8

// NetCat operation modes
typedef enum {
    NETCAT_CLIENT = 0,
    NETCAT_SERVER = 1,
    NETCAT_BOTH = 2
} netcat_mode_t;

// Analog encryption state
typedef struct {
    double phase;
    double amplitude;
    double frequency;
    double Dn_value;
} analog_dimension_t;

// NetCat connection state
typedef struct {
    int socket_fd;
    struct sockaddr_in addr;
    pthread_t thread;
    int active;
    char remote_host[256];
    int remote_port;
    time_t connected_time;
} netcat_connection_t;

// NetCat server state
typedef struct {
    netcat_mode_t mode;
    int local_port;
    char remote_host[256];
    int remote_port;
    int server_fd;
    int running;
    pthread_t server_thread;
    netcat_connection_t connections[MAX_CLIENTS];
    int connection_count;

    // Analog encryption state
    analog_dimension_t dimensions[ANALOG_DIMENSIONS];
    char encryption_key[65]; // 32 bytes hex + null
    int auto_generate_key;

    // Statistics
    unsigned long messages_sent;
    unsigned long messages_received;
    unsigned long bytes_sent;
    unsigned long bytes_received;
} hdgl_netcat_t;

// Global netcat instance
static hdgl_netcat_t g_netcat = {0};
static pthread_mutex_t g_netcat_lock = PTHREAD_MUTEX_INITIALIZER;

// Headless mode configuration
typedef struct {
    int enabled;
    int client_interval_ms;     // How often to attempt client connections (default: 5000ms)
    char target_hosts[10][256]; // List of target hosts for client connections
    int target_ports[10];       // Corresponding ports for target hosts
    int target_count;           // Number of target hosts
    pthread_t client_thread;    // Thread for client operations
    pthread_t modulator_thread; // Thread for signal modulation
    int modulation_enabled;     // Enable analog signal modulation
    double modulation_rate;     // Modulation frequency (Hz)
    int client_running;         // Client thread status
    int modulator_running;      // Modulator thread status
} headless_config_t;

static headless_config_t g_headless = {0};

// Mathematical constants for Dₙ(r)
static const double PHI = 1.6180339887498948;
static const long long FIBONACCI[] = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
static const int PRIMES[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

// Compute Dₙ(r) formula: √(φ·Fₙ·2ⁿ·Pₙ·Ω)·r^k
double compute_dn_r(int n, double r) {
    if (n < 1 || n > 8) return 1.0;

    double F_n = (double)FIBONACCI[n];
    double P_n = (double)PRIMES[n-1];
    double two_n = pow(2.0, n);
    double k = (n + 1) / 8.0;
    double Omega = 1.0; // Base omega constant

    return sqrt(PHI * F_n * two_n * P_n * Omega) * pow(fabs(r), k);
}

// Initialize analog dimensions
void init_analog_dimensions() {
    pthread_mutex_lock(&g_netcat_lock);

    for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
        g_netcat.dimensions[i].phase = ((double)rand() / RAND_MAX) * 2.0 * M_PI;
        g_netcat.dimensions[i].amplitude = 1.0;
        g_netcat.dimensions[i].frequency = 1.0 + i * 0.1;

        double r = (double)i / 8.0;
        g_netcat.dimensions[i].Dn_value = compute_dn_r(i + 1, r);
    }

    g_netcat.auto_generate_key = 1;

    pthread_mutex_unlock(&g_netcat_lock);
}

// Evolve analog dimensions (sync with bridge evolution)
void evolve_dimensions() {
    pthread_mutex_lock(&g_netcat_lock);

    const double dt = 0.01;

    for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
        // Update phase
        g_netcat.dimensions[i].phase += dt * g_netcat.dimensions[i].frequency;
        if (g_netcat.dimensions[i].phase > 2.0 * M_PI) {
            g_netcat.dimensions[i].phase -= 2.0 * M_PI;
        }

        // Recompute Dₙ(r) value
        double r = (double)i / 8.0;
        g_netcat.dimensions[i].Dn_value = compute_dn_r(i + 1, r);
    }

    pthread_mutex_unlock(&g_netcat_lock);
}

// Generate analog encryption key from dimension states
void generate_analog_key() {
    pthread_mutex_lock(&g_netcat_lock);

    char key_components[ANALOG_DIMENSIONS][3];

    for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
        double phase = g_netcat.dimensions[i].phase;
        double Dn = g_netcat.dimensions[i].Dn_value;

        // Generate key byte from phase and Dₙ(r)
        int key_byte = ((int)(phase * Dn * 1000.0)) % 256;
        snprintf(key_components[i], 3, "%02x", key_byte);
    }

    // Concatenate components
    g_netcat.encryption_key[0] = '\0';
    for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
        strncat(g_netcat.encryption_key, key_components[i], 2);
    }

    // Extend to 32 bytes (64 hex chars)
    while (strlen(g_netcat.encryption_key) < 64) {
        strncat(g_netcat.encryption_key, g_netcat.encryption_key,
               64 - strlen(g_netcat.encryption_key));
    }
    g_netcat.encryption_key[64] = '\0';

    pthread_mutex_unlock(&g_netcat_lock);
}

// Analog XOR encryption using dimension phases
int analog_encrypt(const char* message, char* encrypted, int max_len) {
    if (!message || !encrypted || max_len < 1) return -1;

    pthread_mutex_lock(&g_netcat_lock);

    int msg_len = strlen(message);
    int key_len = strlen(g_netcat.encryption_key);

    if (msg_len * 2 + 1 > max_len) {
        pthread_mutex_unlock(&g_netcat_lock);
        return -1;
    }

    for (int i = 0; i < msg_len; i++) {
        int dim_idx = i % ANALOG_DIMENSIONS;

        // Get key byte (2 hex chars)
        char key_hex[3] = {0};
        int key_pos = (i * 2) % key_len;
        key_hex[0] = g_netcat.encryption_key[key_pos];
        key_hex[1] = g_netcat.encryption_key[key_pos + 1];
        int key_byte = (int)strtol(key_hex, NULL, 16);

        // Get phase byte
        double phase = g_netcat.dimensions[dim_idx].phase;
        int phase_byte = ((int)(phase * 40.74)) % 256;

        // XOR encryption
        char encrypted_byte = message[i] ^ key_byte ^ phase_byte;

        // Convert to hex
        snprintf(&encrypted[i * 2], 3, "%02x", (unsigned char)encrypted_byte);
    }

    pthread_mutex_unlock(&g_netcat_lock);
    return msg_len * 2;
}

// Analog XOR decryption
int analog_decrypt(const char* encrypted_hex, char* message, int max_len) {
    if (!encrypted_hex || !message || max_len < 1) return -1;

    pthread_mutex_lock(&g_netcat_lock);

    int hex_len = strlen(encrypted_hex);
    if (hex_len % 2 != 0 || hex_len / 2 + 1 > max_len) {
        pthread_mutex_unlock(&g_netcat_lock);
        return -1;
    }

    int msg_len = hex_len / 2;
    int key_len = strlen(g_netcat.encryption_key);

    for (int i = 0; i < msg_len; i++) {
        // Parse hex byte
        char hex_byte[3] = {encrypted_hex[i*2], encrypted_hex[i*2+1], 0};
        unsigned char encrypted_byte = (unsigned char)strtol(hex_byte, NULL, 16);

        int dim_idx = i % ANALOG_DIMENSIONS;

        // Get key byte
        char key_hex[3] = {0};
        int key_pos = (i * 2) % key_len;
        key_hex[0] = g_netcat.encryption_key[key_pos];
        key_hex[1] = g_netcat.encryption_key[key_pos + 1];
        int key_byte = (int)strtol(key_hex, NULL, 16);

        // Get phase byte
        double phase = g_netcat.dimensions[dim_idx].phase;
        int phase_byte = ((int)(phase * 40.74)) % 256;

        // XOR decryption
        message[i] = encrypted_byte ^ key_byte ^ phase_byte;
    }

    message[msg_len] = '\0';

    pthread_mutex_unlock(&g_netcat_lock);
    return msg_len;
}

// Log connection activity
void log_netcat_activity(const char* type, const char* message) {
    time_t now;
    time(&now);
    struct tm* tm_info = localtime(&now);

    char timestamp[64];
    strftime(timestamp, sizeof(timestamp), "%H:%M:%S", tm_info);

    printf("[%s] NetCat %s: %s\n", timestamp, type, message);
}

// Handle client connection
void* handle_client_connection(void* arg) {
    netcat_connection_t* conn = (netcat_connection_t*)arg;
    char buffer[MAX_MESSAGE_SIZE];
    char encrypted[MAX_MESSAGE_SIZE * 2];
    char decrypted[MAX_MESSAGE_SIZE];

    char log_msg[512];
    snprintf(log_msg, sizeof(log_msg), "Client connected from %s:%d",
             inet_ntoa(conn->addr.sin_addr), ntohs(conn->addr.sin_port));
    log_netcat_activity("CONNECT", log_msg);

    while (conn->active) {
        int bytes_received = recv(conn->socket_fd, buffer, sizeof(buffer) - 1, 0);

        if (bytes_received <= 0) {
            if (bytes_received < 0) {
                log_netcat_activity("ERROR", "Receive error");
            }
            break;
        }

        buffer[bytes_received] = '\0';

        // Try to decrypt message
        int decrypted_len = analog_decrypt(buffer, decrypted, sizeof(decrypted));
        if (decrypted_len > 0) {
            snprintf(log_msg, sizeof(log_msg), "RX [%d bytes] %s",
                     decrypted_len, decrypted);
        } else {
            snprintf(log_msg, sizeof(log_msg), "RX [%d bytes] (raw) %s",
                     bytes_received, buffer);
        }
        log_netcat_activity("RECV", log_msg);

        // Update statistics
        pthread_mutex_lock(&g_netcat_lock);
        g_netcat.messages_received++;
        g_netcat.bytes_received += bytes_received;
        pthread_mutex_unlock(&g_netcat_lock);

        // Echo back encrypted
        const char* echo_msg = (decrypted_len > 0) ? decrypted : buffer;
        int encrypted_len = analog_encrypt(echo_msg, encrypted, sizeof(encrypted));

        if (encrypted_len > 0) {
            send(conn->socket_fd, encrypted, encrypted_len, 0);

            snprintf(log_msg, sizeof(log_msg), "TX [%d bytes] echo", encrypted_len);
            log_netcat_activity("SEND", log_msg);

            pthread_mutex_lock(&g_netcat_lock);
            g_netcat.messages_sent++;
            g_netcat.bytes_sent += encrypted_len;
            pthread_mutex_unlock(&g_netcat_lock);
        }

        // Evolve dimensions after each message
        evolve_dimensions();
        if (g_netcat.auto_generate_key) {
            generate_analog_key();
        }
    }

    close(conn->socket_fd);
    conn->active = 0;

    log_netcat_activity("DISCONNECT", "Client disconnected");

    return NULL;
}

// Server thread function
void* netcat_server_thread(void* arg) {
    int port = *((int*)arg);
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_len = sizeof(client_addr);

    // Create server socket
    g_netcat.server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (g_netcat.server_fd < 0) {
        log_netcat_activity("ERROR", "Failed to create server socket");
        return NULL;
    }

    // Set socket options
    int opt = 1;
    setsockopt(g_netcat.server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

    // Bind server
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(port);

    if (bind(g_netcat.server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        log_netcat_activity("ERROR", "Failed to bind server socket");
        close(g_netcat.server_fd);
        return NULL;
    }

    // Listen
    if (listen(g_netcat.server_fd, MAX_CLIENTS) < 0) {
        log_netcat_activity("ERROR", "Failed to listen on server socket");
        close(g_netcat.server_fd);
        return NULL;
    }

    char log_msg[256];
    snprintf(log_msg, sizeof(log_msg), "Analog NetCat server listening on port %d", port);
    log_netcat_activity("START", log_msg);

    // Accept connections
    while (g_netcat.running) {
        int client_fd = accept(g_netcat.server_fd, (struct sockaddr*)&client_addr, &client_len);

        if (client_fd < 0) {
            if (errno == EINTR || !g_netcat.running) continue;
            log_netcat_activity("ERROR", "Accept failed");
            continue;
        }

        // Find available connection slot
        pthread_mutex_lock(&g_netcat_lock);
        int conn_idx = -1;
        for (int i = 0; i < MAX_CLIENTS; i++) {
            if (!g_netcat.connections[i].active) {
                conn_idx = i;
                break;
            }
        }

        if (conn_idx >= 0) {
            g_netcat.connections[conn_idx].socket_fd = client_fd;
            g_netcat.connections[conn_idx].addr = client_addr;
            g_netcat.connections[conn_idx].active = 1;
            time(&g_netcat.connections[conn_idx].connected_time);

            // Create client thread
            if (pthread_create(&g_netcat.connections[conn_idx].thread, NULL,
                             handle_client_connection, &g_netcat.connections[conn_idx]) == 0) {
                pthread_detach(g_netcat.connections[conn_idx].thread);
                g_netcat.connection_count++;
            } else {
                g_netcat.connections[conn_idx].active = 0;
                close(client_fd);
            }
        } else {
            log_netcat_activity("ERROR", "Maximum clients reached");
            close(client_fd);
        }

        pthread_mutex_unlock(&g_netcat_lock);
    }

    close(g_netcat.server_fd);
    log_netcat_activity("STOP", "Analog NetCat server stopped");

    return NULL;
}

// Connect as client
int netcat_connect_client(const char* host, int port) {
    struct sockaddr_in server_addr;
    int client_fd;

    // Create client socket
    client_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (client_fd < 0) {
        log_netcat_activity("ERROR", "Failed to create client socket");
        return -1;
    }

    // Setup server address
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);

    if (inet_pton(AF_INET, host, &server_addr.sin_addr) <= 0) {
        log_netcat_activity("ERROR", "Invalid server address");
        close(client_fd);
        return -1;
    }

    // Connect
    if (connect(client_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
        char log_msg[256];
        snprintf(log_msg, sizeof(log_msg), "Failed to connect to %s:%d", host, port);
        log_netcat_activity("ERROR", log_msg);
        close(client_fd);
        return -1;
    }

    char log_msg[256];
    snprintf(log_msg, sizeof(log_msg), "Connected to %s:%d", host, port);
    log_netcat_activity("CONNECT", log_msg);

    return client_fd;
}

// Send encrypted message
int netcat_send_message(int socket_fd, const char* message) {
    char encrypted[MAX_MESSAGE_SIZE * 2];

    int encrypted_len = analog_encrypt(message, encrypted, sizeof(encrypted));
    if (encrypted_len <= 0) {
        log_netcat_activity("ERROR", "Encryption failed");
        return -1;
    }

    int sent = send(socket_fd, encrypted, encrypted_len, 0);
    if (sent > 0) {
        char log_msg[256];
        snprintf(log_msg, sizeof(log_msg), "TX [%d bytes] %s", sent, message);
        log_netcat_activity("SEND", log_msg);

        pthread_mutex_lock(&g_netcat_lock);
        g_netcat.messages_sent++;
        g_netcat.bytes_sent += sent;
        pthread_mutex_unlock(&g_netcat_lock);

        // Evolve dimensions
        evolve_dimensions();
        if (g_netcat.auto_generate_key) {
            generate_analog_key();
        }
    }

    return sent;
}

// Initialize NetCat subsystem
int init_hdgl_netcat() {
    memset(&g_netcat, 0, sizeof(g_netcat));

    // Default configuration
    g_netcat.mode = NETCAT_SERVER;
    g_netcat.local_port = DEFAULT_NETCAT_PORT;
    strcpy(g_netcat.remote_host, "localhost");
    g_netcat.remote_port = DEFAULT_NETCAT_PORT;
    g_netcat.running = 0;

    // Initialize analog dimensions
    srand(time(NULL));
    init_analog_dimensions();
    generate_analog_key();

    log_netcat_activity("INIT", "HDGL Analog NetCat initialized");

    return 0;
}

// Start NetCat server
int start_netcat_server(int port) {
    if (g_netcat.running) {
        log_netcat_activity("ERROR", "NetCat server already running");
        return -1;
    }

    g_netcat.local_port = port;
    g_netcat.running = 1;

    if (pthread_create(&g_netcat.server_thread, NULL, netcat_server_thread, &g_netcat.local_port) != 0) {
        g_netcat.running = 0;
        log_netcat_activity("ERROR", "Failed to start server thread");
        return -1;
    }

    pthread_detach(g_netcat.server_thread);
    return 0;
}

// Stop NetCat server
void stop_netcat_server() {
    if (!g_netcat.running) return;

    g_netcat.running = 0;

    // Close server socket to break accept loop
    if (g_netcat.server_fd >= 0) {
        close(g_netcat.server_fd);
    }

    // Close all client connections
    pthread_mutex_lock(&g_netcat_lock);
    for (int i = 0; i < MAX_CLIENTS; i++) {
        if (g_netcat.connections[i].active) {
            g_netcat.connections[i].active = 0;
            close(g_netcat.connections[i].socket_fd);
        }
    }
    g_netcat.connection_count = 0;
    pthread_mutex_unlock(&g_netcat_lock);

    log_netcat_activity("STOP", "NetCat server stopped");
}

// Get NetCat status (for HTTP API)
void get_netcat_status(char* json, int max_len) {
    pthread_mutex_lock(&g_netcat_lock);

    // Calculate phase synchronization
    double mean_phase = 0.0;
    for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
        mean_phase += g_netcat.dimensions[i].phase;
    }
    mean_phase /= ANALOG_DIMENSIONS;

    double phase_var = 0.0;
    for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
        double diff = g_netcat.dimensions[i].phase - mean_phase;
        phase_var += diff * diff;
    }
    phase_var /= ANALOG_DIMENSIONS;

    double phase_sync = 1.0 - fmin(phase_var / (M_PI * M_PI), 1.0);
    int dimension_lock = (phase_var < 0.01) ? 1 : 0;
    int consensus_reached = (phase_sync > 0.95) ? 1 : 0;

    double entropy = 0.0;
    for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
        entropy += g_netcat.dimensions[i].Dn_value;
    }
    entropy /= ANALOG_DIMENSIONS;

    double channel_quality = (phase_sync + (entropy / 10.0)) / 2.0;
    channel_quality = fmin(channel_quality, 1.0);

    snprintf(json, max_len,
        "{\n"
        "  \"netcat_active\": %s,\n"
        "  \"status\": \"%s\",\n"
        "  \"mode\": \"%s\",\n"
        "  \"local_port\": %d,\n"
        "  \"server_port\": %d,\n"
        "  \"remote_host\": \"%s\",\n"
        "  \"remote_port\": %d,\n"
        "  \"connections\": %d,\n"
        "  \"messages_sent\": %lu,\n"
        "  \"messages_received\": %lu,\n"
        "  \"bytes_sent\": %lu,\n"
        "  \"bytes_received\": %lu,\n"
        "  \"analog_state\": {\n"
        "    \"phase_sync\": %.6f,\n"
        "    \"dimension_lock\": %s,\n"
        "    \"consensus_reached\": %s,\n"
        "    \"entropy\": %.6f,\n"
        "    \"channel_quality\": %.6f,\n"
        "    \"encryption_key_length\": %d,\n"
        "    \"auto_generate_key\": %s,\n"
        "    \"dn_r\": %.6f,\n"
        "    \"phase\": %.6f,\n"
        "    \"dimension\": %d\n"
        "  }\n"
        "}",
        g_netcat.running ? "true" : "false",
        g_netcat.running ? "running" : "stopped",
        (g_netcat.mode == NETCAT_CLIENT) ? "client" :
        (g_netcat.mode == NETCAT_SERVER) ? "server" : "both",
        g_netcat.local_port,
        g_netcat.local_port,
        g_netcat.remote_host,
        g_netcat.remote_port,
        g_netcat.connection_count,
        g_netcat.messages_sent,
        g_netcat.messages_received,
        g_netcat.bytes_sent,
        g_netcat.bytes_received,
        phase_sync,
        dimension_lock ? "true" : "false",
        consensus_reached ? "true" : "false",
        entropy,
        channel_quality,
        (int)strlen(g_netcat.encryption_key),
        g_netcat.auto_generate_key ? "true" : "false",
        g_netcat.dimensions[0].Dn_value,
        g_netcat.dimensions[0].phase,
        0
    );

    pthread_mutex_unlock(&g_netcat_lock);
}

// Headless client thread function
void* headless_client_thread(void* arg) {
    log_netcat_activity("CLIENT", "Headless client thread started");

    while (g_headless.client_running && g_netcat.running) {
        // Attempt connections to all target hosts
        for (int i = 0; i < g_headless.target_count; i++) {
            if (!g_headless.client_running) break;

            int client_fd = socket(AF_INET, SOCK_STREAM, 0);
            if (client_fd < 0) continue;

            struct sockaddr_in addr;
            memset(&addr, 0, sizeof(addr));
            addr.sin_family = AF_INET;
            addr.sin_port = htons(g_headless.target_ports[i]);

            if (inet_pton(AF_INET, g_headless.target_hosts[i], &addr.sin_addr) <= 0) {
                close(client_fd);
                continue;
            }

            // Set non-blocking for connection timeout
            int flags = fcntl(client_fd, F_GETFL, 0);
            fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);

            if (connect(client_fd, (struct sockaddr*)&addr, sizeof(addr)) == 0 || errno == EINPROGRESS) {
                // Connection successful or in progress
                fd_set write_fds;
                FD_ZERO(&write_fds);
                FD_SET(client_fd, &write_fds);

                struct timeval timeout = {2, 0}; // 2 second timeout
                if (select(client_fd + 1, NULL, &write_fds, NULL, &timeout) > 0) {
                    // Send analog sync message
                    char sync_msg[512];
                    snprintf(sync_msg, sizeof(sync_msg),
                        "HDGL_ANALOG_SYNC:%.6f:%.6f:%.6f:%s\n",
                        g_netcat.dimensions[0].phase,
                        g_netcat.dimensions[0].Dn_value,
                        g_netcat.dimensions[0].frequency,
                        g_netcat.encryption_key
                    );

                    send(client_fd, sync_msg, strlen(sync_msg), 0);

                    char target_info[512];
                    snprintf(target_info, sizeof(target_info),
                        "Connected to %s:%d", g_headless.target_hosts[i], g_headless.target_ports[i]);
                    log_netcat_activity("SYNC", target_info);
                }
            }

            close(client_fd);
        }

        // Sleep for the configured interval
        usleep(g_headless.client_interval_ms * 1000);
    }

    log_netcat_activity("CLIENT", "Headless client thread stopped");
    return NULL;
}

// Analog signal modulator thread
void* headless_modulator_thread(void* arg) {
    log_netcat_activity("MODULATOR", "Analog signal modulator started");

    double last_time = 0.0;
    struct timespec ts;

    while (g_headless.modulator_running && g_netcat.running) {
        clock_gettime(CLOCK_MONOTONIC, &ts);
        double current_time = ts.tv_sec + ts.tv_nsec / 1e9;

        if (last_time == 0.0) last_time = current_time;
        double dt = current_time - last_time;

        // Modulate analog signal based on bridge evolution state
        extern int g_evolution_count;
        extern double g_phase_variance;
        double evolution_phase = (double)(g_evolution_count % 32768) / 32768.0 * 2.0 * M_PI;
        double bridge_variance = g_phase_variance;

        pthread_mutex_lock(&g_netcat_lock);

        // Apply evolution-based modulation to dimensions
        for (int i = 0; i < ANALOG_DIMENSIONS; i++) {
            // Modulate phase based on bridge state
            double modulation_factor = sin(evolution_phase + i * M_PI / 4.0) * 0.1;
            g_netcat.dimensions[i].phase += modulation_factor * dt;

            // Adjust frequency based on variance
            double freq_mod = (bridge_variance > 10.0) ? 0.05 : -0.05;
            g_netcat.dimensions[i].frequency += freq_mod * dt;

            // Keep frequency in reasonable range
            if (g_netcat.dimensions[i].frequency < 0.5) g_netcat.dimensions[i].frequency = 0.5;
            if (g_netcat.dimensions[i].frequency > 2.0) g_netcat.dimensions[i].frequency = 2.0;

            // Normalize phase
            if (g_netcat.dimensions[i].phase > 2.0 * M_PI) {
                g_netcat.dimensions[i].phase -= 2.0 * M_PI;
            }
            if (g_netcat.dimensions[i].phase < 0) {
                g_netcat.dimensions[i].phase += 2.0 * M_PI;
            }
        }

        pthread_mutex_unlock(&g_netcat_lock);

        last_time = current_time;

        // Sleep for modulation rate (e.g., 100ms for 10Hz)
        usleep((int)(1000000.0 / g_headless.modulation_rate));
    }

    log_netcat_activity("MODULATOR", "Analog signal modulator stopped");
    return NULL;
}

// Configure headless mode
int configure_headless_mode(int enabled, const char* target_hosts[], int target_ports[], int target_count) {
    g_headless.enabled = enabled;

    if (!enabled) {
        // Stop headless mode
        g_headless.client_running = 0;
        g_headless.modulator_running = 0;
        return 0;
    }

    // Configure targets
    g_headless.target_count = (target_count > 10) ? 10 : target_count;
    for (int i = 0; i < g_headless.target_count; i++) {
        strncpy(g_headless.target_hosts[i], target_hosts[i], 255);
        g_headless.target_hosts[i][255] = '\0';
        g_headless.target_ports[i] = target_ports[i];
    }

    // Set default parameters
    g_headless.client_interval_ms = 5000;  // 5 seconds
    g_headless.modulation_enabled = 1;
    g_headless.modulation_rate = 10.0;     // 10 Hz

    log_netcat_activity("CONFIG", "Headless mode configured");
    return 0;
}

// Start headless mode
int start_headless_mode() {
    if (!g_headless.enabled) {
        log_netcat_activity("ERROR", "Headless mode not configured");
        return -1;
    }

    // Update NetCat mode
    g_netcat.mode = NETCAT_BOTH;

    // Start client thread
    g_headless.client_running = 1;
    if (pthread_create(&g_headless.client_thread, NULL, headless_client_thread, NULL) != 0) {
        g_headless.client_running = 0;
        log_netcat_activity("ERROR", "Failed to start headless client thread");
        return -1;
    }
    pthread_detach(g_headless.client_thread);

    // Start modulator thread if enabled
    if (g_headless.modulation_enabled) {
        g_headless.modulator_running = 1;
        if (pthread_create(&g_headless.modulator_thread, NULL, headless_modulator_thread, NULL) != 0) {
            g_headless.modulator_running = 0;
            log_netcat_activity("WARNING", "Failed to start modulator thread");
            // Don't fail completely if modulator fails
        } else {
            pthread_detach(g_headless.modulator_thread);
        }
    }

    log_netcat_activity("HEADLESS", "Headless mode started (client + modulator)");
    return 0;
}

// Stop headless mode
void stop_headless_mode() {
    if (!g_headless.enabled) return;

    g_headless.client_running = 0;
    g_headless.modulator_running = 0;

    log_netcat_activity("HEADLESS", "Headless mode stopped");
}

// Cleanup NetCat subsystem
void cleanup_hdgl_netcat() {
    stop_headless_mode();
    stop_netcat_server();
    log_netcat_activity("CLEANUP", "HDGL Analog NetCat cleaned up");
}