/*
 * 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/>.
 */

#include <kylin-ai/ai-engine/aiengine.h>
#include <nlohmann/json.hpp>
#include "ocr_triton_client/client.h"
#include "ondevicevisioncapabilityengine.h"

namespace ai_engine::core_ai::vision {

std::condition_variable cv_;
bool isProcessing = false;
OndeviceVisionTextRecognitionEngine::OndeviceVisionTextRecognitionEngine()
    : ocrClient_(new OcrTritonClient("localhost:8000")) {}

OndeviceVisionTextRecognitionEngine::~OndeviceVisionTextRecognitionEngine() {
    delete ocrClient_;
}

void OndeviceVisionTextRecognitionEngine::setTextRecognitionResultCallback(
    TextRecognitionResultCallback callback) {
    if (ocrClient_ == nullptr) {
        return;
    }
    std::lock_guard<std::mutex> callBackLock(callBackMutex_);
    ocrResultCallback_ = std::move(callback);
}
result::AiEngineBaseResult
OndeviceVisionTextRecognitionEngine::recognizeTextFromFile(
    const std::string &imageFilePath) {
    std::unique_lock<std::mutex> lock(ocrMutex_);
    cv_.wait(lock, [this] { return !isProcessing; });
    isProcessing = true;
    lock.unlock(); // 解锁，允许其它线程请求
    result::AiEngineBaseResult error;
    error.success = true;
    TextRecognitionResult res = ocrClient_->OcrRequestByPath(imageFilePath);
    if (!res.success) {
        error.success = false;
        error.error = ai_engine::EngineError(
            (int)VisionEngineErrorCode::ImageFileReadError,
            "[OcrTriton]: failed to Request Ocr by img path.");
    }
    {
        std::lock_guard<std::mutex> callBackLock(callBackMutex_);
        if (ocrResultCallback_ != nullptr) {
            ocrResultCallback_(res);
        }
    }
    lock.lock();
    isProcessing = false;
    cv_.notify_one(); // 唤醒其他线程

    return error;
}

result::AiEngineBaseResult
OndeviceVisionTextRecognitionEngine::recognizeTextFromBase64ImageData(
    const std::string &imageBase64Data) {
    std::unique_lock<std::mutex> lock(ocrMutex_);
    cv_.wait(lock, [this] { return !isProcessing; });
    isProcessing = true;
    lock.unlock(); // 解锁，允许其它线程请求
    result::AiEngineBaseResult error;
    error.success = true;
    TextRecognitionResult res =
        ocrClient_->OcrRequestByBase64(imageBase64Data.c_str());
    if (!res.success) {
        error.success = false;
        error.error = ai_engine::EngineError(
            (int)VisionEngineErrorCode::ImageFileReadError,
            "[OcrTriton]: failed to Request Ocr by base64.");
    }
    {
        std::lock_guard<std::mutex> callBackLock(callBackMutex_);
        if (ocrResultCallback_ != nullptr) {
            ocrResultCallback_(res);
        }
    }
    lock.lock();
    isProcessing = false;
    cv_.notify_one(); // 唤醒其他线程

    return error;
}

result::AiEngineBaseResult OndeviceVisionTextRecognitionEngine::init() {
    result::AiEngineBaseResult error;
    error.success = true;
#ifdef TRITON_CLIENT
    tc::Error err = ocrClient_->LoadModel();
    int errorCode = 0;

    if (err.Message() ==
        "explicit model load / unload is not allowed if polling is enabled")
        errorCode = (int)ai_engine::VisionEngineErrorCode::ModelEarlyLoaded;
    else if (err.Message() == "HTTP client failed: Couldn't connect to server")
        errorCode = (int)ai_engine::VisionEngineErrorCode::FileNotFound;
    if (!err.IsOk()) {
        error.error =
            ai_engine::EngineError((int)errorCode, err.Message().c_str());
        error.success = false;
        return error;
    }
#endif
    return error;
}

result::AiEngineBaseResult OndeviceVisionTextRecognitionEngine::destroy() {
    result::AiEngineBaseResult error;
    error.success = true;
#ifdef TRITON_CLIENT
    tc::Error err = ocrClient_->RemoveModel();

    if (!err.IsOk()) {
        error.error = ai_engine::EngineError(
            (int)ai_engine::VisionEngineErrorCode::OcrModelError,
            err.Message().c_str());
        error.success = false;
        return error;
    }
#endif
    return error;
}

namespace nl = nlohmann;
std::string OndeviceVisionTextRecognitionEngine::modelInfo() const {
    const char *info = R"(
    {
        "vendor": "",
        "models": [
            {
                "name": "vision",
                "subConfig": [],
                "debName": "",
                "is3rdModel": false
            }
        ]
    }
    )";
    return info;
}

} // namespace ai_engine::core_ai::vision