"""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="knowledge", help="知识库检索。", no_args_is_help=True)


@app.command("search")
def search(
    query: str = typer.Argument(..., help="搜索查询"),
    collection: str = typer.Argument(
        ..., help="集合名称 (chunks, entities, communities, pictures, relationships)"
    ),
    top_k: int = typer.Option(5, "--top-k", "-k", help="返回数量"),
    score_threshold: float = typer.Option(0.5, "--threshold", "-t", help="分数阈值"),
    search_mode: str = typer.Option("semantic", "--mode", "-m", help="搜索模式 (semantic, hybrid)"),
    vector_weight: float = typer.Option(0.7, "--vector-weight", help="向量权重 (hybrid 模式)"),
    text_weight: float = typer.Option(0.3, "--text-weight", help="文本权重 (hybrid 模式)"),
    entity_type: str | None = typer.Option(None, "--entity-type", help="实体类型过滤"),
    doc_id: str | None = typer.Option(None, "--doc-id", help="文档 ID 过滤"),
    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_search(
                query=query,
                collection=collection,
                top_k=top_k,
                score_threshold=score_threshold,
                search_mode=search_mode,
                vector_weight=vector_weight,
                text_weight=text_weight,
                entity_type=entity_type,
                doc_id=doc_id,
            )

    result = run_async(_run())

    if raw:
        print_json_output(result, raw=True)
    else:
        items = result.results if hasattr(result, "results") else []
        console.print(f"找到 [bold]{len(items)}[/bold] 条结果\n")
        print_json_output(result)


@app.command("retrieve")
def retrieve(
    query: str = typer.Argument(..., help="检索查询"),
    top_k: int = typer.Option(3, "--top-k", "-k", help="返回数量"),
    score_threshold: float = typer.Option(0.5, "--threshold", "-t", 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_retrieve(
                query=query,
                top_k=top_k,
                score_threshold=score_threshold,
            )

    result = run_async(_run())

    if raw:
        print_json_output(result, raw=True)
    else:
        items = result.results if hasattr(result, "results") else []
        console.print(f"找到 [bold]{len(items)}[/bold] 条结果\n")
        print_json_output(result)
