import urllib.request
import json
import os
import ssl

def allowSelfSignedHttps(allowed):
    # bypass the server certificate verification on client side
    if allowed and not os.environ.get('PYTHONHTTPSVERIFY', '') and getattr(ssl, '_create_unverified_context', None):
        ssl._create_default_https_context = ssl._create_unverified_context

def outputModel(api_key,url,model_name, messages):
    allowSelfSignedHttps(True)
    data = {
        "input_data": {
            "input_string": messages,
            "parameters": {
            "max_new_tokens": 1200
            }
        }
    }
    body = str.encode(json.dumps(data))
    
    if not api_key:
        raise Exception("A key should be provided to invoke the endpoint")
    headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key), 'azureml-model-deployment': model_name }

    req = urllib.request.Request(url, body, headers)

    try:
        response = urllib.request.urlopen(req)

        result = response.read()
        result_str = result.decode('utf-8')
        data = json.loads(result_str)
        # print(data['output'])
        return data['output']
    except urllib.error.HTTPError as error:
        # print("The request failed with status code: " + str(error.code))

        # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
        # print(error.info())
        # print(error.read().decode("utf8", 'ignore'))
        return error.read().decode("utf8", 'ignore')
# from constants import phi_api_key, phi_api_endpoint
# print(outputModel(phi_api_key, phi_api_endpoint, messages))