from __future__ import annotations

from typing import Any, Dict, Optional

from analogai.deepthink.messaging.fact.fact import Fact


class FactStorageMapper:
    @staticmethod
    def to_document(fact: Fact) -> Dict[str, Any]:
        return {
            "_id": fact.id,
            "turn_id": fact.turn_id,
            "statement_id": fact.statement_id,
            "notion_id": fact.notion_id,
            "reference_type": fact.reference_type,
            "user_id": fact.user_id,
            "agent_id": fact.agent_id,
            "text": fact.text,
            "embedding": fact.embedding,
            "prev_id": fact.prev_id,
            "next_id": fact.next_id,
        }

    @staticmethod
    def from_document(doc: Optional[Dict[str, Any]]) -> Optional[Fact]:
        if not doc:
            return None
        embedding = doc.get("embedding")
        if embedding is not None and not isinstance(embedding, list):
            embedding = None
        return Fact(
            id=str(doc.get("_id")),
            turn_id=doc.get("turn_id"),
            statement_id=doc.get("statement_id"),
            notion_id=doc.get("notion_id"),
            reference_type=doc.get("reference_type"),
            user_id=str(doc.get("user_id")),
            agent_id=str(doc.get("agent_id")),
            text=str(doc.get("text") or ""),
            embedding=embedding,
            prev_id=doc.get("prev_id"),
            next_id=doc.get("next_id"),
        )
