"""
RBSP One-Line API.

Provides the simplest possible interface to RBSP::

    from rbsp import resolve
    results = resolve("authentication logic")

All functions delegate to :class:`~rbsp.runtime.engine.RBSPEngine` and
handle lazy initialization transparently.
"""

from __future__ import annotations

from pathlib import Path
from typing import Any, Dict, List, Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from rbsp.runtime.engine import IndexStats, Result


def resolve(query: str, scope: str = ".", **kwargs: Any) -> "List[Result]":
    """Search for code matching *query* and return ranked results.

    This is the primary entry point for RBSP.  If no index exists for
    *scope*, one is created automatically on first call.

    Parameters
    ----------
    query:
        Natural-language or keyword search string.
    scope:
        Directory to search within (default: current directory).

    Returns
    -------
    list[Result]
        Ranked list of matching results, highest score first.

    Example
    -------
    >>> from rbsp import resolve
    >>> results = resolve("authentication logic")
    >>> for r in results[:5]:
    ...     print(f"{r.path}:{r.line}  ({r.score:.2f})")
    """
    from rbsp.runtime.engine import RBSPEngine

    engine = RBSPEngine.get_instance()
    if not engine.is_initialized:
        engine.init(scope)
    return engine.resolve(query, scope=scope, **kwargs)


def search(query: str, **kwargs: Any) -> "List[Result]":
    """Extended search with additional keyword options.

    Accepts the same parameters as :func:`resolve` plus:

    - ``scope``      : directory to search (default ``"."``)
    - ``max_results``: maximum number of results to return
    - ``threshold``  : minimum score threshold

    Example
    -------
    >>> from rbsp import search
    >>> results = search("database connection", scope="src/", max_results=10)
    """
    from rbsp.runtime.engine import RBSPEngine

    engine = RBSPEngine.get_instance()
    scope = kwargs.pop("scope", ".")
    if not engine.is_initialized:
        engine.init(scope)
    return engine.search(query, scope=scope, **kwargs)


def index(path: str = ".", **kwargs: Any) -> "IndexStats":
    """Index all files under *path*.

    Creates the RBSP index structure if it doesn't exist.  Subsequent
    calls only re-index files that have changed.

    Parameters
    ----------
    path:
        Directory to index (default: current directory).

    Returns
    -------
    IndexStats
        Statistics about the indexing operation.

    Example
    -------
    >>> from rbsp import index
    >>> stats = index("/my/project")
    >>> print(f"Indexed {stats.files_indexed} files in {stats.duration:.2f}s")
    """
    from rbsp.runtime.engine import RBSPEngine

    engine = RBSPEngine.get_instance()
    if not engine.is_initialized:
        engine.init(path)
    force = kwargs.pop("force", False)
    return engine.index(path, force=force)


def init(path: str = ".", **kwargs: Any) -> None:
    """Initialize RBSP in a directory.

    Creates the ``.rbsp/`` structure and writes a default configuration.
    Safe to call multiple times (idempotent).

    Parameters
    ----------
    path:
        Project root to initialize (default: current directory).

    Example
    -------
    >>> from rbsp import init
    >>> init("/my/project")
    """
    from rbsp.runtime.engine import RBSPEngine

    engine = RBSPEngine.get_instance()
    engine.init(path, overrides=kwargs.get("overrides"))


def status(path: str = ".") -> "Dict[str, Any]":
    """Return the current RBSP engine status and statistics.

    Example
    -------
    >>> from rbsp.runtime.api import status
    >>> info = status()
    >>> print(f"Index entries: {info['index_entries']}")
    """
    from rbsp.runtime.engine import RBSPEngine

    engine = RBSPEngine.get_instance()
    if not engine.is_initialized:
        engine.init(path)
    return engine.status()
