"""
# flake8: noqa
export.py
---------
Memory export endpoint for HIEROMEM API.

Allows exporting all episodes in a namespace to JSON format.

Author: Sai Rishi Kiran Mannava
"""

from datetime import datetime

from fastapi import APIRouter, Depends

from hieromem_api.auth import require_api_key, require_permission
from hieromem_api.rbac import Permission
from hieromem_api.deps import get_memory_engine
from hieromem_api.tenants import Tenant, canonical_namespace, public_namespace, resolve_tenant
from hieromem_core.memory import Memory

router = APIRouter()


@router.post("/memory/export")
def export_memory(
    namespace: str | None = None,
    tenant: Tenant = Depends(require_api_key),
    memory: Memory = Depends(get_memory_engine),
    _perm_check: None = Depends(require_permission(Permission.MANAGE_TENANT)),
) -> dict:
    """
    Export all episodes in a namespace to JSON.

    Args:
        namespace: Optional namespace to export (defaults to tenant's default namespace)
        tenant: Authenticated tenant
        memory: Memory instance

    Returns:
        JSON dump of all episodes with metadata
    """
    # Use tenant's default namespace if not specified
    tenant = resolve_tenant(tenant)
    public_ns = namespace or tenant.tenant_id
    
    # Convert to internal namespace (adds tenant prefix if isolation is enabled)
    internal_ns = canonical_namespace(tenant, public_ns)

    # Fetch episodes scoped to the requested namespace.
    with memory.use_namespace(internal_ns):
        episodes = list(memory.episodes)
    
    # Convert episodes to JSON-serializable format
    export_data = {
        "namespace": public_namespace(tenant, internal_ns),
        "exported_at": datetime.now().isoformat(),
        "episode_count": len(episodes),
        "episodes": [
            {
                "id": ep.id,
                "embedding": ep.e.tolist(),  # Convert numpy array to list
                "graph": {
                    "nodes": list(ep.G.nodes(data=True)) if ep.G else [],
                    "edges": list(ep.G.edges(data=True)) if ep.G else [],
                } if ep.G else None,
                "timestamp": ep.tocc.isoformat(),
                "trust": ep.trust,
                "parent": ep.parent,
                "meta": ep.meta,
            }
            for ep in episodes
        ],
        "metadata": {
            "Nmax": int(memory.Nmax),
            "b": int(memory.b),
            "lambda": float(memory.lam),
            "theta": float(memory.theta),
            "tau": float(memory.tau),
        }
    }

    return export_data
