from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import os
import asyncio
from smart_search import SmartSearch
# from dotenv import load_dotenv

# load_dotenv()

app = FastAPI()
LOAD_BALANCER_URL = os.getenv("LOAD_BALANCER_URL")

search_system = SmartSearch(
    films_url=f'{LOAD_BALANCER_URL}/api/get/movie/all',
    tv_series_url=f'{LOAD_BALANCER_URL}/api/get/series/all'
)
search_system_lock = asyncio.Lock()

@app.on_event("startup")
async def startup_event():
    # Start the background task for updating data and initializing
    asyncio.create_task(update_data_periodically())

async def update_data_periodically():
    while True:
        async with search_system_lock:
            await search_system.update_data()
        await asyncio.sleep(120)  # Sleep for 2 minutes (120 seconds)

class Query(BaseModel):
    query: str

@app.get("/")
async def index():
    return "Server Running ..."

@app.post("/api/search")
async def search(query: Query):
    query_str = query.query
    if not query_str:
        raise HTTPException(status_code=400, detail="Missing 'query' field in JSON body")
    
    async with search_system_lock:
        if not search_system.is_initialized:
            raise HTTPException(status_code=503, detail="Search system is not initialized yet.")
        results = search_system.search(query_str)
    
    return results

@app.get("/api/data")
async def get_data():
    async with search_system_lock:
        if not search_system.is_initialized:
            raise HTTPException(status_code=503, detail="Search system is not initialized yet.")
        films = search_system.films
        tv_series = search_system.tv_series
    
    return {"films": films, "tv_series": tv_series}