"""Agent tools for knowledge chunk graph (studied material relationships)."""
from __future__ import annotations

from typing import Any

from langchain_core.tools import tool


@tool
def knowledge_graph_subgraph(
    focus_node_id: str,
    corpus: str | None = None,
    depth: int = 2,
    max_nodes: int = 80,
    layers: str = "concept",
) -> str:
    """Export a knowledge subgraph around ``focus_node_id``.

    ``layers``: ``concept`` (topics/sources), ``similarity`` (chunk passages),
    ``entity`` (union from entity ``chunk_node_ids``; focus ``knowledge:{slug}:entity:{key}``).
    """
    from utils.knowledge_graph import export_knowledge_subgraph
    import json

    layer = (layers or "concept").strip().lower()
    if layer not in ("concept", "concepts", "similarity", "entity", "entities", "all"):
        return json.dumps({"ok": False, "error": f"unsupported layers: {layers}"})
    out = export_knowledge_subgraph(
        focus_node_id,
        corpus_slug=corpus,
        depth=depth,
        max_nodes=max_nodes,
        layers=layer,
    )
    return json.dumps(out, indent=2)[:12000]


@tool
def knowledge_graph_list_suggestions(corpus: str | None = None, limit: int = 30) -> str:
    """List suggested chunk similarity edges awaiting operator confirm."""
    from utils.knowledge_graph import list_knowledge_graph_suggestions
    import json

    out = list_knowledge_graph_suggestions(corpus_slug=corpus, limit=limit)
    return json.dumps(out, indent=2)[:8000]


@tool
def knowledge_graph_confirm_edge(edge_id: str) -> str:
    """Confirm a suggested knowledge graph edge."""
    from utils.knowledge_graph import confirm_knowledge_graph_edge
    import json

    return json.dumps(confirm_knowledge_graph_edge(edge_id), indent=2)


@tool
def knowledge_graph_reject_edge(edge_id: str) -> str:
    """Reject a suggested or active knowledge graph edge (tombstones the pair)."""
    from utils.knowledge_graph import reject_knowledge_graph_edge
    import json

    return json.dumps(reject_knowledge_graph_edge(edge_id), indent=2)


@tool
def knowledge_graph_neighbors(
    node_id: str,
    corpus: str | None = None,
    limit: int = 12,
    include_suggested: bool = False,
) -> str:
    """List one-hop chunk graph neighbors for a focus node."""
    from utils.knowledge_graph import list_knowledge_graph_neighbors
    import json

    rows = list_knowledge_graph_neighbors(
        node_id,
        corpus_slug=corpus,
        limit=limit,
        include_suggested=bool(include_suggested),
    )
    return json.dumps({"node_id": node_id, "neighbors": rows}, indent=2)[:8000]


@tool
def knowledge_graph_reindex_corpus(corpus: str) -> str:
    """Rebuild chunk embeddings and similarity links for one corpus."""
    from utils.knowledge_graph import refresh_knowledge_graph_suggestions
    import json

    return json.dumps(refresh_knowledge_graph_suggestions(corpus), indent=2)


@tool
def knowledge_graph_gitnexus_hint(node_id: str) -> str:
    """Return a GitNexus MCP query hint for a knowledge chunk node (repo-local sources)."""
    from utils.knowledge_graph import gitnexus_query_hint_for_node

    hint = gitnexus_query_hint_for_node(node_id)
    if not hint:
        return "No GitNexus hint for this node (missing rel_path/repo_root or unknown node)."
    return hint
