"""AgentKitClient - Python SDK for AgentKit Server"""

from typing import Any

import httpx


class AgentKitClient:
    """Python SDK for AgentKit Server"""

    def __init__(self, base_url: str = "http://localhost:8000"):
        self._base_url = base_url.rstrip("/")
        self._client = httpx.AsyncClient(base_url=self._base_url)

    async def create_agent(
        self, skill_name: str | None = None, config: dict | None = None
    ) -> dict:
        """Create an agent instance"""
        payload: dict[str, Any] = {}
        if skill_name:
            payload["skill_name"] = skill_name
        if config:
            payload["config"] = config
        response = await self._client.post("/api/v1/agents", json=payload)
        response.raise_for_status()
        return response.json()

    async def list_agents(self) -> list[dict]:
        """List all agents"""
        response = await self._client.get("/api/v1/agents")
        response.raise_for_status()
        return response.json()

    async def get_agent(self, name: str) -> dict:
        """Get agent details"""
        response = await self._client.get(f"/api/v1/agents/{name}")
        response.raise_for_status()
        return response.json()

    async def delete_agent(self, name: str) -> None:
        """Delete an agent"""
        response = await self._client.delete(f"/api/v1/agents/{name}")
        response.raise_for_status()

    async def submit_task(
        self,
        input_data: dict,
        skill_name: str | None = None,
        agent_name: str | None = None,
    ) -> dict:
        """Submit a task"""
        payload: dict[str, Any] = {"input_data": input_data}
        if skill_name:
            payload["skill_name"] = skill_name
        if agent_name:
            payload["agent_name"] = agent_name
        response = await self._client.post("/api/v1/tasks", json=payload)
        response.raise_for_status()
        return response.json()

    async def register_skill(self, config: dict) -> dict:
        """Register a skill"""
        response = await self._client.post(
            "/api/v1/skills", json={"config": config}
        )
        response.raise_for_status()
        return response.json()

    async def list_skills(self) -> list[dict]:
        """List all skills"""
        response = await self._client.get("/api/v1/skills")
        response.raise_for_status()
        return response.json()

    async def get_usage(self, agent_name: str | None = None) -> dict:
        """Get LLM usage statistics"""
        params = {}
        if agent_name:
            params["agent_name"] = agent_name
        response = await self._client.get("/api/v1/llm/usage", params=params)
        response.raise_for_status()
        return response.json()

    async def health(self) -> dict:
        """Health check"""
        response = await self._client.get("/api/v1/health")
        response.raise_for_status()
        return response.json()

    async def submit_task_async(
        self,
        input_data: dict,
        skill_name: str | None = None,
        agent_name: str | None = None,
    ) -> dict:
        """Submit a task in async mode"""
        payload: dict[str, Any] = {"input_data": input_data, "mode": "async"}
        if skill_name:
            payload["skill_name"] = skill_name
        if agent_name:
            payload["agent_name"] = agent_name
        response = await self._client.post("/api/v1/tasks", json=payload)
        response.raise_for_status()
        return response.json()

    async def get_task_status(self, task_id: str) -> dict:
        """Get task status"""
        response = await self._client.get(f"/api/v1/tasks/{task_id}")
        response.raise_for_status()
        return response.json()

    async def cancel_task(self, task_id: str) -> dict:
        """Cancel a running task"""
        response = await self._client.post(f"/api/v1/tasks/{task_id}/cancel")
        response.raise_for_status()
        return response.json()

    async def list_tasks(
        self, status: str | None = None, limit: int = 100
    ) -> list[dict]:
        """List tasks"""
        params: dict[str, Any] = {"limit": limit}
        if status:
            params["status"] = status
        response = await self._client.get("/api/v1/tasks", params=params)
        response.raise_for_status()
        return response.json()

    async def stream_task(
        self,
        input_data: dict,
        skill_name: str | None = None,
        agent_name: str | None = None,
    ):
        """Stream task execution events via SSE.

        Yields event dicts with 'event' and 'data' keys.
        """
        payload: dict[str, Any] = {"input_data": input_data}
        if skill_name:
            payload["skill_name"] = skill_name
        if agent_name:
            payload["agent_name"] = agent_name

        async with self._client.stream(
            "POST", "/api/v1/tasks/stream", json=payload
        ) as response:
            response.raise_for_status()
            event_type = ""
            async for line in response.aiter_lines():
                line = line.strip()
                if not line:
                    continue
                if line.startswith("event: "):
                    event_type = line[7:]
                elif line.startswith("data: "):
                    import json as _json
                    data = _json.loads(line[6:])
                    yield {"event": event_type, "data": data}

    async def close(self) -> None:
        """Close the HTTP client"""
        await self._client.aclose()

    async def __aenter__(self) -> "AgentKitClient":
        return self

    async def __aexit__(self, *args) -> None:
        await self.close()
