import psutil
import pytest

from clarabot_nano_tests.core.utility.common import start_core_expect_error
from clarabot_nano_tests.core.utility.config import (
    check_configs_empty,
    get_configs,
    check_configs_default,
)
from clarabot_nano_tests.testing.file import write_yaml
from clarabot_nano_tests.testing.process import pypopen


def test_core_bootstrap_config_error_create(reset_user_app_config_dir, reset_user_app_data_dir):
    check_configs_empty(reset_user_app_config_dir)
    reset_user_app_data_dir.mkdir(parents=True, exist_ok=True)
    write_yaml(str(reset_user_app_data_dir / "logs"), {"test": "me"})
    start_core_expect_error(
        ["--headless"],
        "Exception: Could not create default configuration",
    )
    assert get_configs(reset_user_app_config_dir) == {"local": None}


def test_core_bootstrap_config_error_root(reset_user_app_config_dir, reset_user_app_data_dir, dev_nano_root_dir):
    check_configs_empty(reset_user_app_config_dir)
    start_core_expect_error(
        ["--headless"],
        "Exception: Without Nano bundle root (CBNANO_ROOT), the local.solr_bundle_dir config must be set",
        timeout=5,
    )
    check_configs_default(reset_user_app_config_dir, reset_user_app_data_dir)
    # check if the empty/broken local file permits proper setup
    with pypopen(["clarabot_nano"], env={"CBNANO_ROOT": str(dev_nano_root_dir)}) as p:
        with pytest.raises(psutil.TimeoutExpired):
            p.wait(5)
    assert p.returncode == 0
    check_configs_default(reset_user_app_config_dir, reset_user_app_data_dir)


def test_core_bootstrap_config_create(reset_user_app_config_dir, reset_user_app_data_dir, dev_nano_root_dir):
    check_configs_empty(reset_user_app_config_dir)
    with pypopen(["clarabot_nano"], env={"CBNANO_ROOT": str(dev_nano_root_dir)}) as p:
        with pytest.raises(psutil.TimeoutExpired):
            p.wait(5)
    assert p.returncode == 0
    check_configs_default(reset_user_app_config_dir, reset_user_app_data_dir)
