#pragma once
#include <atomic>
#include <optional>
#include <string>
#include "./dispacther.hpp"
#include "../scheduler/async_executor.hpp"

namespace lsp::core
{
    class LspServer
    {
    public:
        LspServer(size_t concurrency = std::thread::hardware_concurrency());
        ~LspServer();
        void Run();

    private:
        // 读取LSP消息
        std::optional<std::string> ReadMessage();

        // 处理LSP请求 - 返回序列化的响应或空字符串（对于通知）
        void HandleMessage(const std::string& raw_message);

        // 发送LSP响应
        void SendResponse(const std::string& response);

        // 处理不同类型的消息
        void HandleRequest(const protocol::RequestMessage& request);
        void HandleNotification(const protocol::NotificationMessage& notification);
        void HandleResponse(const protocol::ResponseMessage& response);

        // 生命周期事件处理
        void OnLifecycleEvent(provider::ServerLifecycleEvent event);

        // 判断是否需要同步处理
        bool RequiresSyncProcessing(const std::string& method) const;

        // 检查是否可以处理请求
        bool CanProcessRequest(const std::string& method) const;

        // 处理取消请求
        void HandleCancelRequest(const protocol::NotificationMessage& notification);

    private:
        void InitializeCoreServices();
        void InitializeExtensionServices();
        void SendError(const protocol::RequestMessage& request, protocol::ErrorCodes code, const std::string& message);
        void SendStateError(const protocol::RequestMessage& request);

    private:
        RequestDispatcher dispatcher_;
        scheduler::AsyncExecutor async_executor_;
        service::Registry service_registry_;

        std::atomic<bool> is_initialized_ = false;
        std::atomic<bool> is_shutting_down_ = false;
        std::mutex output_mutex_;
    };
}
