import logging

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

from app.core.logging_setup import configure_logging
from app.core.error_handlers import register_error_handlers
from app.modules.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
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=False,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    app.include_router(modules.chat.public_router())
    app.include_router(modules.rag.public_router())
    app.include_router(modules.rag.internal_router())
    app.include_router(modules.rag_repo.internal_router())
    app.include_router(modules.agent.internal_router())

    register_error_handlers(app)

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

    @app.get("/health")
    async def health() -> dict:
        return {"status": "ok"}

    return app


app = create_app()
