from typing import Any, Coroutine

from fastapi import Request, Response, status
from fastapi.responses import JSONResponse

from ..sentiment_engine.sentiment_engine import SentimentEngine
from .blackbox import Blackbox

from injector import singleton
@singleton
class Sentiment(Blackbox):

    def __init__(self) -> None:
        self.engine = SentimentEngine()

    def __call__(self, *args, **kwargs):
        return self.processing(*args, **kwargs)

    def valid(self,  *args, **kwargs) -> bool:
        data = args[0]
        return isinstance(data, str)
    
    def processing(self, *args, **kwargs) -> int:
        text = args[0]
        return int(self.engine.infer(text))
    
    async def fast_api_handler(self, request) -> Response:
        try:
            data = await request.json()
        except:
            return JSONResponse(content={"error": "json parse error"}, status_code=status.HTTP_400_BAD_REQUEST)
        text = data.get("text")
        if text is None:
            return JSONResponse(content={"error": "text is required"}, status_code=status.HTTP_400_BAD_REQUEST)
        sentiment = self.processing(text)
        return JSONResponse(content={"sentiment": sentiment }, status_code=status.HTTP_200_OK)
    