import sys
import json
import os
import io

# Force UTF-8 for stdout/stderr to avoid encoding issues on Windows
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

# Add project root and src/ to sys.path
project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(project_root)
sys.path.append(os.path.join(project_root, "src"))

try:
 import mcp_client
 import shell_runner
except ImportError:
 print(json.dumps({"error": "Failed to import required modules"}))
 sys.exit(1)

def main() -> None:
 if len(sys.argv) < 2:
  print(json.dumps({"error": "No tool name provided"}))
  sys.exit(1)
 tool_name = sys.argv[1]
 # Read arguments from stdin
 try:
  input_data = sys.stdin.read()
  if input_data:
   tool_input = json.loads(input_data)
  else:
   tool_input = {}
 except json.JSONDecodeError:
  print(json.dumps({"error": "Invalid JSON input"}))
  sys.exit(1)
 try:
  if tool_name == "run_powershell":
   script = tool_input.get("script", "")
   # We use the current directory as base_dir for CLI calls
   result = shell_runner.run_powershell(script, os.getcwd())
  else:
  # mcp_client tools generally resolve paths relative to CWD if not configured.
   mcp_client.configure([], [os.getcwd()])
   result = mcp_client.dispatch(tool_name, tool_input)
   # We print the raw result string as that's what gemini-cli expects.
  print(result)
 except Exception as e:
  print(f"ERROR executing tool {tool_name}: {e}")
  sys.exit(1)

if __name__ == "__main__":
 main()

