"""Assistant API client.

Endpoints:
- POST /api/v1/assistants - Create assistant
- GET /api/v1/assistants - List assistants
- GET /api/v1/assistants/{id} - Get assistant info
- DELETE /api/v1/assistants/{id} - Stop assistant
- POST /api/v1/assistants/{id}/messages - Send message
- GET /api/v1/assistants/{id}/messages - Get message history
- GET /api/v1/assistants/{id}/stream - Stream events (SSE)
- POST /api/v1/assistants/{id}/suspend - Suspend assistant
- POST /api/v1/assistants/{id}/resume - Resume assistant
"""

from __future__ import annotations

from collections.abc import AsyncIterator
from typing import Any

from manta_client.api.client import MantaClient, get_client


class AssistantAPI:
    """Assistant API client."""

    def __init__(self, client: MantaClient | None = None):
        self.client = client or get_client()

    async def create_assistant(
        self,
        name: str,
        *,
        system_prompt: str | None = None,
        skill_slugs: list[str] | None = None,
        agents: dict | None = None,
        workspace_id: int | None = None,
        model: str | None = None,
        idle_timeout: int | None = None,
    ) -> dict[str, Any]:
        """Create a new persistent assistant."""
        data: dict[str, Any] = {"name": name}
        if system_prompt:
            data["system_prompt"] = system_prompt
        if skill_slugs:
            data["skill_slugs"] = skill_slugs
        if agents:
            data["agents"] = agents
        if workspace_id is not None:
            data["workspace_id"] = workspace_id
        if model:
            data["model"] = model
        if idle_timeout is not None:
            data["idle_timeout"] = idle_timeout

        return await self.client.post("/api/v1/assistants", data=data)

    async def list_assistants(
        self,
        skip: int = 0,
        limit: int = 100,
        status: str | None = None,
        user_id: str | None = None,
    ) -> dict[str, Any]:
        """List assistants."""
        params: dict[str, Any] = {"skip": skip, "limit": limit}
        if status:
            params["status"] = status
        if user_id:
            params["user_id"] = user_id
        return await self.client.get("/api/v1/assistants", params=params)

    async def get_assistant(self, assistant_id: str) -> dict[str, Any]:
        """Get assistant by ID."""
        return await self.client.get(f"/api/v1/assistants/{assistant_id}")

    async def delete_assistant(self, assistant_id: str) -> bool:
        """Stop and delete an assistant."""
        await self.client.delete(f"/api/v1/assistants/{assistant_id}")
        return True

    async def send_message(self, assistant_id: str, content: str) -> dict[str, Any]:
        """Send a message to the assistant."""
        return await self.client.post(
            f"/api/v1/assistants/{assistant_id}/messages",
            data={"content": content},
        )

    async def get_messages(
        self,
        assistant_id: str,
        skip: int = 0,
        limit: int = 100,
    ) -> dict[str, Any]:
        """Get message history."""
        params: dict[str, Any] = {"skip": skip, "limit": limit}
        return await self.client.get(f"/api/v1/assistants/{assistant_id}/messages", params=params)

    async def stream_assistant(self, assistant_id: str) -> AsyncIterator[dict[str, Any]]:
        """Stream assistant events via SSE."""
        async for event in self.client.stream_sse(f"/api/v1/assistants/{assistant_id}/stream"):
            yield event

    async def suspend_assistant(self, assistant_id: str) -> bool:
        """Suspend assistant (scale to 0)."""
        await self.client.post(f"/api/v1/assistants/{assistant_id}/suspend")
        return True

    async def resume_assistant(self, assistant_id: str) -> bool:
        """Resume assistant (scale to 1)."""
        await self.client.post(f"/api/v1/assistants/{assistant_id}/resume")
        return True


# Singleton API instance
_assistant_api: AssistantAPI | None = None


def get_assistant_api() -> AssistantAPI:
    """Get or create the global Assistant API instance."""
    global _assistant_api
    if _assistant_api is None:
        _assistant_api = AssistantAPI()
    return _assistant_api
