//! Engine-agnostic searchable-index trait.
//!
//! Without it, every engine swap requires touching every LSP module.

use std::any::Any;

use crate::chunk::CodeChunk;
use crate::hybrid::SearchMode;

/// Engine-agnostic searchable index.
///
/// transformer engines,
/// [`RipvecIndex`](crate::encoder::ripvec::index::RipvecIndex) for
/// the ripvec engine.
pub trait SearchableIndex: Send + Sync {
    /// Borrow the indexed chunks.
    fn chunks(&self) -> &[CodeChunk];

    /// Search by text query.
    ///
    /// Returns `(chunk_idx, score)` pairs ranked descending. Score is
    /// normalized to `[0, 1]` regardless of mode so callers can apply
    /// a single threshold consistently.
    fn search(&self, query_text: &str, top_k: usize, mode: SearchMode) -> Vec<(usize, f32)>;

    /// Search by similarity to an existing chunk's embedding.
    ///
    /// Caller passes the chunk index whose embedding should be used
    /// as the query vector. The canonical `goto_definition` pattern:
    /// the LSP layer identifies the chunk at the cursor, then asks
    /// the index for structurally similar chunks elsewhere.
    ///
    /// If `chunk_idx` is out of range or the engine cannot provide
    /// an embedding for it (keyword-only mode, embedding row not
    /// stored), implementations fall back to text-only search via
    /// [`Self::search`].
    fn search_from_chunk(
        &self,
        chunk_idx: usize,
        query_text: &str,
        top_k: usize,
        mode: SearchMode,
    ) -> Vec<(usize, f32)>;

    /// Downcast escape hatch for callers that legitimately need the
    /// concrete engine-specific index type.
    ///
    /// Used by transformer-engine-only code paths (e.g., legacy
    /// `run_search` with caller-supplied query embedding) that need
    /// use [`Any::downcast_ref`] to attempt the conversion. Returns
    /// `None`-equivalent when the concrete type doesn't match.
    ///
    /// Engine-neutral code should never need this; the three
    /// trait methods above are the supported surface.
    fn as_any(&self) -> &dyn Any;
}
