from io import BytesIO
from typing import Any

from python_multipart import parse_form


def parse(
    headers: dict[str, Any],
    body: BytesIO,
) -> dict[str, Any]:
    ret = {}

    def on_field(field):
        field_name = field.field_name.decode().split('.')

        if len(field_name) > 1:
            key, sub = field_name

            if key not in ret:
                ret[key] = {}

            ret[key][sub] = field.value
        else:
            key, *_ = field_name
            ret[key] = field.value

    def on_file(file):
        file.file_object.seek(0)
        ret[file.field_name.decode()] = file.file_object.read(-1)

    parse_form(headers, body, on_field=on_field, on_file=on_file)

    return ret
