from typing import List
from sirio.event import ObjEvent
import requests
import json
            
class Message:
    role: str
    content: str

class RequestAiBatch:
    key: str
    idSync: str = None
    sirioDomain: str = None
    application: str
    messages: List[Message]

class SirioAiBatch:
    
    def __init__(self, hostOpenAiBatchRequest: str):
        self.hostOpenAiBatchRequest = hostOpenAiBatchRequest

    def requestBatchAi(self, requestAi: RequestAiBatch) -> str:
        
        url = f'{self.hostOpenAiBatchRequest}/batch/request'
        payload = self.request_to_dict(requestAi)
        response = requests.post(url=url, json=payload)
        if response.status_code == 200:
            #print(f'Invovazione per openai-batch-request, domain: {requestAi.domain} - idSync: {requestAi.idSync}: response: {response.text}')
            id_openai_batch_request = response.text.replace('"', '')
            #print(f'id_openai_batch_request: {id_openai_batch_request}')
            return id_openai_batch_request
        else:
            print(f'Problemi con invocazione openai-batch-request, domain: {requestAi.domain} - idSync: {requestAi.idSync} - status: {response.status_code}: {response.text}')
            raise Exception(f'Problema di invocazione objEvent.domain --> status: {response.status_code}: {response.text}')
    
    def getResponseBatchAi(self, idOpenaiBatchRequest: str) -> str:
        url = f'{self.hostOpenAiBatchRequest}/batch/getById/{idOpenaiBatchRequest}'
        response = requests.get(url=url)
        if response.status_code == 200:
            return response.json()
        else:
            print(f'Problemi con invocazione openai-batch-request getById, idOpenaiBatchRequest: {idOpenaiBatchRequest} - status: {response.status_code}: {response.text}')
            raise Exception(f'Problema di invocazione openai-batch-request getById --> status: {response.status_code}: {response.text}')
    
    def message_to_dict(self, msg: Message):
        return {
            "role": msg.role,
            "content": msg.content
        }

    def request_to_dict(self, r: RequestAiBatch):
        return {
            "key": r.key,
            "idSync": r.idSync,
            "sirioDomain": r.sirioDomain,
            "application": r.application,
            "messages": [self.message_to_dict(m) for m in r.messages]
        }
        
