"""记忆服务（聊天记录等持久化），与 npm MemoryService / memory-service API 对齐。"""
from typing import Any, Optional

from .base_client import BaseClient
from .types import ClientConfig, RequestOptions, TokenStorage


class MemoryService(BaseClient):
    service_path = "memory"

    def __init__(
        self,
        config: ClientConfig,
        token_storage: Optional[TokenStorage] = None,
    ) -> None:
        super().__init__(config, token_storage=token_storage)

    @property
    def service_name(self) -> str:
        return "memory"

    def create_message(
        self,
        body: dict,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        """写入一条消息（幂等）。POST /api/v1/messages"""
        opts = RequestOptions(method="POST", body=body)
        if options:
            opts.headers = options.headers or opts.headers
            opts.params = options.params or opts.params
            opts.user_context = options.user_context or opts.user_context
        return self.request("/api/v1/messages", opts)

    def list_room_messages(
        self,
        room_id: str,
        source: str,
        limit: Optional[int] = None,
        cursor: Optional[str] = None,
        direction: Optional[str] = None,
        msg_type: Optional[str] = None,
        options: Optional[RequestOptions] = None,
    ) -> dict:
        """分页拉取房间消息（游标分页）。GET /api/v1/rooms/:roomId/messages"""
        params = {"source": source}
        if limit is not None:
            params["limit"] = limit
        if cursor is not None:
            params["cursor"] = cursor
        if direction is not None:
            params["direction"] = direction
        if msg_type is not None:
            params["msg_type"] = msg_type
        opts = RequestOptions(method="GET", params=params)
        if options:
            opts.params = options.params or opts.params
        res = self.request_with_pagination(
            f"/api/v1/rooms/{room_id}/messages",
            opts,
        )
        return {
            "items": res.get("data") or [],
            "next_cursor": (res.get("pagination") or {}).get("cursor"),
            "has_more": (res.get("pagination") or {}).get("has_more", False),
        }

    def get_last_message(
        self,
        room_id: str,
        source: str,
        options: Optional[RequestOptions] = None,
    ) -> Any:
        """获取房间某 source 下最后一条消息。GET /api/v1/rooms/:roomId/last-message"""
        return self.request(
            f"/api/v1/rooms/{room_id}/last-message",
            RequestOptions(method="GET", params={"source": source})
            if options is None
            else options,
        )
