"""
realms.py
---------
API routes for managing memory realms (Phase 4).
"""

from fastapi import APIRouter, Depends, HTTPException
from hieromem_core.memory import Memory
from hieromem_api.deps import get_memory_engine
from hieromem_api.auth import require_permission
from hieromem_api.rbac import Permission
from hieromem_api.models.requests import CreateRealmRequest, JoinRealmRequest
from hieromem_api.models.responses import RealmResponse

router = APIRouter(prefix="/realms", tags=["Realms"])


@router.post("", response_model=RealmResponse)
def create_realm(
    req: CreateRealmRequest,
    memory: Memory = Depends(get_memory_engine),
    _perm: None = Depends(require_permission(Permission.MANAGE_REALMS))
):
    """Create a new memory realm."""
    try:
        # Convert Pydantic participants to dicts
        participants = None
        if req.participants:
            participants = [p.dict() for p in req.participants]

        realm = memory.create_realm(
            name=req.name,
            realm_type=req.type,
            participants=participants,
            isolation_level=req.isolation_level
        )

        # Convert back solely to response model
        part_dicts = [
            {"agent_id": p.agent_id, "permissions": p.permissions}
            for p in realm.participants
        ]

        return RealmResponse(
            name=realm.name,
            type=realm.type,
            participants=part_dicts,
            isolation_level=realm.isolation_level,
            count=0
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/{name}", response_model=RealmResponse)
def get_realm(
    name: str,
    memory: Memory = Depends(get_memory_engine),
    _perm: None = Depends(require_permission(Permission.READ_MEMORY))
):
    """Get details of a memory realm."""
    if name not in memory.realms:
        raise HTTPException(status_code=404, detail=f"Realm '{name}' not found")

    realm = memory.realms[name]

    # Calculate count (optional)
    count = 0
    if memory._multi_tenant and name in memory._episodes_by_namespace:
        count = len(memory._episodes_by_namespace[name])

    part_dicts = [
        {"agent_id": p.agent_id, "permissions": p.permissions}
        for p in realm.participants
    ]

    return RealmResponse(
        name=realm.name,
        type=realm.type,
        participants=part_dicts,
        isolation_level=realm.isolation_level,
        count=count
    )


@router.post("/{name}/join", response_model=RealmResponse)
def join_realm(
    name: str,
    req: JoinRealmRequest,
    memory: Memory = Depends(get_memory_engine),
    _perm: None = Depends(require_permission(Permission.MANAGE_REALMS))
):
    """Add a participant to a realm."""
    if name not in memory.realms:
        raise HTTPException(status_code=404, detail=f"Realm '{name}' not found")

    realm = memory.realms[name]

    # Check if already exists
    for p in realm.participants:
        if p.agent_id == req.agent_id:
            raise HTTPException(status_code=400, detail=f"Agent '{req.agent_id}' already in realm")

    # Add
    from hieromem_core.realms import RealmParticipant
    realm.participants.append(RealmParticipant(
        agent_id=req.agent_id,
        permissions=req.permissions
    ))

    part_dicts = [
        {"agent_id": p.agent_id, "permissions": p.permissions}
        for p in realm.participants
    ]

    return RealmResponse(
        name=realm.name,
        type=realm.type,
        participants=part_dicts,
        isolation_level=realm.isolation_level,
    )
