'''
Helper to resolve simply finding an exe, across OS differences
'''


from opencos import eda_config
from opencos.files import safe_shutil_which
from opencos.utils import macos_utils, vsim_helper, win_utils
from opencos.utils.subprocess_helpers import IS_MACOS, IS_WINDOWS


def get_tool_exe(config: dict, tool: str) -> str:
    '''Returns an exe that can be used for this tool'''

    # Use the macos_utils to resolve that exe.
    # If this is mac, and the tool (in config.tools.TOOLNAME) has
    # macos-app-name defined, then we have to query that.
    # otherwise, we get the first exe listed from config.tools.TOOLNAME
    if IS_MACOS:
        exe = macos_utils.get_tool_exe_from_config(config, tool)

    elif IS_WINDOWS:
        # Note that WSL will not report IS_WINDOWS, will report IS_LINUX,
        # so we don't go down this path (looking in C:\ for LOCALAPPDATA AND
        # PROGRAMFILES) for WSL.
        exe = win_utils.get_tool_exe_from_config(config, tool)

    else:
        tool_cfg = config.get('tools', {}).get(tool, {})
        exe_list = eda_config.tool_get_exe_list(tool=tool, config=config)
        exe = exe_list[0] # pick first one, or tool name


    # Attempt to resolve, compatible for IS_LINUX, IS_WINDOWS,
    # or IS_WINDOWS+WSL:
    exe = safe_shutil_which(exe)

    # special hook for eda_config - tools - TOOLNAME - requires_vsim_helper:
    tool_cfg = config.get('tools', {}).get(tool, {})
    if tool_cfg.get('requires-vsim-helper', False):
        exe = vsim_helper.lookup_exe(tool)

    return exe
