import logging

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.requests import Request

from app.infra.logging_setup import configure_logging
from app.infra.error_handlers import register_error_handlers
from app.core.application import ModularApplication


def _configure_logging() -> None:
    configure_logging()


_configure_logging()


def create_app() -> FastAPI:
    app = FastAPI(title="Agent Backend MVP", version="0.1.0")
    modules = ModularApplication()
    app.state.modules = modules
    logger = logging.getLogger("app.http")
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=False,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    app.include_router(modules.api.public_router())
    register_error_handlers(app)

    @app.middleware("http")
    async def log_http_requests(request: Request, call_next):
        logger.warning("http request: method=%s path=%s query=%s", request.method, request.url.path, request.url.query)
        try:
            response = await call_next(request)
            logger.warning(
                "http response: method=%s path=%s status=%s",
                request.method,
                request.url.path,
                response.status_code,
            )
            return response
        except Exception:
            logger.exception("http request failed: method=%s path=%s", request.method, request.url.path)
            raise

    @app.on_event("startup")
    async def startup() -> None:
        modules.startup()

    @app.get("/health")
    async def health() -> dict:
        return modules.health_payload()

    return app


app = create_app()
