import os
import sys
import logging
from typing import Dict, List, Any

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

project_root = "./futuremind"
if project_root not in sys.path:
    sys.path.insert(0, project_root)
    logger.info(f"Added to PYTHONPATH: {project_root}")

try:
    from futuremind.tool.base import BaseTool
    from futuremind.tool.tools.llm_infer.llminfer_tool import get_infer_handler
    from futuremind.tool.tools.mindset.search_mindpattern import Description, Requirement

except ImportError as e:
    logger.error(f"Import failed: {e}")
    raise

try:
    infer_handler = get_infer_handler(config_path="../llm_infer/config", config_name="llm_config")
except Exception as e:
    logger.error(f"Failed to initialize handlers: {e}")
    raise

class FutureMind(BaseTool):
    name = "futuremind"
    description = Description
    parameters = {
        "type": "object",
        "properties": {
            "query": {"type": "string", "description": "A query for which problem analysis and information retrieval (search) strategy analysis are required"}
        },
        "required": ["query"]
    }

    def __init__(self):
        super().__init__()

    def execute(self, args: Dict[str, str]) -> Dict[str, Any]:
        try:
            query = args.get("query")
            query = str(Requirement)+str("query is: ")+str(query )+str("output: ")
            if not query:
                return {"content": "Empty query provided.", "success": False}

            assistant_input = ""
            result = infer_handler.call_qwen_model(query, assistant_input)

            if result and "reply" in result:
                return {"content": result["reply"], "success": True}
            else:
                return {"content": "No reply returned from model.", "success": True}

        except Exception as e:
            logger.exception("Error during inference execution.")
            return {"content": f"执行失败: {str(e)}", "success": False}

    def batch_execute(self, args_list: List[Dict[str, str]]) -> List[Dict[str, Any]]:
        try:
            queries = [arg.get("query") for arg in args_list]
            if not all(queries):
                return [{"content": "Invalid query", "success": False} for _ in args_list]
            queries_update = []
            for query in queries:
                query_update = str(Requirement)+str("query is: ")+str(query )+str("output: ")
                queries_update.append(query_update)
            assistant_input = ""
            batch_results = infer_handler.batch_call_qwen_model(queries_update, assistant_input)

            results = []
            for result in batch_results:
                if result and "reply" in result:
                    results.append({"content": result["reply"], "success": True})
                else:
                    results.append({"content": "No reply returned from model.", "success": True})

            return results

        except Exception as e:
            logger.exception("Error during batch inference execution.")
            return [{"content": f"Execute Fail: {str(e)}", "success": False} for _ in args_list]

if __name__ == "__main__":
    furturemind = FutureMind()
    query = "The weapon that the FM 24/29 light machine gun was derived from was manufactured in which country?"
    single_query = {"query": query}
    result = furturemind.execute(single_query)
    print(result["content"])
