from typing import Dict, List
from analogai.foundation.modules.agent.agent import Agent, Role
from analogai.foundation.modules.user.user import User
from analogai.foundation.common.enums.agent_openness import AgentOpenness


class AgentStorageMapper:
    @staticmethod
    def to_dict(agent: Agent) -> Dict:
        return {
            "id": agent.id,
            "name": agent.name,
            "knowledge_base": agent.knowledge_base,
            "creator_id": agent.creator.id,
            "openness": agent.openness.value,
            "roles": [
                {
                    "user_id": role.user.id,
                    "authority": role.authority
                } for role in agent.roles
            ]
        }

    @staticmethod
    def from_dict(data: Dict) -> Agent:
        creator_id = data.get("creator_id")
        if not creator_id:
            raise ValueError(f"Agent {data.get('id', 'unknown')} is missing creator_id")
        creator = User(id=creator_id, name="", email="")
        
        roles_doc = data.get("roles", [])
        roles: List[Role] = []
        if isinstance(roles_doc, list):
            for role_data in roles_doc:
                if role_data.get("user_id") and role_data.get("authority") is not None:
                    user = User(id=role_data["user_id"], name="", email="")
                    authority = float(role_data["authority"])
                    roles.append(Role(user=user, authority=authority))
        elif isinstance(roles_doc, dict) and roles_doc.get("user_id") and roles_doc.get("authority") is not None:
            user = User(id=roles_doc["user_id"], name="", email="")
            authority = float(roles_doc["authority"])
            roles.append(Role(user=user, authority=authority))
        
        openness_value = data.get("openness", AgentOpenness.OPEN.value)
        openness = AgentOpenness.OPEN
        try:
            openness = AgentOpenness(openness_value)
        except ValueError:
            openness = AgentOpenness.OPEN
        
        return Agent(
            id=data["id"],
            name=data.get("name", ""),
            knowledge_base=data.get("knowledge_base", ""),
            creator=creator,
            roles=roles,
            openness=openness
        )


