from aiohttp import web
from aiohttp.web import Request, Response, json_response, middleware
from marshmallow import Schema, ValidationError, fields, validate

from . import domain

__all__ = ["create"]


def create() -> web.Application:
    api = web.Application(middlewares=[validation_error_middleware])

    api.add_routes(
        [web.get("/ping", ping), web.post("/v1/extract-lemmas/", extract_lemmas)]
    )

    return api


async def ping(req: Request) -> Response:
    return Response(status=204)


async def extract_lemmas(req: Request) -> Response:
    data = await req.json()
    input_ = ExtractLemmasInputSchema().load(data)[0]["input"]

    got = domain.extract_lemmas(input_)

    return json_response(got)


class ExtractLemmasInputSchema(Schema):
    def __init__(self, *args, **kwargs):
        kwargs["strict"] = True
        super().__init__(*args, **kwargs)

    input = fields.Str(required=True, validate=validate.Length(min=1))


@middleware
async def validation_error_middleware(req: Request, handler) -> Response:
    try:
        return await handler(req)
    except ValidationError as exc:
        return json_response(exc.messages, status=400)
