"""save_memory -- domain logic for saving conversation memories.

Extracted from app/tools/memory_tool.py.
No sqlalchemy / fastapi / redis imports allowed.

Accepts a MemoryVectorStore protocol.
"""
from __future__ import annotations

import logging
from dataclasses import dataclass

from kokoro_chat.storage.protocol import MemoryVectorStore

logger = logging.getLogger(__name__)


@dataclass
class SaveMemoryResult:
    """Result of a save memory operation."""

    success: bool
    memory_id: str = ""
    error: str = ""


async def save_memory(
    store: MemoryVectorStore,
    character_id: str,
    user_id: str,
    summary: str,
    importance: float = 0.5,
    room_id: str | None = None,
    visibility: str = "room",
) -> SaveMemoryResult:
    """Save a conversation memory to the vector store.

    Parameters
    ----------
    store : MemoryVectorStore
        Protocol-based memory storage.
    character_id, user_id : str
        Identifiers for the character/user pair.
    summary : str
        Concise summary of the conversation moment.
    importance : float
        Importance score clamped to [0.0, 1.0].
    room_id : str | None
        Room identifier for scoping the memory.
    visibility : str
        'room' (default) for general facts, 'private' for secrets/confessions.
    """
    if not summary:
        return SaveMemoryResult(success=False, error="summary must not be empty")

    importance = max(0.0, min(1.0, float(importance)))

    if visibility not in ("room", "private"):
        visibility = "room"

    try:
        memory_id = await store.add(
            character_id=character_id,
            user_id=user_id,
            text=summary,
            memory_type="conversation_summary",
            importance=importance,
            room_id=room_id,
            visibility=visibility,
        )

        logger.info(
            "Memory saved for user=%s char=%s: id=%s importance=%.2f visibility=%s",
            user_id, character_id, memory_id, importance, visibility,
        )
        return SaveMemoryResult(success=True, memory_id=memory_id)

    except Exception as e:
        logger.error("save_memory failed: %s", e, exc_info=True)
        return SaveMemoryResult(success=False, error=str(e))
