"""
Computer Vision Service
Quality Inspection, OCR, Object Detection, and Face Recognition
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
import logging

from app.api import ocr_routes, detection_routes, quality_routes, face_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 Vision Service...")
    # Pre-load models for faster inference
    from app.services.detection_service import detection_service
    await detection_service.load_models()
    yield
    logger.info("Shutting down Vision Service...")


app = FastAPI(
    title="AI360 Vision Service",
    description="Computer Vision API for Quality Inspection, OCR, Object Detection, and Face Recognition",
    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(ocr_routes.router, prefix="/api/v1/ocr", tags=["OCR"])
app.include_router(detection_routes.router, prefix="/api/v1/detection", tags=["Object Detection"])
app.include_router(quality_routes.router, prefix="/api/v1/quality", tags=["Quality Inspection"])
app.include_router(face_routes.router, prefix="/api/v1/face", tags=["Face Recognition"])


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


@app.get("/")
async def root():
    return {
        "service": "AI360 Vision Service",
        "version": "1.0.0",
        "capabilities": [
            "OCR - Text extraction from images",
            "Object Detection - Detect and classify objects",
            "Quality Inspection - Defect detection for manufacturing",
            "Face Recognition - Face detection and verification"
        ],
        "endpoints": {
            "ocr": "/api/v1/ocr",
            "detection": "/api/v1/detection",
            "quality": "/api/v1/quality",
            "face": "/api/v1/face"
        }
    }
