# -- Must be first 3 lines -----------------------------------------------------
__import__('pysqlite3')
import sys
sys.modules['sqlite3'] = sys.modules.pop('pysqlite3')

import warnings
from dotenv import load_dotenv
load_dotenv()

import chromadb.telemetry.product.posthog as posthog_module
import unittest.mock as mock
posthog_module.Posthog = mock.MagicMock()
warnings.filterwarnings("ignore", category=FutureWarning)

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from langchain_community.embeddings import HuggingFaceEmbeddings

# -- Load ONLY embeddings at startup — small and required for /ask -------------
print("[STARTUP] Loading HuggingFace embeddings...")
shared_embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
print("[STARTUP] Embeddings loaded ?")

from search  import router as search_router
from process import router as process_router

app = FastAPI(
    title="K-nest LMS API",
    description="Search (/ask) + Content Processing (/process)",
    version="3.0.0"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["POST", "GET"],
    allow_headers=["*"],
)

app.include_router(search_router,  tags=["Search"])
app.include_router(process_router, tags=["Process"])

@app.get("/health")
def health():
    from search import _retriever_cache
    return {
        "status":            "running",
        "version":           "3.0.0",
        "model":             "llama-3.1-8b-instant",
        "whisper_loaded":    shared_whisper is not None,
        "cached_retrievers": len(_retriever_cache),
        "endpoints": {
            "search":  "POST /ask",
            "process": "POST /process",
            "health":  "GET  /health",
        }
    }