import requests
from typing import List, Any

from alayaflow.clients.alayamem.base_client import BaseAlayaMemClient


class HttpAlayaMemClient(BaseAlayaMemClient):
    def __init__(self, base_url: str):
        self.base_url = base_url.rstrip("/")

    def init_session(self, user_id, user_name, agent_name):
        return self._post("/init", {
            "user_id": user_id,
            "user_name": "unknown",
            "agent_name": "unknown",
        })

    def vdb_query(self, messages: List[Any], limit: int,  collection_name: str):
        query_text = self._extract_query(messages)
        return self._post("/vdb/query", {
            "collection_name": collection_name,
            "query_text": query_text,
            "limit": limit,
        })

    def query(self, user_id, message):
        return self._post("/query", {
            "user_id": user_id,
            "question": self._msg_content(message),
        })

    def add_session_messages(self, user_id, messages):
        for msg in messages:
            return self._post("/add_message", {
                                "user_id": user_id,
                                "message": self._msg_content(msg),
                                "is_user": self._is_user(msg),
                                "speaker_name": "unknown",
                            })

    # ---------- private helpers ----------

    def _post(self, path: str, payload: dict):
        resp = requests.post(f"{self.base_url}{path}", json=payload)
        resp.raise_for_status()
        return resp.json()

    def _msg_content(self, msg):
        # 支持字典格式
        if isinstance(msg, dict):
            return msg.get("content", str(msg))
        # 支持对象格式
        return msg.content if hasattr(msg, "content") else str(msg)

    def _extract_query(self, messages):
        if not messages:
            return ""
        last_msg = messages[-1]
        return self._msg_content(last_msg)

    def _is_user(self, msg):
        if isinstance(msg, dict):
            return msg.get("role", "").lower() == "user"
        return "Human" in msg.__class__.__name__ or "User" in msg.__class__.__name__