#ifndef VISION_TEXTRECOGNITION_H
#define VISION_TEXTRECOGNITION_H

#include <kylin-ai/aiengine.h>

#include <atomic>
#include <filesystem>
#include <memory>
#include <string>

#include "concurrentqueue/blockingconcurrentqueue.h"
#include "coreaivisionmodelconfig.h"
#include "corevisionserviceglue.h"
#include "taskmanager/taskrunner.h"

struct PixelPoint {
    int x;
    int y;
};

struct TextLine {
    std::string text;
    std::vector<PixelPoint> points;
    float conf;
};

struct TextRecognitionResult {
    std::string allText;
    std::vector<TextLine> lines;
    int errorCode;
    std::string errorMessage;
};

class TextRecognition : public std::enable_shared_from_this<TextRecognition> {
public:
    using RecognitionResultCallback = std::function<void(const TextRecognitionResult&)>;

    explicit TextRecognition(std::unique_ptr<ai_engine::core_ai::vision::AbstractTextRecognitionEngine> visionEngine);

    ~TextRecognition();

    bool init();

    void setTextRecognitionResultCallback(const RecognitionResultCallback& callback);

    void recognizeTextFromImageFile(const std::string& imageFilePath, RecognitionResultCallback resultCallback);

    void recognizeTextFromImageData(const std::string& imageData, RecognitionResultCallback resultCallback);

private:
    struct TextRecognitionRequest {
        enum Type { Unknown, ImagePath, Base64Data };
        Type type{Unknown};
        std::filesystem::path imagePath{};
        std::string base64Data{};
        RecognitionResultCallback resultCallback{nullptr};
    };

    TextRecognitionRequest generateTextRecognitionRequestWithFilePath(const std::string& imageFilePath,
                                                                      RecognitionResultCallback resultCallback);

    TextRecognitionRequest generateTextRecognitionRequestWithBase64Data(const std::string& base64Data,
                                                                        RecognitionResultCallback resultCallback);

private:
    std::shared_ptr<TextRecognition> getSharedObject() { return shared_from_this(); }

    TextRecognitionResult makeResultFromEngineError(const ai_engine::EngineError& error) const;

    void callTextRecognitionResultCallback(const TextRecognitionResult& result) const;

    void textRecogniseAsync();

    void textRecognizeTask();

private:
    std::unique_ptr<ai_engine::core_ai::vision::AbstractTextRecognitionEngine> visionEngine_{nullptr};
    RecognitionResultCallback recognitionResultCallback_{nullptr};
    moodycamel::BlockingConcurrentQueue<TextRecognitionRequest> textRecognitionRequests_{};
    TextRecognitionRequest currentRequest_{};
    std::atomic<task::TaskId> taskId_{task::INVALID_TASK_ID};
};

#endif