"""CLI 图谱查询命令。"""

from typing import Any

import typer

from hezor_common.cli._common import (
    console,
    create_sdk_from_profile,
    get_profile,
    print_json_output,
    run_async,
)

app = typer.Typer(name="graph", help="知识图谱查询。", no_args_is_help=True)


@app.command("query")
def query(
    query_type: str = typer.Argument(
        ...,
        help=(
            "查询类型: graph_statistics, entity_search, entity_relationships, "
            "entity_subgraph, find_paths, entity_co_occurrence, "
            "entity_communities, community_subgraph, related_communities"
        ),
    ),
    keyword: str | None = typer.Option(None, "--keyword", "-q", help="搜索关键词"),
    entity_name: str | None = typer.Option(None, "--entity", "-e", help="实体名称"),
    entity_type: str | None = typer.Option(None, "--entity-type", help="实体类型"),
    relationship_type: str | None = typer.Option(None, "--rel-type", help="关系类型"),
    direction: str = typer.Option("both", "--direction", "-d", help="方向 (both, in, out)"),
    target_name: str | None = typer.Option(None, "--target", help="目标实体名称"),
    max_depth: int = typer.Option(2, "--max-depth", help="最大遍历深度"),
    max_paths: int = typer.Option(3, "--max-paths", help="最大路径数"),
    community_id: str | None = typer.Option(None, "--community-id", help="社区 ID"),
    limit: int = typer.Option(20, "--limit", "-n", help="结果数量限制"),
    raw: bool = typer.Option(False, "--raw", help="输出原始 JSON"),
) -> None:
    """执行知识图谱查询。"""
    profile = get_profile()

    async def _run() -> Any:
        sdk = create_sdk_from_profile(profile)
        async with sdk:
            return await sdk.knowledge_graph_query(
                query_type=query_type,
                keyword=keyword,
                entity_name=entity_name,
                entity_type=entity_type,
                relationship_type=relationship_type,
                direction=direction,
                target_name=target_name,
                max_depth=max_depth,
                max_paths=max_paths,
                community_id=community_id,
                limit=limit,
            )

    result = run_async(_run())

    if raw:
        print_json_output(result, raw=True)
    else:
        console.print(f"[green]✓[/green] 图谱查询完成 (类型: {query_type})\n")
        print_json_output(result)
