# -*- coding: utf-8 -*-

from importlib.metadata import version as pkg_version

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded

from odoo_api.core.config import get_settings
from odoo_api.core.limiter import limiter, set_rate_limits
from odoo_api.routers import get_routers
from odoo_api.exceptions import register_exception_handlers

OPENAPI_TAGS = [
    {"name": "Health", "description": "Server health check"},
    {"name": "Authentication", "description": "Login and token management"},
    {"name": "Models", "description": "CRUD operations and function execution on Odoo models"},
]


def create_app(
    title: str = "Odoo FastAPI Gateway",
    description: str = "REST API gateway for Odoo ERP via XML-RPC.",
    version: str | None = None,
    rate_limits: dict[str, str] | None = None,
    **kwargs,
) -> FastAPI:
    """Create a FastAPI app pre-configured with Odoo gateway routers, exception handlers, and OpenAPI docs."""
    if version is None:
        version = pkg_version("odoo-fastapi-gateway")

    kwargs.setdefault("docs_url", "/api/docs")
    kwargs.setdefault("redoc_url", "/api/redoc")
    kwargs.setdefault("openapi_url", "/api/openapi.json")

    app = FastAPI(
        title=title,
        description=description,
        version=version,
        openapi_tags=OPENAPI_TAGS,
        **kwargs,
    )

    register_exception_handlers(app)

    if rate_limits:
        set_rate_limits(rate_limits)

    app.state.limiter = limiter
    app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

    for router in get_routers():
        app.include_router(router)

    settings = get_settings()
    if settings.cors_origins:
        app.add_middleware(
            CORSMiddleware,
            allow_origins=[o.strip() for o in settings.cors_origins.split(',')],
            allow_credentials=False,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    return app
