"""
Helper utilities for working with sessions via the refactored backend.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

from .client import PopingClient


def _client(client: Optional[PopingClient]) -> PopingClient:
    if client:
        return client
    from . import get_client  # lazy import to avoid cycles

    return get_client()


def create(*, client: Optional[PopingClient] = None, project_id: Optional[str] = None, end_user_id: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None, session_id: Optional[str] = None) -> Dict[str, Any]:
    c = _client(client)
    payload = {
        "project_id": project_id,
        "end_user_id": end_user_id,
        "metadata": metadata or {},
        "session_id": session_id,
    }
    return c.create_session(**{k: v for k, v in payload.items() if v is not None or k == "metadata"})


def list(*, client: Optional[PopingClient] = None, project_id: Optional[str] = None, end_user_id: Optional[str] = None) -> List[Dict[str, Any]]:
    c = _client(client)
    params = {"project_id": project_id, "end_user_id": end_user_id}
    return c.list_sessions(**{k: v for k, v in params.items() if v is not None})


def get(session_id: str, *, client: Optional[PopingClient] = None, project_id: Optional[str] = None, end_user_id: Optional[str] = None) -> Dict[str, Any]:
    c = _client(client)
    return c.get_session(session_id, project_id=project_id, end_user_id=end_user_id)


def append_message(agent_id: str, session_id: str, *, role: str, content: str, client: Optional[PopingClient] = None, project_id: Optional[str] = None, end_user_id: Optional[str] = None) -> Dict[str, Any]:
    """
    Convenience wrapper for /agents/{agent_id}/sessions/{session_id}/message.
    """
    c = _client(client)
    return c.append_session_message(agent_id, session_id, role=role, content=content, project_id=project_id, end_user_id=end_user_id)


def stream_chat(agent_id: str, *, message: str, client: Optional[PopingClient] = None, session_id: Optional[str] = None, project_id: Optional[str] = None, end_user_id: Optional[str] = None):
    """
    Stream chat events (NDJSON) for a given agent. Yields dict events.
    """
    c = _client(client)
    return c.chat_stream_events(agent_id, message=message, session_id=session_id, project_id=project_id, end_user_id=end_user_id)


__all__ = ["create", "list", "get"]
