# app/services/query_service.py
import logging
from typing import Any, Dict, List, Optional

from langchain_redis import RedisVectorStore

logger = logging.getLogger(__name__)


class QueryService:
    """Pure query logic; no global state."""

    def __init__(self, vectorstore: Optional[RedisVectorStore] = None):
        self.vectorstore = vectorstore

    def search(self, query: str, top_k: int = 3, distance_threshold: Optional[float] = None) -> List[Dict[str, Any]]:
        """
        Search the vector store for similar documents.
        
        Args:
            query: Search query string
            top_k: Maximum number of results to return
            distance_threshold: Optional distance threshold for filtering results (0.0-1.0)
                               Results with distance > threshold are excluded
        
        Returns:
            List of {"page_content": str, "metadata": dict, "distance": float}
        """
        if self.vectorstore is None:
            raise ValueError("Vector store not initialized")

        try:
            # Use similarity_search_with_score to get distance values
            results = self.vectorstore.similarity_search_with_score(query, k=top_k)
            
            # Convert results and apply distance threshold filtering
            filtered_results = []
            for doc, score in results:
                # score is distance (lower is better in Redis)
                distance = score
                
                # Apply threshold filter if provided
                if distance_threshold is not None and distance > distance_threshold:
                    continue
                
                filtered_results.append({
                    "page_content": doc.page_content,
                    "metadata": doc.metadata if hasattr(doc, "metadata") else {},
                    "distance": distance,
                })
            
            return filtered_results
        except Exception as e:
            logger.error("Search failed: %s", e)
            raise
