"""MessageManager — conversation history retrieval and persistence."""
from __future__ import annotations

import logging

from kokoro_chat.character.model import Character
from kokoro_chat.config import ChatConfig
from kokoro_chat.storage.protocol import (
    CacheStore,
    ChatHistoryStore,
    ChatMessageWriter,
    RollingSummaryStore,
)

logger = logging.getLogger(__name__)


class MessageManager:
    def __init__(
        self,
        history: ChatHistoryStore,
        writer: ChatMessageWriter,
        cache: CacheStore,
        summary_store: RollingSummaryStore,
        config: ChatConfig,
    ) -> None:
        self._history = history
        self._writer = writer
        self._cache = cache
        self._summary_store = summary_store
        self._config = config

    async def get_for_prompt(
        self, char_id: str, user_id: str,
    ) -> tuple[str, list[dict]]:
        """Return (rolling_summary_text, recent_messages) with cache fallback."""
        cfg = self._config
        limit = cfg.recent_turns * 2

        # Recent messages
        cached_msgs = await self._cache.get_recent_messages(user_id, char_id, limit=limit)
        if cached_msgs is not None:
            recent = cached_msgs
        else:
            chat_msgs = await self._history.get_recent(user_id, char_id, limit=limit)
            recent = [{"role": m.role, "content": m.content} for m in chat_msgs]
            if recent:
                await self._cache.set_recent_messages(user_id, char_id, recent)

        # Rolling summary
        cached_summary = await self._cache.get_rolling_summary(user_id, char_id)
        if cached_summary is not None:
            summary_text = cached_summary.get("summary", "")
        else:
            record = await self._summary_store.get_or_create(user_id, char_id)
            summary_text = record.summary or ""
            if summary_text:
                await self._cache.set_rolling_summary(
                    user_id, char_id, summary_text, record.turn_count,
                )

        return summary_text, recent

    async def add_message(
        self,
        char_id: str,
        user_id: str,
        role: str,
        content: str,
        chat_mode: str = "short",
    ) -> None:
        """Write message to store + append to cache."""
        await self._writer.add_message(
            user_id=user_id,
            character_id=char_id,
            role=role,
            content=content,
            chat_mode=chat_mode,
        )
        await self._cache.append_message(user_id, char_id, role, content)

    @staticmethod
    def build_few_shot_prefix(character: Character) -> list[dict]:
        """Convert mes_example to Claude message format."""
        if not character.mes_example:
            return []
        prefix: list[dict] = []
        for ex in character.mes_example:
            user_text = str(ex.get("user", "")).strip()
            char_text = str(ex.get("char", "")).strip()
            if user_text:
                prefix.append({"role": "user", "content": user_text})
            if char_text:
                prefix.append({"role": "assistant", "content": char_text})
        return prefix
