from fastapi import FastAPI
from contextlib import asynccontextmanager
import logging
import asyncio
from .core.config import settings
from .services.kafka_consumer import kafka_consumer
from .api import health

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage application lifecycle"""
    # Startup
    logger.info("Starting Notification Service...")
    
    # Start Kafka consumer in background
    consumer_task = asyncio.create_task(kafka_consumer.start_consuming())
    
    logger.info("Notification Service started successfully")
    
    yield
    
    # Shutdown
    logger.info("Shutting down Notification Service...")
    kafka_consumer.stop_consuming()
    consumer_task.cancel()
    try:
        await consumer_task
    except asyncio.CancelledError:
        pass

app = FastAPI(
    title=settings.service_name,
    version=settings.version,
    lifespan=lifespan
)

# Include routers
app.include_router(health.router, tags=["health"])

@app.get("/")
async def root():
    return {
        "service": settings.service_name,
        "version": settings.version,
        "status": "running"
    }
