import sys
from importlib import reload
from pathlib import Path
from unittest.mock import patch

from lang_main import config


def test_p4c_dependency():
    assert config._has_py4cyto
    with patch.dict(sys.modules, {'py4cytoscape': None}):
        reload(sys.modules['lang_main.config'])
        assert not config._has_py4cyto


def test_load_config():
    toml_path = config.PKG_DIR / 'lang_main_config.toml'
    loaded_cfg = config.load_toml_config(toml_path)
    assert loaded_cfg['paths']['models'] == './lang-models'


def test_get_config_path():
    pkg_dir = config.PKG_DIR
    filename = config.CONFIG_FILENAME
    cyto_stylesheet_name = config.CYTO_STYLESHEET_FILENAME

    cfg_pth_internal = (pkg_dir / filename).resolve()
    cyto_cfg_pth = (pkg_dir / cyto_stylesheet_name).resolve()

    cfg_internal, cyto_internal = config.get_config_paths(
        root_folder=pkg_dir,
        cfg_name=filename,
        cyto_stylesheet_name=cyto_stylesheet_name,
    )
    assert cfg_internal == cfg_pth_internal
    assert cyto_internal == cyto_cfg_pth


def test_load_cfg_func(monkeypatch, tmp_path):
    monkeypatch.setattr(Path, 'cwd', lambda: tmp_path)
    pkg_dir = config.PKG_DIR
    filename = config.CONFIG_FILENAME
    stop_folder = config.STOP_FOLDER

    cfg_pth_internal = (pkg_dir / filename).resolve()
    ref_config = config.load_toml_config(cfg_pth_internal)
    assert ref_config['paths']['models'] == './lang-models'

    loaded_cfg = config.load_cfg(
        starting_path=pkg_dir,
        glob_pattern=filename,
        stop_folder_name=stop_folder,
        lookup_cwd=False,
    )
    assert loaded_cfg['paths']['models'] == './lang-models'

    loaded_cfg = config.load_cfg(
        starting_path=pkg_dir,
        glob_pattern=filename,
        stop_folder_name=stop_folder,
        lookup_cwd=True,
    )
    assert loaded_cfg['paths']['models'] == './lang-models'
