# async def upload(requestData: dict = Depends(RequestParser())):

import json
from fastapi import Request, UploadFile


class RequestParser:
    def __init__(self, include_files=True):
        self.include_files = include_files

    async def __call__(self, request: Request) -> dict:
        parsed = {
            "method": request.method,
            "url": str(request.url),
            "query": dict(request.query_params),
            "headers": dict(request.headers),
            "cookies": request.cookies,
            "body": None,
            "files": {},
        }

        # ----- BODY (JSON, Text) -----
        raw_body = await request.body()
        if raw_body:
            try:
                parsed["body"] = json.loads(raw_body.decode("utf-8"))
            except Exception:
                parsed["body"] = raw_body.decode("utf-8", errors="ignore")

        # ----- FORM / FILES -----
        try:
            form = await request.form()

            for key, value in form.items():
                # Файл
                if isinstance(value, UploadFile):
                    if self.include_files:
                        file_bytes = await value.read()

                        parsed["files"][key] = {
                            "filename": value.filename,
                            "content_type": value.content_type,
                            "content": file_bytes,
                        }
                else:
                    # Добавляем как текстовое поле
                    if parsed["body"] is None:
                        parsed["body"] = {}
                    if isinstance(parsed["body"], dict):
                        parsed["body"][key] = value

        except Exception:
            pass

        parsed["headers"].pop("cookie", None)
        # logger.info(f"[RequestParser] Parsed request:")
        # logger.info(parsed)
        return parsed
