import requests
from typing import List, Any

from alayaflow.clients.alayamem.base_client import BaseAlayaMemClient


class HttpAlayaMemClient(BaseAlayaMemClient):

    def __init__(self, base_url: str):
        """Initialize the HTTP client with base URL"""
        self.base_url = base_url.rstrip('/')

    def query_file(self, user_id, message, limit=10, use_query_params=False):
        """ 查询文件内容 - POST 请求 """
        query_content = self._msg_content(message)
        params = {
                "query": query_content,
                "user_id": user_id,
                "limit": limit
            }   
        return self._post_with_params("/memory/query_file", params)
   

    def commit_turn(self, session_id, user_text, assistant_text, user_id=None, window_size=10):
        """ 提交多轮对话记录 - POST 请求 """
        payload = {
            "session_id": session_id,
            "user_text": user_text,
            "assistant_text": assistant_text,
            "window_size": window_size
        }
        if user_id:
            payload["user_id"] = user_id
        return self._post("/memory/commit_turn", payload)

    def turns(self, session_id, user_id=None, limit=10):
        """ 查询对话历史记录 - GET 请求 """
        params = {
            "session_id": session_id,
            "limit": limit
        }
        if user_id:
            params["user_id"] = user_id
        return self._get("/memory/turns", params)

    def summary(self, session_id, user_id=None):
        """ 查询会话摘要 - GET 请求 """
        params = {
            "session_id": session_id,
        }
        if user_id:
            params["user_id"] = user_id
        return self._get("/memory/summary", params)

    def profile(self, user_id):
        """ 查询用户画像 - GET 请求 """
        return self._get("/memory/profile", {
            "user_id": user_id,
        })



    # ---------- 私有辅助方法 ----------
    def _get(self, path: str, params: dict):
        """发送 GET 请求，参数作为 query string"""
        resp = requests.get(f"{self.base_url}{path}", params=params)
        resp.raise_for_status()
        return resp.json()

    def _post(self, path: str, payload: dict):
        """发送 POST 请求，参数作为 JSON Body"""
        resp = requests.post(f"{self.base_url}{path}", json=payload)
        resp.raise_for_status()
        return resp.json()

    def _post_with_params(self, path: str, params: dict):
        """发送 POST 请求，参数作为 Query Parameters"""
        resp = requests.post(f"{self.base_url}{path}", params=params)
        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)
