'''Because > 1 tools use the exe 'code', I don't want to run

`code --list-extensions --show-versionsvsim -version` for every tool that needs
to check if they exist in VScode land.

Instead, eda.py can call this once, and then query if the VScode extension exists when
running opencos.eda.auto_tool_setup(..)
'''

import subprocess

from opencos.files import safe_shutil_which
from opencos.util import debug
from opencos.utils.macos_utils import IS_MACOS, get_macos_tool_info

VSCODE_PATH_INIT_RUN = False
INIT_HAS_RUN = False # pylint: disable=invalid-name
EXTENSIONS = {} # dict of {name: version} for VScode extensions of name

vscode_path = '' # update for macos during init() # pylint: disable=invalid-name

def get_vscode_path() -> str:
    '''Sets global vscode_path if it hasn't been set, returns it'''
    global VSCODE_PATH_INIT_RUN # pylint: disable=global-statement
    global vscode_path          # pylint: disable=global-statement

    if VSCODE_PATH_INIT_RUN:
        return vscode_path

    VSCODE_PATH_INIT_RUN = True

    if vscode_path:
        return vscode_path

    vscode_path = safe_shutil_which('code')

    if not vscode_path and IS_MACOS:
        data = get_macos_tool_info('Visual Studio Code', prefer_exes=['code'])
        if exe := data.get('bin', ''):
            vscode_path = exe

    return vscode_path


vscode_path = get_vscode_path()


def init() -> None:
    '''Sets INIT_HAS_RUN=True (only runs once) and one of TOOL_IS[tool] = True'''
    global INIT_HAS_RUN # pylint: disable=global-statement

    if INIT_HAS_RUN:
        return

    INIT_HAS_RUN = True

    _ = get_vscode_path()

    if not vscode_path:
        return

    proc = None
    try:
        proc = subprocess.run([vscode_path, '--list-extensions', '--show-versions'],
                              capture_output=True, check=False)
    except Exception as e:
        debug(f'vscode --list-extensions --show-versions: exception {e}')

    if proc is None or proc.returncode != 0:
        return

    for line in proc.stdout.decode('utf-8', errors='replace').split('\n'):
        if '@' in line:
            parts = line.split('@')
            if parts[0] and parts[1]:
                EXTENSIONS[parts[0]] = parts[1]
