from typing import Dict
from datetime import datetime
from analogai.foundation.extensions.fallback import Fallback


class FallbackStorageMapper:
    @staticmethod
    def to_dict(fallback: Fallback) -> Dict:
        return {
            "id": fallback.id,
            "user_id": fallback.user_id,
            "agent_id": fallback.agent_id,
            "user_question": fallback.user_question,
            "timestamp": fallback.timestamp.isoformat() if fallback.timestamp else None
        }

    @staticmethod
    def from_dict(data: Dict) -> Fallback:
        timestamp = None
        if data.get("timestamp"):
            if isinstance(data["timestamp"], str):
                timestamp = datetime.fromisoformat(data["timestamp"])
            elif isinstance(data["timestamp"], datetime):
                timestamp = data["timestamp"]

        return Fallback(
            id=data.get("id"),
            user_id=data["user_id"],
            agent_id=data["agent_id"],
            user_question=data["user_question"],
            timestamp=timestamp
        )
