/**
 * @file mvgal_pool.h
 * @brief Internal pool manager structures
 *
 * SPDX-License-Identifier: MIT
 */

#ifndef MVGAL_POOL_INTERNAL_H
#define MVGAL_POOL_INTERNAL_H

#include <stdint.h>
#include <stdbool.h>
#include <pthread.h>
#include "mvgal/mvgal_network.h"
#include "transport/mvgal_transport.h"

#ifdef __cplusplus
extern "C" {
#endif

/******************************************************************************
 * Remote GPU tracking entry
 ******************************************************************************/

typedef struct {
    mvgal_net_remote_gpu_t  gpu;              /**< Remote GPU descriptor */
    uint64_t                last_seen_ns;      /**< Monotonic timestamp of last announce */
    uint32_t                health_check_idx;  /**< Round-robin health check index */
    bool                    in_use;            /**< Entry slot is active */
} mvgal_remote_gpu_entry_t;

/******************************************************************************
 * Pool internal state
 ******************************************************************************/

typedef struct {
    /* Configuration */
    mvgal_net_config_t      config;

    /* Peer tracking */
    mvgal_net_peer_t        peers[MVGAL_NET_MAX_PEERS];
    uint32_t                peer_count;

    /* Remote GPU tracking */
    mvgal_remote_gpu_entry_t remote_gpus[MVGAL_NET_MAX_PEERS * MVGAL_NET_MAX_GPU_ANNOUNCE];
    uint32_t                remote_gpu_count;

    /* Statistics */
    mvgal_net_stats_t       stats;

    /* Synchronisation */
    pthread_mutex_t         lock;

    /* State flags */
    bool                    initialized;
    bool                    discovery_running;
} mvgal_pool_internal_t;

/******************************************************************************
 * Internal function declarations
 ******************************************************************************/

/* Called by discovery when a new peer is found via UDP */
int mvgal_pool_add_peer(uint64_t node_id, const char *instance_name,
                        uint32_t num_gpus, uint32_t protocol_version,
                        const uint8_t *addr, uint32_t addr_len);

/* Called by transport peer callback on disconnect / timeout */
void mvgal_pool_remove_peer(uint64_t node_id);

/* Called by transport message callback on GPU_ANNOUNCE */
int mvgal_pool_update_gpus(uint64_t peer_node_id,
                           const mvgal_net_gpu_announce_t *announce,
                           const mvgal_net_gpu_descriptor_t *gpu_descs,
                           uint32_t num_gpus);

/* Called by remote work completion handler */
void mvgal_pool_notify_work_complete(uint64_t peer_node_id,
                                     uint64_t workload_id,
                                     uint32_t result);

/* Access the global pool instance */
mvgal_pool_internal_t *mvgal_pool_get_instance(void);

#ifdef __cplusplus
}
#endif

#endif /* MVGAL_POOL_INTERNAL_H */
