"""Forwards tool calls from Pipecat LLM to agent-service for execution."""

import httpx
import logging

logger = logging.getLogger(__name__)


class ToolHandler:
    def __init__(self, agent_service_url: str, session_id: str, tenant_id: str):
        self.agent_service_url = agent_service_url
        self.session_id = session_id
        self.tenant_id = tenant_id

    async def execute_tool(self, tool_name: str, tool_input: dict) -> dict:
        """Execute a tool call by forwarding to agent-service."""
        try:
            async with httpx.AsyncClient(timeout=60.0) as client:
                resp = await client.post(
                    f"{self.agent_service_url}/api/v1/agent/sessions/{self.session_id}/tool",
                    json={"toolName": tool_name, "input": tool_input},
                    headers={"X-Tenant-Id": self.tenant_id},
                )
                if resp.status_code == 200:
                    return resp.json()
                return {"error": f"Tool execution failed: {resp.status_code}", "output": ""}
        except Exception as e:
            logger.error(f"Tool execution error: {e}")
            return {"error": str(e), "output": ""}
