#ifndef ANSPaddleOCR_H
#define ANSPaddleOCR_H
#pragma once
#include "opencv2/core.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <vector>
#include <atomic>
#include <chrono>
#include <thread>
#include "LabVIEWHeader/extcode.h"
#include "ANSLicense.h"
#include "ANSOCRBase.h"
#include <include/paddleocr.h>

namespace ANSCENTER {

	class ANSOCR_API ANSCPUOCR :public ANSOCRBase {
	public:
		[[nodiscard]] virtual bool Initialize(const std::string& licenseKey, OCRModelConfig modelConfig, const std::string& modelZipFilePath, const std::string& modelZipPassword, int engineMode) override;
		[[nodiscard]] std::vector<ANSCENTER::OCRObject> RunInference(const cv::Mat& input);
		[[nodiscard]] std::vector<ANSCENTER::OCRObject> RunInference(const cv::Mat& input, const std::string &cameraId);
		[[nodiscard]] std::vector<ANSCENTER::OCRObject> RunInference(const cv::Mat& input, const std::vector<cv::Rect>& Bbox);
		[[nodiscard]] std::vector<ANSCENTER::OCRObject> RunInference(const cv::Mat& input, const std::vector<cv::Rect> &Bbox, const std::string& cameraId);
		~ANSCPUOCR();
		[[nodiscard]] bool Destroy();
	private:
		std::unique_ptr<PaddleOCR::PPOCR> ppocr = std::make_unique<PaddleOCR::PPOCR>();
		std::mutex    _mutex;
		std::atomic<bool> _modelLoading{ false };
		cv::Mat _frameBuffer;  // Reusable buffer for color conversion

		// Try to lock _mutex with a timeout for non-recursive mutex
		std::unique_lock<std::mutex> TryLockWithTimeout(
				const char* caller, unsigned int timeoutMs = 5000)
		{
			const auto deadline = std::chrono::steady_clock::now()
								+ std::chrono::milliseconds(timeoutMs);
			std::unique_lock<std::mutex> lk(_mutex, std::defer_lock);
			while (!lk.try_lock()) {
				if (std::chrono::steady_clock::now() >= deadline) {
					_logger.LogWarn(caller,
						"Mutex acquisition timed out after "
						+ std::to_string(timeoutMs) + " ms"
						+ (_modelLoading.load() ? " (model loading in progress)" : ""),
						__FILE__, __LINE__);
					return lk;
				}
				std::this_thread::sleep_for(std::chrono::milliseconds(1));
			}
			return lk;
		}

	};
}
#endif
