
# telm.py
import re
import json

class DynamicToolELM:
    def __init__(self, tools_list):
        self.tools = tools_list
        self.last_normalized_text = ""

    def call_tool_elm(self, raw_text):
        print('telm: call_tool_smart')
        raw_text = raw_text.strip()
        
        # --- NORMALISATION POUR FINE-TUNING ---
        
        # 1. Pattern global incluant les parenthèses ( )
        # On capture : [ ], < >, * *, ( )
        pattern_strict = r"[[<*(](\w+[\w-]*)\s*[:=]\s*['\"]?(.*?)['\"]?[]>*)]"
        
        def normalize(match):
            func_name = match.group(1).strip()
            # Remplacement des tirets par des underscores dans le nom de la fonction
            func_name = func_name.replace("-", "_")
            prompt_content = match.group(2).strip()
            # Retourne le format standard [action: prompt]
            return f"[{func_name}: {prompt_content}]"
        
        # On crée la version normalisée (indispensable pour le fine-tuning)
        normalized_raw_text = re.sub(pattern_strict, normalize, raw_text)
        self.last_normalized_text = normalized_raw_text

        # --- RECHERCHE DES TOOLS (sur le texte normalisé) ---
        new_pattern = r"\[(\w+)\s*:\s*(.*?)\]"
        matches = list(re.finditer(new_pattern, normalized_raw_text))
        
        if matches:
            tools = []
            seen_calls = set()
            for m in matches:
                func_name = m.group(1)
                prompt_content = m.group(2).strip()
                
                if (func_name, prompt_content) not in seen_calls:
                    seen_calls.add((func_name, prompt_content))
                    tools.append({
                        "function": func_name, 
                        "args": {"prompt_sup": prompt_content}
                    })

            # Texte propre pour l'affichage (sans les balises)
            clean_text = re.sub(new_pattern, "", normalized_raw_text).strip()

            if len(tools) > 1:
                print(f'multi tool ({len(tools)})')
                
                for tool in tools:
                    print(tool)
                    
                return {
                    "type": "multi-tool",
                    "results": tools,
                    "text_only": clean_text
                }
            elif len(tools) == 1:
                print('single tool')
                print(tools)
                return {
                    "type": "tool",
                    "function": tools[0]["function"],
                    "args": tools[0]["args"],
                    "text_only": clean_text
                }

        # --- TEST 3 : FALLBACK ---
        return {
            "type": "text",
            "text_only": raw_text
        }



from tools import *

tools_legacy = [
  {
    "name": "web_search",
    "description": "Performs an internet search via DuckDuckGo to retrieve recent information and news.",
    "parameters": {
      "type": "object",
      "properties": {
        "query": {
          "type": "string",
          "description": "The search query or keywords to look up."
        }
      },
      "required": ["query"]
    }
  },
  {
    "name": "get_weather",
    "description": "Retrieves the current weather conditions for a specific city.",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "The name of the city (e.g., Paris, Tokyo)."
        }
      },
      "required": ["city"]
    }
  },
  {
    "name": "safe_calculator",
    "description": "Evaluates complex mathematical expressions securely.",
    "parameters": {
      "type": "object",
      "properties": {
        "expression": {
          "type": "string",
          "description": "The mathematical expression to solve (e.g., sqrt(144) + 2 * pi)."
        }
      },
      "required": ["expression"]
    }
  }
]


