from typing import List, Dict, Any, Optional

from src.models import Tool, ToolPreset, BiasProfile


class ToolBiasEngine:
 def apply_semantic_nudges(self, tool_definitions: List[Dict[str, Any]], preset: ToolPreset) -> List[Dict[str, Any]]:
  """
  [C: tests/test_tool_bias.py:test_apply_semantic_nudges, tests/test_tool_bias.py:test_parameter_bias_nudging]
  """
  weight_map = {
   5: "[HIGH PRIORITY] ",
   4: "[PREFERRED] ",
   2: "[NOT RECOMMENDED] ",
   1: "[LOW PRIORITY] "
  }
  
  preset_tools: Dict[str, Tool] = {}
  for cat_tools in preset.categories.values():
   for t in cat_tools:
    if isinstance(t, Tool):
     preset_tools[t.name] = t
  
  for defn in tool_definitions:
   name = defn.get("name")
   if name in preset_tools:
    tool = preset_tools[name]
    prefix = weight_map.get(tool.weight, "")
    if prefix:
     defn["description"] = prefix + defn.get("description", "")
    
    if tool.parameter_bias:
     params = defn.get("parameters") or defn.get("input_schema")
     if params and "properties" in params:
      props = params["properties"]
      for p_name, bias in tool.parameter_bias.items():
       if p_name in props:
        p_desc = props[p_name].get("description", "")
        props[p_name]["description"] = f"[{bias}] {p_desc}".strip()
  
  return tool_definitions

 def generate_tooling_strategy(self, preset: ToolPreset, global_bias: BiasProfile) -> str:
  """
  [C: tests/test_tool_bias.py:test_generate_tooling_strategy]
  """
  lines = ["### Tooling Strategy"]
  
  preferred = []
  low_priority = []
  for cat_tools in preset.categories.values():
   for t in cat_tools:
    if not isinstance(t, Tool): continue
    if   t.weight >= 5: preferred.append(f"{t.name} [HIGH PRIORITY]")
    elif t.weight == 4: preferred.append(f"{t.name} [PREFERRED]")
    elif t.weight == 2: low_priority.append(f"{t.name} [NOT RECOMMENDED]")
    elif t.weight <= 1: low_priority.append(f"{t.name} [LOW PRIORITY]")
  
  if preferred:    lines.append(f"Preferred tools: {', '.join(preferred)}.")
  if low_priority: lines.append(f"Low-priority tools: {', '.join(low_priority)}.")
  
  if global_bias.category_multipliers:
   lines.append("Category focus multipliers:")
   for cat, mult in global_bias.category_multipliers.items():
    lines.append(f"- {cat}: {mult}x")
    
  return "\n\n".join(lines)
