"""cortex/api/routes/graph.py — Graph visualization endpoints."""

import logging
from typing import Any, Dict, List, Optional

from fastapi import APIRouter, Depends, HTTPException, status

from cortex.api.deps import PREFIX, _serialise, get_plugin

logger = logging.getLogger(__name__)

router = APIRouter()


def _make_routes(verify_api_key):
    """Register graph visualization routes with the given auth dependency."""

    @router.get(
        f"{PREFIX}/graph",
        summary="Get entity relationship graph",
        tags=["graph"],
    )
    async def get_entity_graph(
        owner_id: Optional[str] = None,
        center_entity_id: Optional[str] = None,
        max_depth: int = 2,
        max_nodes: int = 50,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ):
        """Return entity relationship graph for visualization."""
        if plugin.storage is None:
            raise HTTPException(503, detail="Storage unavailable")

        owner_id = owner_id or getattr(plugin.config, "owner_id", "default")

        try:
            graph_data = await plugin.storage.get_entity_graph(
                owner_id=owner_id,
                center_entity_id=center_entity_id,
                max_depth=max_depth,
                max_nodes=max_nodes,
            )
            return graph_data
        except Exception as exc:
            logger.error("get_entity_graph failed: %s", exc, exc_info=True)
            raise HTTPException(500, detail="Internal server error")

    @router.get(
        f"{PREFIX}/graph/neighbors/{{entity_id}}",
        summary="Get entity neighborhood",
        tags=["graph"],
    )
    async def get_entity_neighbors(
        entity_id: str,
        owner_id: Optional[str] = None,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ):
        """Return immediate neighbors of an entity."""
        if plugin.storage is None:
            raise HTTPException(503, detail="Storage unavailable")

        owner_id = owner_id or getattr(plugin.config, "owner_id", "default")

        try:
            neighbors = await plugin.storage.get_entity_neighbors(
                entity_id=entity_id,
                owner_id=owner_id,
            )
            return neighbors
        except Exception as exc:
            logger.error("get_entity_neighbors failed: %s", exc, exc_info=True)
            raise HTTPException(500, detail="Internal server error")

    @router.get(
        f"{PREFIX}/graph/paths/{{source_id}}/{{target_id}}",
        summary="Find shortest path between entities",
        tags=["graph"],
    )
    async def get_entity_path(
        source_id: str,
        target_id: str,
        owner_id: Optional[str] = None,
        max_hops: int = 5,
        _: None = Depends(verify_api_key),
        plugin: Any = Depends(get_plugin),
    ):
        """Find shortest path between two entities."""
        if plugin.storage is None:
            raise HTTPException(503, detail="Storage unavailable")

        owner_id = owner_id or getattr(plugin.config, "owner_id", "default")

        try:
            path = await plugin.storage.find_shortest_path(
                source_id=source_id,
                target_id=target_id,
                owner_id=owner_id,
                max_hops=max_hops,
            )
            return path
        except Exception as exc:
            logger.error("get_entity_path failed: %s", exc, exc_info=True)
            raise HTTPException(500, detail="Internal server error")
