using System;
using System.IO;
using System.Drawing;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Linq;
using PaddleOCRSharp;

namespace CtrEditor.Services
{
    // Clase auxiliar para gestionar PaddleOCR
    public static class PaddleOCRManager
    {
        private static PaddleOCREngine _engine;
        private static bool _initialized = false;
        private static readonly object _lockObj = new object();

        public static PaddleOCREngine GetEngine()
        {
            if (!_initialized)
            {
                lock (_lockObj)
                {
                    if (!_initialized)
                    {
                        InitializeEngine();
                        _initialized = true;
                    }
                }
            }
            return _engine;
        }

        private static void InitializeEngine()
        {
            try
            {
                string baseDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "paddleocr");

                OCRModelConfig config = new OCRModelConfig
                {
                    // Rutas a modelos de inferencia
                    det_infer = Path.Combine(baseDir, "det", "inference"),
                    cls_infer = Path.Combine(baseDir, "cls", "inference"),
                    rec_infer = Path.Combine(baseDir, "rec", "inference"),
                    keys = Path.Combine(baseDir, "keys", "ppocr_keys.txt")
                };

                OCRParameter parameter = new OCRParameter
                {
                    // Configurar parámetros de OCR
                    use_angle_cls = true,
                    cls_thresh = 0.9f,
                    det_db_thresh = 0.3f,
                    det_db_box_thresh = 0.6f,
                    rec_batch_num = 6,
                    rec_img_h = 48,
                    enable_mkldnn = true,
                    use_gpu = false,
                    cpu_math_library_num_threads = Environment.ProcessorCount
                };

                _engine = new PaddleOCREngine(config, parameter);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"Error al inicializar PaddleOCR: {ex.Message}");
                // Fallback - inicializar con configuración predeterminada
                _engine = new PaddleOCREngine();
            }
        }

        public static void Cleanup()
        {
            lock (_lockObj)
            {
                if (_initialized && _engine != null)
                {
                    _engine.Dispose();
                    _engine = null;
                    _initialized = false;
                }
            }
        }
    }
        
}