"""
VSS - Video Search & Summarization Service
FastAPI Application Entrypoint
"""

import logging
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from config.settings import get_settings
from config.logging_config import setup_logging
from api.routes import router

# Logging is configured inside the lifespan so the logs/ directory is
# guaranteed to exist before any handler tries to open a file.
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan management."""
    settings = get_settings()
    setup_logging(level=settings.log_level if hasattr(settings, "log_level") else "INFO")
    logger.info(f"Starting VSS service on {settings.api_host}:{settings.api_port}")
    logger.info(f"ClickHouse: {settings.clickhouse.host}:{settings.clickhouse.port}/{settings.clickhouse.database}")
    logger.info(f"LLM: {settings.llm.model_name} @ {settings.llm.endpoint}")
    if settings.vlm_enabled:
        logger.info(f"VLM: enabled — {settings.vlm.model_name} @ {settings.vlm.endpoint}")
    else:
        logger.info("VLM: disabled (set VSS_VLM_ENABLED=true to enable)")
    
    yield
    
    logger.info("Shutting down VSS service")


# Create app
settings = get_settings()
app = FastAPI(
    title="VSS - Video Search & Summarization",
    description="AI-powered video analytics query service",
    version="1.0.0",
    lifespan=lifespan,
)

# CORS — origins are driven by VSS_CORS_ALLOWED_ORIGINS in the environment.
# Default is ["*"] (permissive); restrict to explicit origin(s) in production.
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.cors_allowed_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Routes
app.include_router(router, prefix="/api/v1", tags=["VSS"])


@app.get("/")
async def root():
    return {"service": "VSS", "status": "running", "docs": "/docs"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=settings.api_host,
        port=settings.api_port,
        reload=False,
        workers=1,
        log_level=settings.log_level.lower(),
        access_log=True,
    )