"""Main FastAPI application for AI Insights Service."""

import structlog

from app.core.config import settings
from app.core.database import init_db, close_db
from app.api import insights
from shared.service_base import StandardFastAPIService

# Initialize logger
logger = structlog.get_logger()


class AIInsightsService(StandardFastAPIService):
    """AI Insights Service with standardized monitoring setup"""

    async def on_startup(self, app):
        """Custom startup logic for AI Insights"""
        # Initialize database
        await init_db()
        logger.info("Database initialized")

        await super().on_startup(app)

    async def on_shutdown(self, app):
        """Custom shutdown logic for AI Insights"""
        await super().on_shutdown(app)

        # Close database
        await close_db()
        logger.info("Database connections closed")


# Create service instance
service = AIInsightsService(
    service_name="ai-insights",
    app_name="AI Insights Service",
    description="Intelligent insights and recommendations for bakery operations",
    version=settings.SERVICE_VERSION,
    log_level=getattr(settings, 'LOG_LEVEL', 'INFO'),
    cors_origins=getattr(settings, 'ALLOWED_ORIGINS', ["*"]),
    api_prefix=settings.API_V1_PREFIX,
    enable_metrics=True,
    enable_health_checks=True,
    enable_tracing=True,
    enable_cors=True
)

# Create FastAPI app
app = service.create_app()

# Add service-specific routers
service.add_router(
    insights.router,
    tags=["insights"]
)


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "app.main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level=settings.LOG_LEVEL.lower()
    )
