import json
import os
# from openai import AzureOpenAI
from rest_framework.response import Response
from rest_framework import status


class OpenApiRequest():
    
    def analyze_receipt_cathegory(self,receipt_type_data, merchant, phone, address):

        # print(receipt_type_data)
        # print(merchant)
        # print(phone)
        # print(address)
        client = AzureOpenAI(
            azure_endpoint = os.getenv('AZURE_OPENAI_ENDPOINT'), 
            api_key= os.getenv('AZURE_OPENAI_API_KEY'),  
            api_version="2024-02-01"
        )

        try:
            response = client.chat.completions.create(
            #model="ToolNotaSpese_ada002 ", # model = "deployment_name"
            model="Tool_Nota_spese",
            temperature=0.1,
            messages=[
                    {"role": "system", "content": "Sei un sistema per categorizzare le informazioni. "},
                    {"role": "user", "content": f"Date le categorie: 1.Aereo, 2.Trasporto pubblico, 3.Noleggio veicoli, 4.Carburante, 5.Parcheggio, 6.Pedaggio, 7.Hotel, 8.Ristorazione, 9.Telefonia e internet, 10.Altro. Data la categoria molto approssimativa dello scontrino: {receipt_type_data}, analizza i seguenti dati e rispondi in che categoria ricade questa azienda: Nome dell'azienda è {merchant}, i telefono se esiste è {phone}, indirizzo  è {address}. Rispondi come se fosse risposta JSON con campi id e name. Se il nome dell'azienda è 'Strada Parchi dei S.p.A.' oppure 'Strada dei Parchi S.p.A.', rispondi con categoria id: 6, name: Pedaggio. Se il nome dell'azienda è 'autostrade per l'Italia' oppure 'Telepass', rispondi con categoria id: 6, name: Pedaggio. Inoltre, se non puoi individuare una categoria, rispondi con categoria id: 10, name: Altro.Rispondi come se fosse risposta JSON. Non aggiungere niente altro alla risposta"}
            ]
            )
            #print(response.choices[0].message.content)
            responseAi = response.choices[0].message.content
            dictionary = json.loads(responseAi)
           



            # data storage for analysis
            self.data_storage_for_analysis(receipt_type_data, merchant, phone, address, dictionary)


            return dictionary
        

        except Exception as e:
            # Handles all other exceptions
            #print(e)
            return Response({'message': "Qualcosa è andato storto durante l'elaborazione dei dati. Riprova a fare la foto o a caricare di nuovo il documento."}, status = status.HTTP_500_INTERNAL_SERVER_ERROR) 
        



    def data_storage_for_analysis(self,receipt_type_data, merchant, phone, address, dictionary):
            
       
            doc_intell_data = f'\n\n\n \n\nDati scontrino da docIntelligence:  \nCategoria: {receipt_type_data}, \nNome azienda: {merchant}, \nTelefono: {phone}, \nIndirizzo: {address}\n'

            ai_response = f'\nCategoria secondo chatGPT: {dictionary}\n\n\n'

            current_directory = os.path.dirname(os.path.abspath(__file__))
            file_path = os.path.join(current_directory, 'responses.txt')

            with open(file_path, 'a') as file:
                file.write(doc_intell_data)
                file.write(ai_response)



    #more specific:
    
        # except openai.AuthenticationError as e:
        #     # Handle Authentication error here, e.g. invalid API key
        #     print(f"OpenAI API returned an Authentication Error: {e}")

        # except openai.APIConnectionError as e:
        #     # Handle connection error here
        #     print(f"Failed to connect to OpenAI API: {e}")

        # except openai.BadRequestError as e:
        #     # Handle connection error here
        #     print(f"Invalid Request Error: {e}")

        # except openai.RateLimitError as e:
        #     # Handle rate limit error
        #     print(f"OpenAI API request exceeded rate limit: {e}")

        # except openai.InternalServerError as e:
        #     # Handle Service Unavailable error
        #     print(f"Service Unavailable: {e}")

        # except openai.APITimeoutError as e:
        #     # Handle request timeout
        #     print(f"Request timed out: {e}")
            
        # except openai.APIError as e:
        #     # Handle API error here, e.g. retry or log
        #     print(f"OpenAI API returned an API Error: {e}")


  
    # --------Analysis of receipt #1--------
    # Receipt type: receipt.retailMeal
    # Merchant Name: Trattoria Il Gabbiano has confidence: 0.972
    # Merchant Phone Number: +39037295108 has confidence: 0.988
    # Merchant Address: {'houseNumber': '10\n26020', 'road': 'Piazza Vittorio Veneto', 'streetAddress': '10\n26020 Piazza Vittorio Veneto'} has confidence: 0.984
    # Transaction Date: 2016-02-06 has confidence: 0.988
    # Transaction Time: 13:45:00 has confidence: 0.988