"""Text-level memory interchange — HU3-prime protocol.

Provides export/import of MemoryUnit collections in portable text formats.
Embeddings are NOT included in exports — the receiving system re-embeds
text content in its own model (~10-15ms per memory for MiniLM-L6-v2).

Supported formats:
    - "json": Single JSON array of portable dicts.
    - "jsonl": One JSON object per line (streaming-friendly).
"""

from __future__ import annotations

import json

from .memory_unit import MemoryUnit


def export_memories(memories: list[MemoryUnit], format: str = "json") -> str:
    """Export memories as portable text (no embeddings).

    Args:
        memories: List of MemoryUnit objects to export.
        format: Output format — "json" (array) or "jsonl" (one per line).

    Returns:
        Serialized string in the requested format.

    Raises:
        ValueError: If format is not "json" or "jsonl".
    """
    if format not in ("json", "jsonl"):
        raise ValueError(f"Unsupported format: {format!r}. Use 'json' or 'jsonl'.")

    portables = [m.to_portable() for m in memories]

    if format == "jsonl":
        return "\n".join(json.dumps(p) for p in portables)

    return json.dumps(portables, indent=2)


def import_memories(data: str, format: str = "json") -> list[MemoryUnit]:
    """Import memories from portable text format.

    Creates MemoryUnit objects with local fields (id, embedding, etc.)
    set to defaults. The caller is responsible for storing them via
    storage.store() which will compute fresh embeddings.

    Args:
        data: Serialized string in the specified format.
        format: Input format — "json" (array) or "jsonl" (one per line).

    Returns:
        List of MemoryUnit objects ready for storage.

    Raises:
        ValueError: If format is not "json" or "jsonl".
    """
    if format not in ("json", "jsonl"):
        raise ValueError(f"Unsupported format: {format!r}. Use 'json' or 'jsonl'.")

    if format == "jsonl":
        records = [json.loads(line) for line in data.strip().splitlines() if line.strip()]
    else:
        records = json.loads(data)

    return [MemoryUnit.from_portable(r) for r in records]
