#pragma once
// ── CS2 External C++ WebRadar — WebSocket + HTTP Server ─────────────────────
// Matches C# WebRadarServer.cs: serves the React frontend over HTTP,
// broadcasts JSON game state to all connected WebSocket clients.
// Uses ixwebsocket for both HTTP static serving and WS.

#include "game/game_data.h"
#include "game/player.h"
#include "server/webradar_config.h"
#include "server/radar_config_store.h"

#include <ixwebsocket/IXWebSocketServer.h>
#include <ixwebsocket/IXHttpServer.h>
#include <ixwebsocket/IXWebSocket.h>
#include <ixwebsocket/IXConnectionState.h>
#include <nlohmann/json.hpp>
#include <atomic>
#include <memory>

class WebRadarServer {
public:
    WebRadarServer(const WebRadarConfig& config, GameData* game_data,
                   RadarConfigStore* config_store);
    ~WebRadarServer();

    // Start the server (blocking — call from main thread)
    bool start();

    // Stop the server
    void stop();

    // Called by GameData::frame_produced — builds and broadcasts JSON
    void broadcast(GameData& data);

    // Returns true while the server event loop is active
    bool is_running() const { return m_running.load(); }

private:
    WebRadarConfig m_config;
    GameData* m_game_data;
    RadarConfigStore* m_config_store;

    std::unique_ptr<ix::HttpServer> m_server;
    std::atomic<bool> m_running{false};

    // Rate limiting
    long long m_last_broadcast_tick = 0;
    static constexpr long long BROADCAST_INTERVAL_MS = 8; // ~120 Hz max

    // ── JSON builders ────────────────────────────────────────────────────
    nlohmann::json build_players_json(GameData& data);
    nlohmann::json build_bomb_json(GameData& data);
    nlohmann::json build_round_info_json(GameData& data);
    nlohmann::json build_grenades_json(GameData& data);
    nlohmann::json build_dropped_weapons_json(GameData& data);
    float compute_bomb_damage(float player_x, float player_y, float bomb_x, float bomb_y);
};
