"""
FastAPI ML Service Main Application

This is the entry point for the ML inference service.
"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging

from .config import settings
from .models.predictor import ModelPredictor
from . import dependencies

# Configure logging
logging.basicConfig(
    level=getattr(logging, settings.LOG_LEVEL),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    Lifespan context manager for FastAPI app
    Handles startup and shutdown events
    """
    # Startup
    logger.info("Starting ML Service...")
    logger.info(f"Initializing Groq API client with model: {settings.GROQ_MODEL}")
    logger.info(f"API Key configured: {'Yes' if settings.GROQ_API_KEY else 'No'}")

    try:
        predictor = ModelPredictor()
        dependencies.set_predictor(predictor)
        logger.info("Groq API client initialized successfully!")
    except Exception as e:
        logger.error(f"Failed to initialize Groq client: {e}")
        logger.warning("Service will start but predictions will fail")

    yield

    # Shutdown
    logger.info("Shutting down ML Service...")
    dependencies.set_predictor(None)


# Create FastAPI app
app = FastAPI(
    title="Influencer ML Service",
    description="ML inference service for influencer-business matching using Groq API with LLaMA 3.2",
    version="1.0.0",
    lifespan=lifespan
)

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

# Include routers (imported here to avoid circular imports)
from .routers import health, predict
app.include_router(health.router, tags=["Health"])
app.include_router(predict.router, prefix="/api/v1", tags=["Predictions"])


@app.get("/")
async def root():
    """Root endpoint"""
    return {
        "service": "Influencer ML Service",
        "version": "1.0.0",
        "status": "running",
        "model": settings.GROQ_MODEL,
        "provider": "Groq API"
    }

