import time
from .utils import decode_text, getCommand, isLinux, isMac, isWindows
from .utils_debug import debug_log
import os
import subprocess


def __FIX_PATH_VARIABLES():
    if isMac() or isLinux():
        # for some reason usr/locaL/bin doesnt exist in the path on mac when running from blender app
        currentPathVariables = os.environ["PATH"].split(os.pathsep)
        if "/usr/local/bin" not in currentPathVariables:
            currentPathVariables.append("/usr/local/bin")
            os.environ["PATH"] = os.pathsep.join(currentPathVariables)
            debug_log("Added /usr/local/bin to path")

        # try add NVM path
        nvmPath = os.path.join(os.path.expanduser("~"), ".nvm")
        if os.path.exists(nvmPath):
            installed_versions_directory = nvmPath + "/versions/node"
            if os.path.exists(installed_versions_directory):
                for version in os.listdir(installed_versions_directory):
                    if version.startswith("v"):
                        majorVersion = version[1:3]
                        debug_log("Found NVM version", version, " → ", majorVersion)
                        # only add supported versions to the search path
                        if majorVersion == "16" or majorVersion == "18" or majorVersion == "20":
                            path = os.path.join(installed_versions_directory, version, "bin")
                            if os.path.exists(path):
                                if path not in currentPathVariables:
                                    currentPathVariables.append(path)
                                    os.environ["PATH"] = os.pathsep.join(currentPathVariables)
                                    debug_log("Added NVM path", path)

    pass

__FIX_PATH_VARIABLES()



did_find_any_node_version = False
last_node_version_result = None
last_node_version_time = 0

def tryGetNodeVersion(force:bool = False) -> str | None:
    try:
        global last_node_version_time
        global last_node_version_result
        if force == False:
            if last_node_version_time > time.time() - 5:
                return last_node_version_result
        last_node_version_time = time.time()

        global did_find_any_node_version
        nodeCommand = getCommand("node") + " -v"
        if not did_find_any_node_version:
            debug_log(f"Request node version with command \"{nodeCommand}\"")
        # set to blender addon dir (otherwise current dir could not exist anymore and then the command fails)
        os.chdir(os.path.dirname(__file__))
        result = subprocess.run(nodeCommand, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            last_node_version_result = decode_text(result.stdout).strip()
            if not did_find_any_node_version:
                debug_log("Request node version result:", last_node_version_result)
            return last_node_version_result
        res = str(result.returncode) + ": " + decode_text(result.stderr).strip()
        debug_log("Request node version failed", res)
        last_node_version_result = None
        return None 
    except:
        pass
    return None

def getMinSupportedNodeVersion():
    return "18.0"

def getMaxSupportedNodeVersion():
    return "22 LTS"

def hasSupportedNodeVersionInstalled():
    global did_find_any_node_version
    version = tryGetNodeVersion()
    if version is None:
        return False
    if version.startswith("v"):
        version = version[1:]
    parts = version.split(".")
    if len(parts) < 2:
        return False
    major = int(parts[0])
    minor = int(parts[1])
    did_find_any_node_version = True
    if major < 16:
        return False
    if major == 16 and minor < 13:
        return False
    return True
