"""upsert_memo -- domain logic for user memo updates.

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

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

import logging
from dataclasses import dataclass

from kokoro_chat.storage.protocol import MemoStore

logger = logging.getLogger(__name__)


@dataclass
class UpsertMemoResult:
    """Result of a memo upsert operation."""

    success: bool
    key: str = ""
    value: str = ""
    error: str = ""


async def upsert_memo(
    store: MemoStore,
    user_id: str,
    character_id: str,
    key: str,
    value: str,
) -> UpsertMemoResult:
    """Upsert a user memo (personal information).

    Parameters
    ----------
    store : MemoStore
        Protocol-based memo storage.
    user_id, character_id : str
        Identifiers for the user/character pair.
    key : str
        Memo key (e.g. ``user_name``, ``likes_food``).
    value : str
        The value to store.
    """
    key = key.strip()
    value = value.strip()

    if not key:
        return UpsertMemoResult(success=False, error="key must not be empty")
    if not value:
        return UpsertMemoResult(success=False, error="value must not be empty")

    try:
        await store.upsert(
            user_id=user_id,
            character_id=character_id,
            key=key,
            value=value,
        )

        logger.info(
            "Memo upserted for user=%s char=%s: %s=%s",
            user_id, character_id, key, value,
        )
        return UpsertMemoResult(success=True, key=key, value=value)

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