"""
cortex/eval/locomo_converter.py — Convert LoCoMo sessions to Cortex remember() payloads.

Maps conversation dialog turns into the format expected by Cortex's remember() API,
preserving speaker attribution, dialog IDs, and session dates.
"""
from __future__ import annotations

from typing import Any, Dict, List

from .locomo import LoCoMoDataset, LoCoMoSession


def conversations_to_remember_payloads(
    dataset: LoCoMoDataset,
    owner_id: str = "locomo_eval",
) -> List[Dict[str, Any]]:
    """
    Convert LoCoMo sessions → Cortex remember() call payloads.

    Each dialog turn becomes::

        {
            "content": "{speaker}: {text}",
            "owner_id": "locomo_eval",
            "conversation_id": session_id,
            "metadata": {
                "dia_id": dia_id,
                "session_date": session_date,
                "speaker": speaker
            }
        }

    Args:
        dataset: A loaded LoCoMoDataset (from load_native() or load()).
        owner_id: Owner ID for the Cortex payloads.

    Returns:
        List of dicts ready to be passed to cortex.remember().
    """
    payloads: List[Dict[str, Any]] = []

    for session in dataset.sessions:
        for turn in session.conversation:
            speaker = turn.get("role", "unknown")
            content = turn.get("content", "")
            dia_id = turn.get("dia_id", "")

            payload = {
                "content": f"{speaker}: {content}",
                "owner_id": owner_id,
                "conversation_id": session.session_id,
                "metadata": {
                    "dia_id": dia_id,
                    "session_date": session.session_date,
                    "speaker": speaker,
                },
            }
            payloads.append(payload)

    return payloads


def session_to_remember_payloads(
    session: LoCoMoSession,
    owner_id: str = "locomo_eval",
) -> List[Dict[str, Any]]:
    """
    Convert a single LoCoMoSession → Cortex remember() payloads.

    Convenience wrapper for per-session processing.
    """
    payloads: List[Dict[str, Any]] = []

    for turn in session.conversation:
        speaker = turn.get("role", "unknown")
        content = turn.get("content", "")
        dia_id = turn.get("dia_id", "")

        payload = {
            "content": f"{speaker}: {content}",
            "owner_id": owner_id,
            "conversation_id": session.session_id,
            "metadata": {
                "dia_id": dia_id,
                "session_date": session.session_date,
                "speaker": speaker,
            },
        }
        payloads.append(payload)

    return payloads
