"""
Search CLI for ChunkHive
"""

import typer
from pathlib import Path

from chunkhive.retrieval.vector_store import VectorStore
from chunkhive.retrieval.retrieval_engine import RetrievalEngine

search_app = typer.Typer(help="Search indexed repository")


@search_app.command("query")
def search_query(
    query: str = typer.Argument(..., help="Search query"),
    index_path: Path = typer.Option(..., "--index", "-i"),
    top_k: int = typer.Option(5, "--top-k", "-k"),
    expand: bool = typer.Option(True, "--expand"),
):

    typer.echo("\n🔎 Loading index...")

    vector_store = VectorStore(index_path=index_path)
    vector_store.load()

    retrieval_engine = RetrievalEngine(
        vector_store=vector_store,
        enable_expansion=expand,
    )

    typer.echo("⚡ Running search...\n")

    results = retrieval_engine.search(query=query, top_k=top_k)

    if not results:
        typer.echo("❌ No results found.")
        return

    for i, result in enumerate(results, 1):

        typer.echo("=" * 80)
        typer.echo(f"Result #{i}")
        typer.echo(f"Score: {result['score']:.4f}")
        typer.echo("-" * 80)

        for chunk in result["context"]:
            name = getattr(chunk.ast, "name", "unknown")
            typer.echo(f"\n### {name}")
            typer.echo(chunk.code)

    typer.echo("\n✅ Search complete.")
