import logging

from services.memory import get_session

logger = logging.getLogger(__name__)


async def resolve_session_persona(
    session_id: str,
    requested: str | None = None,
    *,
    create_persona: str | None = None,
) -> str:
    """
    Session.persona_id is the source of truth.
    requested is ignored when it disagrees (logged). create_persona used only if session missing.
    """
    session = await get_session(session_id)
    if not session:
        return (create_persona or requested or "default").strip() or "default"

    bound = (session.get("persona_id") or "default").strip() or "default"
    req = (requested or "").strip()
    if req and req != bound:
        logger.warning(
            "persona_id mismatch session=%s bound=%s requested=%s (using bound)",
            session_id,
            bound,
            req,
        )
    return bound
