# File: hypertube/utils/messageHelper/MessageHelper.py
import datetime
import importlib.metadata
import os
import platform
import socket
import threading
import urllib.request
import urllib.error
import json

from hypertube.utils.UtilsConst import UtilsConst


def __get_host_name():
    try:
        return socket.gethostname()
    except socket.error:
        return "Unknown Host"


def __get_package_version():
    try:
        return importlib.metadata.version("hypertube-python-sdk")
    except importlib.metadata.PackageNotFoundError:
        return None


APP_INSIGHTS_TRACK_URL = "https://dc.services.visualstudio.com/v2/track"
REQUEST_TIMEOUT_SECONDS = 3
INSTRUMENTATION_KEY = os.environ.get("HYPERTUBE_INSTRUMENTATION_KEY", "2c751560-90c8-40e9-b5dd-534566514723")
CALLING_RUNTIME_NAME = "Python"
VERSION = __get_package_version()
NODE_NAME = __get_host_name()
OS_NAME = platform.system()


class MessageHelper:

    @staticmethod
    def send_message_to_app_insights(operation_name, message):
        thread = threading.Thread(target=MessageHelper.send_message_to_app_insights_sync,
                                  args=(operation_name, message))
        thread.start()

    @staticmethod
    def send_message_to_app_insights_sync(operation_name, message):
        try:
            formatted_datetime = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S")
            license_key = UtilsConst.get_license_key()

            json_payload = {
                "name": "AppEvents",
                "time": formatted_datetime,
                "iKey": INSTRUMENTATION_KEY,
                "tags": {
                    "ai.application.ver": VERSION,
                    "ai.cloud.roleInstance": NODE_NAME,
                    "ai.operation.id": "0",
                    "ai.operation.parentId": "0",
                    "ai.operation.name": operation_name,
                    "ai.internal.sdkVersion": "hypertube",
                    "ai.internal.nodeName": NODE_NAME
                },
                "data": {
                    "baseType": "EventData",
                    "baseData": {
                        "ver": 2,
                        "name": message,
                        "properties": {
                            "OperatingSystem": OS_NAME,
                            "LicenseKey": license_key,
                            "CallingTechnology": CALLING_RUNTIME_NAME
                        }
                    }
                }
            }

            data = json.dumps(json_payload).encode("utf-8")
            req = urllib.request.Request(
                APP_INSIGHTS_TRACK_URL,
                data=data,
                headers={'Content-Type': 'application/json'}
            )
            with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT_SECONDS) as response:
                status_code = response.getcode()
            return status_code
        except urllib.error.HTTPError as e:
            return e.code
        except Exception:
            return 0
