from typing import Any
from fastapi import HTTPException, status, Body
from guayaba.app import output


def generate_get(key: str):
    """Generates a GET endpoint function for the given key field."""

    def fn(**kwargs):
        """"""
        print(key, kwargs)
        key_value = kwargs[key]

        path = output / f"{key_value}.json"
        # TODO: Read pydantic model from file is under the output /path/<key_value>.json

    fn.__annotations__ = {key: Any, "return": Any}
    return fn


def generate_post(key: str):
    """Generates a POST endpoint function for the given key field."""
    def fn(item = Body(...)):
        """"""
        print(key, item)

        path = output / f"{key_value}.json"
        key_value = getattr(item, key, None)
        if key_value is None:
            raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Item must include a non-empty '{key}' field.")
        # TODO: Write pydantic model to file is under the output /path/<key_value>.json
        return item
    
    fn.__annotations__ = {"item": Any, "return": Any}
    return fn


def generate_put(key: str):
    """Generates a PUT endpoint function for the given key field."""
    def fn(key_value: Any, item = Body(...)):
        """"""
        path = output / f"{key_value}.json"
        # TODO: Write pydantic model to file is under the output /path/<key_value>.json
        return item
    
    fn.__annotations__ = {key: Any, "item": Any, "return": Any}
    return fn


def generate_delete(key: str):
    """Generates a DELETE endpoint function for the given key field."""
    def fn(**kwargs):
        """"""
        path = output / f"{key_value}.json"
        key_value = kwargs[key]
        # TODO: Delete from file is under the output /path/<key_value>.json
        return {"detail": f"Deleted item with {key} '{key_value}'"}
    
    fn.__annotations__ = {key: Any, "return": Any}
    return fn
