"""Knowledge graph API routes."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException

from pycharter.wiki.api.dependencies import get_db_session
from pycharter.wiki.knowledge.graph import KnowledgeGraph
from pycharter.wiki.shared.errors import GraphError

router = APIRouter(tags=["Wiki"])


@router.get("/concepts/{concept_id}/ancestors")
async def get_ancestors(concept_id: str, session=Depends(get_db_session)):
    """Get ancestor concepts."""
    try:
        kg = KnowledgeGraph(session)
        return kg.get_ancestors(concept_id)
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/concepts/{concept_id}/descendants")
async def get_descendants(concept_id: str, session=Depends(get_db_session)):
    """Get descendant concepts."""
    try:
        kg = KnowledgeGraph(session)
        return kg.get_descendants(concept_id)
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/concepts/tree")
async def get_concept_tree(
    node_kind: str | None = None,
    session=Depends(get_db_session),
):
    """Get the full concept hierarchy tree, optionally filtered by node_kind."""
    try:
        kg = KnowledgeGraph(session)
        tree = kg.get_concept_tree()
        if node_kind is None:
            return tree

        # Filter roots and children by node_kind
        def filter_by_kind(nodes: list) -> list:
            result = []
            for node in nodes:
                children = filter_by_kind(node.get("children", []))
                if node.get("node_kind") == node_kind or children:
                    filtered = {**node, "children": children}
                    result.append(filtered)
            return result

        return {"roots": filter_by_kind(tree.get("roots", []))}
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/concepts/{concept_id}/fields")
async def get_related_fields(concept_id: str, session=Depends(get_db_session)):
    """Get fields related to a concept."""
    try:
        kg = KnowledgeGraph(session)
        return kg.find_related_fields(concept_id)
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.get("/concepts/by-name/{concept_name}/fields")
async def get_fields_for_concept(concept_name: str, session=Depends(get_db_session)):
    """Get fields for a concept by name."""
    try:
        kg = KnowledgeGraph(session)
        return kg.get_fields_for_concept(concept_name)
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))
