from fastapi import FastAPI
from contextlib import asynccontextmanager
import logging
import asyncio
from app.core.config import settings
from app.services.google_search_service import GoogleSearchService




logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


google_search_service = GoogleSearchService()

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup
    logger.info("Starting Google Search Service...")
    
    # Start Kafka client
    await google_search_service.kafka_client.start_consumer(topics=[settings.GOOGLE_QUEUE_TOPIC])
    
    # Start consuming messages
    asyncio.create_task(
        google_search_service.kafka_client.consume_messages(message_handler=google_search_service.process_search_task)
    )
    
    logger.info("Google Search Service started")
    
    yield
    
    # Shutdown
    logger.info("Shutting down Google Search Service...")
    await google_search_service.kafka_client.stop()
    logger.info("Google Search Service stopped")

app = FastAPI(
    title="Google Search Service",
    version="1.0.0",
    lifespan=lifespan
)

@app.get("/")
async def root():
    return {"service": "Google Search Service", "status": "running"}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}
