import os
from typing import List, Tuple
from pathlib import Path

# Simple in‑memory RAG placeholder. In production replace with a vector store (FAISS, Qdrant, etc.).
# The index is a dict keyed by clone_id, each value is a list of (chunk_text, source_path) tuples.
_RAG_INDEX: dict[str, List[Tuple[str, str]]] = {}


def _split_into_chunks(text: str, chunk_size: int = 500) -> List[str]:
    """Naive whitespace‑based chunker.
    Splits the input text into chunks of roughly ``chunk_size`` characters.
    """
    words = text.split()
    chunks: List[str] = []
    current: List[str] = []
    length = 0
    for w in words:
        length += len(w) + 1
        current.append(w)
        if length >= chunk_size:
            chunks.append(" ".join(current))
            current = []
            length = 0
    if current:
        chunks.append(" ".join(current))
    return chunks


def index_clone_knowledge(clone_id: str, file_path: str, extracted_text: str) -> None:
    """Add extracted text from a knowledge file to the RAG index for ``clone_id``.
    ``file_path`` is stored alongside each chunk for provenance.
    """
    chunks = _split_into_chunks(extracted_text)
    entries = [(chunk, file_path) for chunk in chunks]
    if clone_id not in _RAG_INDEX:
        _RAG_INDEX[clone_id] = []
    _RAG_INDEX[clone_id].extend(entries)


def retrieve_relevant(clone_id: str, query: str, top_k: int = 3) -> List[Tuple[str, str]]:
    """Very naive retrieval: return up to ``top_k`` chunks that contain any query term.
    A real implementation would embed ``query`` and compute similarity scores.
    """
    if clone_id not in _RAG_INDEX:
        return []
    query_terms = set(query.lower().split())
    results: List[Tuple[str, str]] = []
    for chunk, src in _RAG_INDEX[clone_id]:
        if any(term in chunk.lower() for term in query_terms):
            results.append((chunk, src))
            if len(results) >= top_k:
                break
    return results
