"""appxen search — semantic search over knowledge base."""

from __future__ import annotations

import typer

from appxen_cli.display import error, search_results


def search(
    query: str = typer.Argument(..., help="Search query"),
    top_k: int = typer.Option(5, "--top-k", "-k", help="Number of results"),
    json_output: bool = typer.Option(False, "--json", help="Output raw JSON"),
) -> None:
    """Semantic search over the knowledge base."""
    from appxen_cli.main import get_client
    from appxen_cli.display import print_json

    try:
        client = get_client()
    except typer.Exit:
        raise

    try:
        data = client.search(query, top_k=top_k)
    except Exception as e:
        error(f"Search failed: {e}")
        raise typer.Exit(1)

    if json_output:
        print_json(data)
        return

    results = data.get("results", [])
    search_results(results)
