# https://fastapi.tiangolo.com/tutorial/body-multiple-params/#singular-values-in-body
from json import JSONDecodeError
from pathlib import Path
from typing import Any
import magic
import arklog
from fastapi import APIRouter, Query, Request, Response
from fastapi.responses import JSONResponse
import asyncio
from io import StringIO
import csv


class ExampleRouter(APIRouter):
    """"""

    def __init__(self, *args: Any, title: str, description: str, version: str, configuration, **kwargs: Any):
        self.title = title
        self.description = description
        self.version = version
        self.configuration = configuration
        super().__init__(*args, **kwargs)

        @self.get("/")
        async def root_mock(request: Request, query: str | None = Query(None)) -> Response:
            """Example request response for a simulated activity."""
            if query:
                match query.lower():
                    case "error":
                        return JSONResponse(status_code=400, content={"ctrl": "error"})
                    case "get":
                        return JSONResponse(status_code=200, content={"ctrl": "ok"})
            try:
                body = await request.json()
            except JSONDecodeError:
                return JSONResponse(status_code=500, content={"ctrl": "error", "debug": "Could not parse json input."})
            control = body.get("ctrl")
            arklog.debug(control)
            content = body.get("input").get("din").get("content")
            f = StringIO(content)
            reader = csv.reader(f, delimiter=',')
            file_path = Path(__file__).parent.parent.parent / Path("data/mock_requirements.txt")
            requirements = file_path.read_text() + "\n\nChecked!"
            mime = magic.Magic(mime=True).from_file(file_path)
            await asyncio.sleep(3)
            if ((list(reader)[5][1]) == '0.0004'):
                return JSONResponse(status_code=200, content={
                    "ctrl": "ok",
                    "output": {
                        "dout": {
                            "type": "inline",
                            "content": requirements,
                            "name": file_path.name,
                            "encoding": mime
                        }
                    }
                })
            else:
                return JSONResponse(status_code=200, content={
                    "ctrl": "notOk",
                    "output": {
                        "dout": {
                            "type": "inline",
                            "content": requirements,
                            "name": file_path.name,
                            "encoding": mime
                        }
                    }
                })


        @self.put("/")
        async def root_put_mock(request: Request, query: str | None = Query(None)) -> Response:
            return await root_mock(request, query)

        @self.post("/")
        async def root_post_mock(request: Request, query: str | None = Query(None)) -> Response:
            return await root_mock(request, query)
