#!/usr/bin/env python3

from atexit import register
import os
import sys
import logging

import asyncio
from langchain.memory import ConversationBufferWindowMemory
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from pydantic import SecretStr

import json
from pathlib import Path

# 获取当前脚本的路径（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 tools.core.common_functions import read_json_file
# 配置日志记录器
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


class MCP_Clients:

    def __init__(self):
        """
        初始化MCP_Clients
        """
        self.multi_server_mcp_client = None

    def parse_mcp_client_config(self,mcp_clients_config_json_file:str):
        """
        读取mcp_client_config的JSON文件并返回解析后的数据
        
        参数:
            mcp_clients_config_json_file: mcp_clients配置信息的JSON文件的路径
            
        返回:
            解析后的JSON数据（通常是字典或列表），如果出错则返回None
        """
        try:
            # 使用with语句打开文件，确保文件会被正确关闭
            with open(mcp_clients_config_json_file, 'r', encoding='utf-8') as file:
                # 加载并解析JSON数据
                json_data = json.load(file)
                print(f"成功读取JSON文件: {mcp_clients_config_json_file}")
                return json_data
                
        except FileNotFoundError:
            print(f"错误: 找不到文件 '{mcp_clients_config_json_file}'")
        except json.JSONDecodeError:
            print(f"错误: 文件 '{mcp_clients_config_json_file}' 不是有效的JSON格式")
        except PermissionError:
            print(f"错误: 没有权限读取文件 '{mcp_clients_config_json_file}'")
        except Exception as e:
            print(f"读取JSON文件时发生错误: {str(e)}")
        
        return None


    def register_mcp_client(self,mcp_clients_config_json):
        """
        注册具体的mcp_client

        参数:
            mcp_clients_config_json: mcp_clients json格式的配置信息
            
        返回:
            注册成功返回True，失败返回False
        """
        mcp_clients_len = len(mcp_clients_config_json)
        success_register_count = 0
        for client_config in mcp_clients_config_json:
            mcp_client_key_name = list(client_config.keys())[0]
            if "MultiServerMCPClient" == mcp_client_key_name:
                self.multi_server_mcp_client = MultiServerMCPClient(client_config[mcp_client_key_name])
                
                if self.multi_server_mcp_client:
                    logger.info("MultiServerMCPClient register success!")
                    success_register_count=success_register_count + 1
            else:
                logger.info("mcp_client_key_name is not known!")
        return (success_register_count,mcp_clients_len)
        

async def main():
    mcp_clients_config_json_file = "/home/ubuntu/Workspace/Projects/VLM_VLA/UAV_AI/src/Model/AI_Agent/tools/mcp_clients_config.json"
    mcp_client = MCP_Clients()
    mcp_client_config_json = mcp_client.parse_mcp_client_config(mcp_clients_config_json_file)
    if not mcp_client_config_json:
        logger.error("no json data.")
    (sucess_register_count,clients_len) =  mcp_client.register_mcp_client(mcp_client_config_json)




if __name__ == "__main__":
    
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n👋 程序已退出")
    except Exception as e:
        print(f"❌ 程序异常退出: {e}")
    
