/*
 * Copyright 2024 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
#pragma once

#include <filesystem>
#include <iostream>
#include <opencv2/opencv.hpp>
#ifdef TRITON_CLIENT
#include <triton/client/http_client.h>
#endif
#include <dirent.h>
#include <chrono>
#include <fstream>
#include <kylin-ai/ai-engine/aiengine.h>
#include <kylin-ai/ai-engine/textrecognitionengine.h>
#include "base64_transformer.h"

#ifdef TRITON_CLIENT
namespace tc = triton::client;
#endif

namespace vision = ai_engine::core_ai::vision;
#ifdef TRITON_CLIENT
#define FAIL_IF_ERR(X, MSG)                                                    \
    {                                                                          \
        tc::Error err = (X);                                                   \
        if (!err.IsOk()) {                                                     \
            std::cerr << "error: " << (MSG) << ": " << err << std::endl;       \
            exit(1);                                                           \
        }                                                                      \
    }
#endif

class OcrTritonClient {
public:
    OcrTritonClient(const std::string &url);
    vision::TextRecognitionResult OcrRequestByPath(std::string ImagePath);
    vision::TextRecognitionResult OcrRequestByImage(cv::Mat Image);
    vision::TextRecognitionResult OcrRequestByBase64(const char *ImageData);
#ifdef TRITON_CLIENT
    tc::Error LoadModel();
    tc::Error RemoveModel();
#endif
    std::string GetConfigValue(const char *key, const char *engine);

private:
#ifdef TRITON_CLIENT
    std::unique_ptr<tc::InferenceServerHttpClient>
        client_; // Triton client as a member variable
#endif
    std::string model_name_;
};
