#!/usr/bin/env python3
import os
import sys
import io

from typing import List, Dict, Any, Optional, Tuple

# from langchain.agents import initialize_agent, AgentType
# from langchain.tools import BaseTool, Tool
# from langchain.llms import LlamaCpp
# from langchain.callbacks.manager import CallbackManager
# from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
# from langchain.prompts import PromptTemplate
# from langchain.chains import LLMChain
# import magic  # 用于识别文件类型（辅助文件搜索工具）

# from langchain.vectorstores import Chroma
# from langchain.embeddings import LlamaCppEmbeddings
# from langchain.text_splitter import RecursiveCharacterTextSplitter
# from langchain.document_loaders import (
#     TextLoader, UnstructuredFileLoader, PDFMinerLoader,
#     UnstructuredMarkdownLoader, Docx2txtLoader
# )
# from langchain.chains import RetrievalQA
# from langchain.memory import ConversationBufferWindowMemory
# from langchain.prompts import PromptTemplate
# from langchain.schema import HumanMessage, AIMessage

# from llama_cpp import Llama, LlamaGrammar

import json
import logging
from pathlib import Path

# import argparse
# import base64

import time
# from fastapi import FastAPI, HTTPException, APIRouter, Path
# from fastapi.responses import JSONResponse

# from fastapi_utils.cbv import cbv
# from fastapi_utils.inferring_router import InferringRouter

# from pydantic import BaseModel
# from PIL import Image
# import numpy as np

# 获取当前脚本的路径（Path 对象）
current_script = Path(__file__).resolve()
# 向上两级找到项目根目录（根据实际结构调整层级）
project_root = current_script.parents[1]  # parents[0] 是当前目录，parents[1] 是父目录，以此类推

print("project_root: ",project_root)

#添加到搜索路径
sys.path.append(str(project_root))

#查看系统环境
print("sys path:",sys.path)


from models.models_server import Models_Server
from models.models_client import Models_Client

# 配置日志记录器
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)

#模型管理器
class Models_Mag:
    """
    模型管理器，包含模型推理server和模型推理client
    """

    def __init__(self):
        #定义模型管理器的server和client
        self.models_server = None
        self.models_client = None
        self.models_interface= None

    def init_model_server(self,model_config:Optional[dict[str,Any]]):
        """
        初始化模型推理server

        参数：

        返回：
            初始化成功返回True,初始化失败返回False
        """

        try:

            self.models_server = Models_Server(model_config["models_server"])
            return True
        except Exception as e:
            logger.error(f"models_server初始化失败: {str(e)}")
            return False
        
    def init_model_client(self,model_config:Optional[dict[str,Any]]):
        """
        初始化模型推理client

        参数：

        返回：
            初始化成功返回True,初始化失败返回False
        """

        try:

            self.models_client = Models_Client(model_config["models_client"]["server_url"])
            return True
        except Exception as e:
            logger.error(f"models_server初始化失败: {str(e)}")
            return False
    
    def init_model_interface(self,
                             model_config:Optional[dict[str,Any]],
                             is_model_server:bool = False):
        """
        初始化模型推理client

        参数：

        返回：
            初始化成功返回True,初始化失败返回False
        """
        try:
            if is_model_server:
                self.init_model_server(model_config=model_config)
                self.models_interface = self.models_server
            else:
                self.init_model_client(model_config=model_config)
                self.models_interface = self.models_client
            return True
        except Exception as e:
            logger.error(f"models_server初始化失败: {str(e)}")
            return False

        
if __name__=="__main__":

    from tools.core.common_functions import read_json_file
    from tools.data_process.image_process.image_process import decode_base64_image, preprocess_image, PIL_image_to_base64

    
