"""AI Chat API module (SSE streaming)."""

import json


class ChatAPI:
    """Access the AI chat system (advanced tier).

    Available via ``client.chat``.
    """

    def __init__(self, client):
        self._client = client
        self._request = client._request

    def stream(self, message: str, session_id: str = None,
               context: dict = None, timeout: int = 120):
        """Send a chat message and iterate over streamed tokens (SSE).

        Args:
            message: User message.
            session_id: Session ID for continuation.
            context: Context dict (e.g. current stock).
            timeout: Request timeout (default 120s).

        Yields:
            dict: Parsed SSE event data. Each dict has a ``type`` key:
                - ``{"type": "token", "content": "..."}`` — a text token
                - ``{"type": "done", "session_id": "..."}`` — end of stream

        Example::

            for event in client.chat.stream("分析平安银行"):
                if event["type"] == "token":
                    print(event["content"], end="", flush=True)
                elif event["type"] == "done":
                    print()
        """
        body = {"message": message}
        if session_id:
            body["session_id"] = session_id
        if context:
            body["context"] = context

        resp = self._request(
            "POST", "/api/chat/stream",
            data=body, timeout=timeout, stream=True,
        )

        for line in resp.iter_lines(decode_unicode=True):
            if not line or not line.startswith("data: "):
                continue
            payload = line[6:]  # strip "data: "
            try:
                yield json.loads(payload)
            except json.JSONDecodeError:
                continue

    def send(self, message: str, session_id: str = None,
             context: dict = None, timeout: int = 120) -> str:
        """Send a chat message and return the full text response.

        Convenience wrapper around :meth:`stream` that collects all tokens.

        Args:
            message: User message.
            session_id: Session ID for continuation.
            context: Context dict.
            timeout: Request timeout.

        Returns:
            The complete response text.
        """
        tokens = []
        for event in self.stream(message, session_id, context, timeout):
            if event.get("type") == "token":
                tokens.append(event.get("content", ""))
        return "".join(tokens)

    def sessions(self) -> dict:
        """List chat sessions for the current user."""
        return self._request("GET", "/api/chat/sessions")

    def session_detail(self, session_id: str) -> dict:
        """Get details of a specific chat session.

        Args:
            session_id: Session ID.
        """
        return self._request("GET", f"/api/chat/sessions/{session_id}")

    def delete_session(self, session_id: str) -> dict:
        """Delete a chat session.

        Args:
            session_id: Session ID.
        """
        return self._request("DELETE", f"/api/chat/sessions/{session_id}")
