#####################################################################
# THIS FILE IS AUTOMATICALLY GENERATED BY UNSTRUCTURED API TOOLS.
# DO NOT MODIFY DIRECTLY
#####################################################################

import os
import inspect
from typing import List

from fastapi import status, FastAPI, File, Form, Request, UploadFile
from slowapi.errors import RateLimitExceeded
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
{% if response_type %}from fastapi.responses import PlainTextResponse{% endif %}
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

RATE_LIMIT = os.environ.get("PIPELINE_API_RATE_LIMIT", "1/second")
{% if response_type %}
def is_expected_response_type(media_type, response_type):
    if media_type == "application/json" and response_type not in [dict, list]:
        return True
    elif media_type == "text/csv" and response_type != str:
        return True
    else:
        return False
{% endif %}
{{script}}


@app.post("{{pipeline_path}}")
@limiter.limit(RATE_LIMIT)
async def pipeline_1(request: Request, file: UploadFile = File(),
{% for param in multi_string_param_names %}
{{param}}: List[str] = Form(default=[]),
{% endfor %}
):
    {% if response_type %}
    media_type = request.headers.get("Accept")
    default_response_type = "{{response_type}}"
    media_type = default_response_type if media_type == "*/*" else media_type
    {% endif %}

    text = file.file.read().decode("utf-8")

    {% if response_type %}
    response = pipeline_api(text, {% for param in multi_string_param_names %}m_{{param}}={{param}}, {% endfor %} response_type=media_type,)
    {% else %}
    response = pipeline_api(text, {% for param in multi_string_param_names %}{{param}}, {% endfor %})
    {% endif %}

    {% if response_type %}
    if is_expected_response_type(media_type, type(response)):
        return PlainTextResponse(
            content=f"Conflict in media type {media_type} with response type {type(response)}.\n",
            status_code=status.HTTP_406_NOT_ACCEPTABLE,
        )
    valid_response_types = ["application/json", "text/csv", "*/*"]
    if media_type in valid_response_types:
        return response
    else:
        return PlainTextResponse(
            content=f"Unsupported media type {media_type}.\n",
            status_code=status.HTTP_406_NOT_ACCEPTABLE,
        )
    {% else %}
    return response
    {% endif %}

@app.get("/healthcheck", status_code=status.HTTP_200_OK)
@limiter.limit(RATE_LIMIT)
async def healthcheck(request: Request):
    return {
        "healthcheck": "HEALTHCHECK STATUS: EVERYTHING OK!"
    }
