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

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 kafka_client.start_consumer([settings.GOOGLE_QUEUE_TOPIC])
    
    # Start consuming messages
    asyncio.create_task(
        kafka_client.consume_messages(google_search_service.process_search_task)
    )
    
    logger.info("Google Search Service started")
    
    yield
    
    # Shutdown
    logger.info("Shutting down Google Search Service...")
    await 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"}
