"""FastAPI main application."""
from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

from ..utils.config import settings
from ..utils.logging import setup_logging, get_logger
from ..models.database import engine, Base
from ..core.auth import require_auth

# Import routes
from .routes import tracks, search, audio, analyze, similar, stats, library, auth

# Setup logging
setup_logging()
logger = get_logger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Application lifespan events."""
    # Startup
    logger.info("Starting Audio Classifier API")
    logger.info(f"Database: {settings.DATABASE_URL.split('@')[-1]}")  # Hide credentials
    logger.info(f"CORS origins: {settings.cors_origins_list}")

    # Create tables (in production, use Alembic migrations)
    # Base.metadata.create_all(bind=engine)

    yield

    # Shutdown
    logger.info("Shutting down Audio Classifier API")


# Create FastAPI app
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="Audio classification and analysis API",
    lifespan=lifespan,
)

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


# Health check
@app.get("/health", tags=["health"])
async def health_check():
    """Health check endpoint."""
    return {
        "status": "healthy",
        "version": settings.APP_VERSION,
        "service": settings.APP_NAME,
    }


# Include routers
# Auth endpoints (public - no auth required)
app.include_router(auth.router, prefix="/api/auth", tags=["auth"])

# Protected endpoints (auth required for ALL routes)
app.include_router(tracks.router, prefix="/api/tracks", tags=["tracks"], dependencies=[Depends(require_auth)])
app.include_router(search.router, prefix="/api/search", tags=["search"], dependencies=[Depends(require_auth)])
# Audio endpoints handle auth internally (support both header and query param)
app.include_router(audio.router, prefix="/api/audio", tags=["audio"])
app.include_router(analyze.router, prefix="/api/analyze", tags=["analyze"], dependencies=[Depends(require_auth)])
app.include_router(similar.router, prefix="/api", tags=["similar"], dependencies=[Depends(require_auth)])
app.include_router(stats.router, prefix="/api/stats", tags=["stats"], dependencies=[Depends(require_auth)])
app.include_router(library.router, prefix="/api/library", tags=["library"], dependencies=[Depends(require_auth)])


@app.get("/", tags=["root"])
async def root():
    """Root endpoint."""
    return {
        "message": "Audio Classifier API",
        "version": settings.APP_VERSION,
        "docs": "/docs",
        "health": "/health",
    }
