"""OCR Service FastAPI Application."""
import logging
from contextlib import asynccontextmanager
from typing import AsyncIterator

from fastapi import FastAPI

from app.config import settings
from app.routers import extract_router, jobs_router
from app.services import job_queue

# Configure logging
logging.basicConfig(
    level=getattr(logging, settings.log_level.upper(), logging.INFO),
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    """Application lifespan handler for startup/shutdown."""
    # Startup
    logger.info("OCR service starting up")
    yield
    # Shutdown
    logger.info("OCR service shutting down")
    await job_queue.close()


app = FastAPI(
    title="MotoVaultPro OCR Service",
    description="OCR processing service for vehicle documents",
    version="1.0.0",
    lifespan=lifespan,
)

# Include routers
app.include_router(extract_router)
app.include_router(jobs_router)


@app.get("/health")
async def health_check() -> dict:
    """Health check endpoint for container orchestration."""
    return {"status": "healthy"}


@app.get("/")
async def root() -> dict:
    """Root endpoint with service information."""
    return {
        "service": "mvp-ocr",
        "version": "1.0.0",
        "log_level": settings.log_level,
        "endpoints": [
            "POST /extract - Synchronous OCR extraction",
            "POST /extract/vin - VIN-specific extraction with validation",
            "POST /extract/receipt - Receipt extraction (fuel, general)",
            "POST /extract/manual - Owner's manual extraction (async)",
            "POST /jobs - Submit async OCR job",
            "GET /jobs/{job_id} - Get async job status",
        ],
    }
