from .connection import get_mongo_client

def insert_rag_documents(documents, collection_name="rag_documents", db_name="vectors_db"):
    client = get_mongo_client()
    db = client.get_database(db_name)
    collection = db[collection_name]
    
    if documents:
        result = collection.insert_many(documents)
        return len(result.inserted_ids)
    return 0

def search_rag_documents(query_embedding, collection_name="rag_documents", db_name="vectors_db", num_results=5):
    client = get_mongo_client()
    db = client.get_database(db_name)
    collection = db[collection_name]
    
    pipeline = [
        {
            "$vectorSearch": {
                "index": "vector_index",
                "path": "embedding",
                "queryVector": query_embedding,
                "numCandidates": num_results * 10,
                "limit": num_results
            }
        },
        {
            "$project": {
                "_id": 0,
                "text": 1,
                "score": { "$meta": "vectorSearchScore" }
            }
        }
    ]
    
    return list(collection.aggregate(pipeline))

def is_file_processed(filename, log_collection="ingested_files", db_name="vectors_db"):
    client = get_mongo_client()
    db = client.get_database(db_name)
    collection = db[log_collection]
    return collection.find_one({"filename": filename}) is not None

def log_processed_file(filename, log_collection="ingested_files", db_name="vectors_db"):
    client = get_mongo_client()
    db = client.get_database(db_name)
    collection = db[log_collection]
    collection.insert_one({"filename": filename, "processed_at": 1})
