"""
QALRON SDK - AgentClient for communicating with QALRON server
Uses the server's /api/v1/agents/chat endpoint for AI-powered responses
"""
import requests


class AgentClient:
    """Client for communicating with QALRON agent system"""
    
    def __init__(self, api_key: str, server_url: str = "http://localhost:8000"):
        """
        Initialize the QALRON Agent Client
        
        Args:
            api_key: Your QALRON API key
            server_url: Server URL (default: localhost:8000)
        """
        self.api_key = api_key
        self.server_url = server_url.rstrip('/')
        self.agent_id = None
        self.messages = []
        
    def set_agent(self, agent_id: str):
        """Set the current agent identity"""
        self.agent_id = agent_id
        return self
    
    def chat(self, agent: str, message: str) -> str:
        """
        Send a message to an agent and get a response
        
        Args:
            agent: Agent name (coordinator, researcher, analyst, writer, reviewer)
            message: Message to send
            
        Returns:
            Agent's response text
        """
        try:
            response = requests.post(
                f"{self.server_url}/api/v1/agents/chat",
                json={"agent": agent, "message": message},
                headers={"X-API-Key": self.api_key},
                timeout=30
            )
            
            if response.status_code == 200:
                data = response.json()
                return data.get("response", "No response")
            else:
                return f"Error: {response.status_code}"
        except Exception as e:
            return f"Connection error: {e}"
    
    def send_message(self, to_agent: str, content: str, metadata: dict = None):
        """Send a message to another agent (tracked)"""
        self.messages.append({
            "to": to_agent,
            "content": content,
            "metadata": metadata or {}
        })
        # Actually call the agent
        return self.chat(to_agent, content)
    
    def log_event(self, event_type: str, data: dict = None):
        """Log an event to the system"""
        print(f"[QALRON] Event: {event_type} - {data}")
        return True
