import sys, os, sys, platform
from os import environ
import importlib, importlib.machinery, importlib.util
import winreg

class PyVerNotSupported(Exception):
  pass

def findmodule():
  pyver = f"{sys.version_info.major}.{sys.version_info.minor}"
  ossys = platform.system()
  if not (pyver in ["3.6", "3.7", "3.8", "3.9", "3.10", "3.11", "3.12"]): 
    raise PyVerNotSupported(f"TSMaster doesn't support Python{pyver}.")
  # find TSMaster.pyd
  sdir = ''
  key = None
  try:
    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\TOSUN\TSMaster")
    sdir, t = winreg.QueryValueEx(key, "bin")
  except:
    print('retrieve TSMaster bin path failed, TSMaster is not installed')
  if key != None:
    key.Close()
  if not os.path.exists(sdir):
    sdir = os.path.dirname(os.path.abspath(__file__))
    sdir = os.path.dirname(sdir)
    sdir = os.path.dirname(sdir)
    sdir = os.path.dirname(sdir)
    sdir = os.path.dirname(sdir)
    sdir = os.path.dirname(sdir)
    sdir = os.path.dirname(sdir)
    sdir = os.path.dirname(sdir)
    if not os.path.exists(sdir):
      raise ValueError("TSMaster module not found. Try to reinstall the TSMaster package or check for support compatibility.")
  for fname in os.listdir(sdir):
    if 'TSMaster.pyd' in fname:
      return os.path.join(sdir, os.path.basename(fname))
  raise ValueError("TSMaster module not found. Try to reinstall the TSMaster package.")

def new_import():
    modulefullpath = findmodule()
    loader = importlib.machinery.ExtensionFileLoader("TSMaster", modulefullpath)
    spec = importlib.util.spec_from_file_location("TSMaster", modulefullpath,
        loader=loader, submodule_search_locations=None)
    ld = loader.create_module(spec)
    package = importlib.util.module_from_spec(spec)
    sys.modules["TSMaster"] = package
    spec.loader.exec_module(package)
    return package

#Import the shared lib
package = new_import()
