"""RecentChatContextProvider -- injects recent chat history as context.

Extracted from app/providers/recent_chat.py.
No sqlalchemy / fastapi / redis imports allowed.

Uses ``ChatHistoryStore`` protocol instead of direct DB access.
"""
from __future__ import annotations

import logging

from kokoro_chat.storage.protocol import ChatHistoryStore

logger = logging.getLogger(__name__)


class RecentChatContextProvider:
    """Build recent chat history context.

    Created per-request with a ChatHistoryStore and user/character identifiers.
    """

    def __init__(
        self,
        store: ChatHistoryStore,
        character_id: str,
        user_id: str,
        limit: int = 6,
    ):
        self._store = store
        self._character_id = character_id
        self._user_id = user_id
        self._limit = limit

    async def build(self, query: str) -> str:
        """Fetch recent messages and format them as context.

        ``query`` is accepted for protocol compliance but not used --
        recent chat context is static per request.
        """
        try:
            messages = await self._store.get_recent(
                user_id=self._user_id,
                character_id=self._character_id,
                limit=self._limit,
            )
        except Exception as e:
            logger.warning("RecentChatContextProvider failed: %s", e)
            return ""

        if not messages:
            return ""

        lines = ["[\u6700\u8fd1\u5c0d\u8a71]"]
        for msg in messages:
            role = "\u7528\u6236" if msg.role == "user" else "\u89d2\u8272"
            lines.append(f"{role}: {msg.content[:100]}")
        return "\n".join(lines)
