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

Allows importing episodes from JSON export format.

Author: Sai Rishi Kiran Mannava
"""

from fastapi import APIRouter, Depends
from pydantic import BaseModel
from hieromem_api.auth import require_api_key
from hieromem_api.tenants import Tenant, canonical_namespace, public_namespace
from hieromem_api.deps import get_memory_engine
from hieromem_core.memory import Memory
from datetime import datetime
import numpy as np
import networkx as nx

router = APIRouter()


class ImportRequest(BaseModel):
    """Request body for memory import."""
    namespace: str | None = None
    episodes: list[dict]
    merge_strategy: str = "replace"  # "replace" or "merge"


@router.post("/memory/import")
def import_memory(
    request: ImportRequest,
    tenant: Tenant = Depends(require_api_key),
    memory: Memory = Depends(get_memory_engine),
) -> dict:
    """
    Import episodes from JSON export format.

    Args:
        request: Import request with episodes data
        tenant: Authenticated tenant
        memory: Memory instance

    Returns:
        Summary of import operation
    """
    namespace = request.namespace or tenant.tenant_id
    public_ns = request.namespace or tenant.tenant_id
    internal_ns = canonical_namespace(tenant, public_ns)

    # Clear existing episodes if replace strategy
    if request.merge_strategy == "replace":
        with memory.use_namespace(internal_ns):
            memory.episodes = []

    # Import episodes
    imported_count = 0
    for ep_data in request.episodes:
        # Reconstruct embedding
        embedding = np.array(ep_data["embedding"], dtype=np.float32)

        # Reconstruct graph
        graph = None
        if ep_data.get("graph"):
            graph = nx.DiGraph()
            for node, data in ep_data["graph"]["nodes"]:
                graph.add_node(node, **data)
            for u, v, data in ep_data["graph"]["edges"]:
                graph.add_edge(u, v, **data)
        else:
            graph = nx.DiGraph()  # Create empty graph if none provided

        # Prepare metadata and ensure namespace is set
        meta = ep_data.get("meta", {})
        meta["namespace"] = internal_ns  # Ensure namespace is in metadata

        # Use memory.insert() to properly add episode with namespace support
        # This ensures multi-tenant mode works correctly
        episode = memory.insert(
            embedding,
            graph,
            meta,
            namespace=internal_ns,
        )

        # Preserve original ID, timestamp, and trust
        episode.id = ep_data["id"]
        episode.tocc = datetime.fromisoformat(ep_data["timestamp"])
        episode.trust = ep_data.get("trust", 1.0)
        if ep_data.get("parent"):
            episode.parent = ep_data["parent"]

        # Save to store if available (insert() might not persist immediately)
        if memory.store:
            memory.store.save_episode(episode)

        imported_count += 1

    return {
        "namespace": public_namespace(tenant, internal_ns),
        "imported_at": datetime.now().isoformat(),
        "imported_count": imported_count,
        "merge_strategy": request.merge_strategy,
    }
