"""
AI-Powered Analytics Service
Business Intelligence, Forecasting, and Sentiment Analysis
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging

from app.api import analytics_routes, forecast_routes, sentiment_routes
from app.core.config import settings

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


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan events"""
    logger.info("Starting Analytics Service...")
    # Initialize ML models
    from app.services.sentiment_service import sentiment_service
    await sentiment_service.load_models()
    yield
    logger.info("Shutting down Analytics Service...")


app = FastAPI(
    title="AI360 Analytics Service",
    description="AI-Powered Business Intelligence, Forecasting, and Sentiment Analysis",
    version="1.0.0",
    lifespan=lifespan
)

# CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS.split(","),
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include routers
app.include_router(analytics_routes.router, prefix="/api/v1/analytics", tags=["Analytics"])
app.include_router(forecast_routes.router, prefix="/api/v1/forecast", tags=["Forecasting"])
app.include_router(sentiment_routes.router, prefix="/api/v1/sentiment", tags=["Sentiment"])


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


@app.get("/")
async def root():
    return {
        "service": "AI360 Analytics Service",
        "version": "1.0.0",
        "endpoints": {
            "analytics": "/api/v1/analytics",
            "forecast": "/api/v1/forecast",
            "sentiment": "/api/v1/sentiment"
        }
    }
