#!/usr/bin/env python3
"""Minimal LangChain/RAG pipeline with FastAPI and FAISS."""
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.chains import RetrievalQA
from langchain.chat_models import ChatOpenAI

app = FastAPI(title='RAG pipeline')
VECTOR_DIR = os.environ.get('VECTOR_DIR', './faiss_index')
qa = None

class IngestRequest(BaseModel):
    text: str
class AskRequest(BaseModel):
    question: str

@app.post('/ingest')
def ingest(req: IngestRequest):
    global qa
    splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
    docs = splitter.create_documents([req.text])
    vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
    vectorstore.save_local(VECTOR_DIR)
    qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(model='gpt-4o-mini'), retriever=vectorstore.as_retriever())
    return {'chunks': len(docs)}

@app.post('/ask')
def ask(req: AskRequest):
    global qa
    if qa is None:
        if os.path.exists(VECTOR_DIR):
            qa = RetrievalQA.from_chain_type(llm=ChatOpenAI(model='gpt-4o-mini'), retriever=FAISS.load_local(VECTOR_DIR, OpenAIEmbeddings()).as_retriever())
        else:
            raise HTTPException(400, 'Ingest documents first')
    return {'answer': qa.run(req.question)}

if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host='0.0.0.0', port=8000)
