"""
Search tool implementation for simulating internet searches
"""

import asyncio
import time
import random
from typing import Dict, List, Any, Optional
import os

from langchain_text_splitters import RecursiveCharacterTextSplitter
import requests

from meta_researcher.tool.tools.search_engine import Retriever, SearchEngine
from meta_researcher.tool.tools.search_engine.base_search import SearchConfig
from meta_researcher.tool.tools.search_engine.website_crawler.simple_crawler import SimpleContentFetch
from meta_researcher.tool.base import BaseTool

# from txtai.embeddings import Embeddings
import json

class ReflectTool(BaseTool):
    name = "Reflect"
    description = f"""Process Reflection Tool. It can reflect on the currently collected information, identify information gaps, and supplement information. The specific reflection requirements are as follows:
    1. The process reflection stage is indispensable. After each step of the task plan is executed, it is necessary to reflect on whether there is any missing information in the current step.
    2. Never be satisfied with the minimum amount of information. Unless the strictest standard of contextual sufficiency is met, it is default to collect more information.
    """
    parameters = {
        "type": "object",
        "properties": {
            "reflect": {
                "type": "string", 
                "description": "The specific content of process reflection requires a comprehensive reflection on the collected information and identification of information gaps.", 
                "examples": ["I have collected the configuration information and price information of the Xiaomi YU7, but the size information of the Xiaomi YU7 is missing from the configuration details. It is necessary to continue the search to supplement the body size information of the Xiaomi YU7."],
            }
        },
        "required": ["reflect"]
    }

    def __init__(self):
        super().__init__()
        print("[DEBUG] EMBEDDINGS LOADING")
    
    def execute(self, args: Dict) -> str:
        """
        Execute search query
        
        Args:
            args: Tool parameters, containing:
                - "query": search query string
                - "limit": optional int to limit number of results
            
        Returns:
            Formatted search results
        """
        pass
    
    def batch_execute(self, args_list: List[Dict]) -> List[str]:
        try:
            reflects = [x["reflect"] for x in args_list]
            return [{"content": "<reflect>\n" + str(content) + "\n</reflect>", "success": True} for content in reflects]
        except Exception as e:
            return [{"content": str(e), "success": False} for _ in args_list]
    
    def calculate_reward(self, args: Dict, result: str) -> float:
        """
        Calculate reward for search action
        
        Args:
            args: Tool parameters
            result: Tool execution result
            
        Returns:
            Reward value
        """
        # valid tool call
        if "results" in result:
            return 0.1
        else:
            return 0.0