#ifndef WS_MANAGER_H
#define WS_MANAGER_H

// Must be defined before including any Windows headers
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <queue>
#endif

#ifndef NOMINMAX
#define NOMINMAX
#endif

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0601  // Windows 7 or later
#endif

// Winsock and Bluetooth headers
#include <winsock2.h>
#include <ws2bth.h>
#include <bluetoothapis.h>
#include <thread>
#include <mutex>
#include <chrono>
#include <vector>
#include <atomic>
#include <squirrel.h>

// Link required libraries
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "Bthprops.lib")

#ifndef BT_PORT_ANY
#define BT_PORT_ANY ((ULONG)-1)
#endif

#ifndef BTH_ADDR_NULL
#define BTH_ADDR_NULL ((BTH_ADDR)0)
#endif

class WebSocketManager {
public:
    struct CallbackEvent {
        enum Type { CONNECT, DISCONNECT, MESSAGE };
        Type type;
        std::string data;
        SOCKET client_socket;
    };

    struct ClientConnection {
        SOCKET socket;
        std::thread receive_thread;
        std::atomic<bool> active;

        ClientConnection(SOCKET s) : socket(s), active(true) {}
    };

private:
    SOCKET m_listen_socket;
    std::vector<ClientConnection*> m_connections;
    mutable std::mutex m_connections_mutex;
    std::thread m_accept_thread;
    std::atomic<bool> m_running;
    bool m_initialized;
    std::chrono::steady_clock::time_point m_start_time;
    uint16_t m_port;

    // Squirrel VM and callbacks
    HSQUIRRELVM m_vm;
    HSQOBJECT m_on_connect_callback;
    HSQOBJECT m_on_disconnect_callback;
    HSQOBJECT m_on_message_callback;
    bool m_has_on_connect;
    bool m_has_on_disconnect;
    bool m_has_on_message;

    // Event queue - car la VM Squirrel n'est pas thread-safe
    // Les callbacks doivent être appelés depuis le thread principal
    std::queue<CallbackEvent> m_event_queue;
    mutable std::mutex m_queue_mutex;

    void InternalOnConnect(SOCKET client_socket);
    void InternalOnDisconnect(SOCKET client_socket);
    void InternalOnMessage(SOCKET client_socket, const std::string& message);

    void InitializeServer();
    void AcceptLoop();
    void ReceiveLoop(ClientConnection* connection);
    bool SendToClient(SOCKET client_socket, const std::string& message);

public:
    WebSocketManager(HSQUIRRELVM vm);
    ~WebSocketManager();

    // Server control
    bool Start(uint16_t port);
    void Stop();
    bool IsRunning() const { return m_running; }

    // Messaging
    void Broadcast(const std::string& message);

    // Statistics
    int GetConnectionCount() const;
    float GetUptime() const;
    uint16_t GetPort() const { return m_port; }

    // Squirrel callbacks
    void SetOnConnectCallback(HSQOBJECT callback);
    void SetOnDisconnectCallback(HSQOBJECT callback);
    void SetOnMessageCallback(HSQOBJECT callback);

    // Process events - DOIT être appelé depuis le thread principal !
    // C'est ici que les callbacks Squirrel sont réellement invoqués
    void ProcessEvents();
};

#endif // WS_MANAGER_H