"""
Views for pydantic form.

Pydantic form generate form that may contains fields that requires some ajax query.
"""

from fastapi import Query

from fastlife import Configurator, Request, Response, XTemplate, configure
from fastlife.domain.model.template import InlineTemplate
from fastlife.shared_utils.resolver import resolve_extended


async def show_widget(
    typ: str,
    request: Request,
    name: str | None = Query(None),
    token: str | None = Query(None),
    removable: bool = Query(False),
) -> Response:
    """
    This views is used by pydantic_form to generate a nested field asynchronously.
    """
    model_cls = resolve_extended(typ)

    template: InlineTemplate = XTemplate()

    rndr = request.registry.get_renderer(template)(request)
    lczr = request.registry.localizer(request.locale_name)
    rndr.globals.update({"request": request, **lczr.as_dict()})
    data = rndr.pydantic_form_field(
        model=model_cls,  # type: ignore
        name=name,
        token=token,
        removable=removable,
        field=None,
    )
    return Response(data, headers={"Content-Type": "text/html"})


@configure
def includeme(config: Configurator) -> None:
    route_prefix = config.registry.settings.fastlife_route_prefix
    config.add_route(
        "fl-pydantic-form-widget",
        f"{route_prefix}/pydantic-form/widgets/{{typ}}",
        show_widget,
        methods=["GET"],
    )
