#pragma once
#include <atomic>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <string>
#include <thread>

#include "Web/BulletTrackCache.h"
#include "Web/MapRegistry.h"
#include "Web/MapTileService.h"
#include "Web/WebSnapshotService.h"

// Forward-declare httplib types to avoid pulling the whole header (which
// includes <Winsock2.h>) into every translation unit that includes this header.
namespace httplib { class Server; struct Response; }

// -------------------------------------------------------------------------
// WebRadarConfig — tuneable startup parameters.
// -------------------------------------------------------------------------

struct WebRadarConfig {
    std::string bindAddress       = "0.0.0.0";
    int         port              = 7777;
    std::string password          = "";
    int         snapshotIntervalMs = 100;  // max web snapshot rate (default 10 Hz)
};

// -------------------------------------------------------------------------
// WebRadarServer
// -------------------------------------------------------------------------

class WebRadarServer {
public:
    explicit WebRadarServer(WebRadarConfig config = {});
    ~WebRadarServer();

    WebRadarServer(const WebRadarServer&)            = delete;
    WebRadarServer& operator=(const WebRadarServer&) = delete;

    /// Start the HTTP server on a background thread.
    void Start();

    /// Stop the HTTP server and join the background thread.
    void Stop();

    /// Feed a new RuntimeUpdate into the server.  Thread-safe.
    void PushSnapshot(const RuntimeUpdate& update);

private:
    WebRadarConfig      m_config;
    WebSnapshotService  m_snapshotSvc;
    BulletTrackCache    m_bullets;
    MapTileService      m_tiles;
    const MapInfo*      m_currentMap = nullptr;

    std::unique_ptr<httplib::Server> m_server;
    std::thread                      m_thread;

    // SSE broadcast state.
    mutable std::mutex      m_cvMutex;
    std::condition_variable m_cv;
    std::string             m_latestPayload;  // full "event: state\ndata: ...\n\n"
    std::string             m_latestJson;     // JSON only (for /api/state polling)
    std::string             m_bootstrapJson;  // /api/bootstrap response
    int64_t                 m_broadcastSeq = 0;
    std::atomic<bool>       m_stopping{false};
    int64_t                 m_nextSnapshotMs = 0;   // rate-limit for JSON builds
    std::string             m_lastBootstrapMapId;   // only rebuild bootstrap on map change

    void SetupRoutes();
    void ServeFile(httplib::Response& res, const std::string& filename,
                   const std::string& contentType);

    /// Returns true if the request is permitted (localhost, no password, or
    /// correct password query parameter).
    bool Authorise(const std::string& remoteAddr,
                   const std::string& passwordParam) const;

    /// Absolute path to webroot/<file> relative to the executable directory.
    std::string WebrootPath(const std::string& file) const;

    static int64_t NowMs();
};
