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

from mocka.artefact import Artefact


class TemplateRouter(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:
            """Template 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."})
            # Check if we were provided all the data we need to abort early
            control = body.get("ctrl")
            arklog.debug(control)
            content = body.get("input").get("din").get("content")
            name = body.get("input").get("din").get("name")
            mime_type = body.get("input").get("din").get("encoding")

            # The example uses a mock requirements file.
            # This activity checks a local file and appends checked to it to send to the requester.
            requirements = content + "\n\nChecked!"
            return_artefact = Artefact("inline", requirements, name, mime_type)

            return JSONResponse(status_code=200, content={
                "ctrl": "ok",
                "output": {
                    "dout": return_artefact.as_dict()
                }
            })

        @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)
