#ifndef SERVICES_ASSISTANT_MODEL_INFERENCE_H
#define SERVICES_ASSISTANT_MODEL_INFERENCE_H

#include <future>
#include <mutex>

#include "assistant/sessionbase.h"
#include "engineselector/engineselector.h"
#include "modelinferenceinterface.h"

class ModelInference : public ModelInferenceInterface {
public:
    ModelInference() = default;

    ~ModelInference() override;

    std::future<bool> callChatModelInference(const std::string &modelInput) override;

    DialogueData::CallSuccessIdentifier callIntentionModelInference(const std::string &modelInput) override;

    std::string intentModelName() override;

    void initChatEngine(const std::shared_ptr<assistant::TextGenerationEngine> &nlpEngine,
                        EngineSelector &engineSelector_, bool isDefaultMode);

    void initIntentEngine(const std::shared_ptr<assistant::TextGenerationEngine> &nlpEngine);

    int getCurrentModelMaxTokens() override;
    bool isCloudModel() override;
    bool isChatModelConfigured() override;
    bool isIntentModelNotLoaded() override;

    void stopChat() override;

private:
    void handleChatResult(const ai_engine::gen_ai::nlp::TextGenerationResult &result);

    bool handleNetworkDisconnection(
        const std::string &modelInput,
        const std::function<void(const ai_engine::gen_ai::nlp::TextGenerationResult &result)> &callback);

    void waitForChatEngineInited();
    void waitForIntentEngineInited();

    // 用于在初始化方法中等待之前的初始化完成
    void waitForChatEngineInitInternal();
    void waitForIntentEngineInitInternal();

private:
    std::shared_ptr<assistant::TextGenerationEngine> chatEngine_;
    std::shared_ptr<assistant::TextGenerationEngine> intentEngine_;
    std::string intentReplyCache_;
    std::string intentResult_;
    std::string intentModelName_;
    std::atomic_int intentModelCurrentErrorCode_;
    EngineSelector *engineSelector_{nullptr};
    std::atomic_bool isChatEngineInited_{false};
    std::atomic_bool isDefaultMode_{true};
    std::future<void> chatEngineInitFuture_;
    std::future<void> intentEngineInitFuture_;
    std::mutex chatEngineInitMutex_;    // 保护聊天引擎初始化过程
    std::mutex intentEngineInitMutex_;  // 保护意图引擎初始化过程
};

#endif  // SERVICES_ASSISTANT_MODEL_INFERENCE_H
