"""Main FastAPI application entry point and configuration."""

import logging
from logging.handlers import RotatingFileHandler

from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from .api.dependencies import verify_api_key
from .api.routes import router
from .config import settings

# Configure logging
file_handler = RotatingFileHandler(
    settings.LOG_FILE,
    maxBytes=10 * 1024 * 1024,
    backupCount=5,
)

console_handler = logging.StreamHandler()

logging.basicConfig(
    handlers=[file_handler, console_handler],
    level=settings.LOG_LEVEL,
    format=settings.LOG_FORMAT,
)

logger = logging.getLogger(__name__)

# Create FastAPI app
app = FastAPI()

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


# Add API key middleware
@app.middleware("http")
async def api_key_middleware(request: Request, call_next: Response) -> Response:
    """Middleware to verify API key in request headers.

    Args:
        request (Request): The incoming request.
        call_next (Response): The next middleware or endpoint function.

    Returns:
        Response: The response generated by the next function in the chain.
    """
    await verify_api_key(request)
    return await call_next(request)


# Add 404 handler
@app.exception_handler(404)
async def custom_404_handler(request: Request, _exc: HTTPException) -> Response:
    """Custom handler for 404 Not Found errors.

    Args:
        request (Request): The incoming request that resulted in a 404.
        _exc (HTTPException): The HTTPException instance (unused).

    Returns:
        Response: A JSONResponse with status code 404 and detail message.
    """
    logger.warning(f"404 Error: {request.method} {request.url.path} | IP: {request.client.host}")
    return JSONResponse(status_code=404, content={"detail": "Not found"})


# Include all routes
app.include_router(router)

if __name__ == "__main__":
    import asyncio
    from pathlib import Path

    from hypercorn.asyncio import serve
    from hypercorn.config import Config

    config = Config()
    config.bind = ["0.0.0.0:8000"]
    config.use_reloader = True  # Enable auto-reload
    config.reload_dirs = [str(Path(__file__).parent)]  # Watch the src directory
    config.loglevel = "DEBUG"
    config.accesslog = "-"
    config.errorlog = "-"
    config.worker_class = "asyncio"

    asyncio.run(serve(app, config))
