# Path: clouddq/utils.py
# def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None:
#     """
# 
#     Args:
#       value: typing.Any:
#       error_msg: str:
# 
#     Returns:
# 
#     """
#     if not value:
#         raise ValueError(error_msg)
# 
# Path: clouddq/utils.py
# def load_yaml(file_path: Path, key: str = None) -> typing.Any:
#     with file_path.open() as f:
#         yaml_configs = yaml.safe_load(f)
#     if not yaml_configs:
#         return dict()
#     output = yaml_configs.get(key, dict())
#     if type(output) == dict:
#         return {key.upper(): value for key, value in output.items()}
#     elif type(output) == list:
#         return [item.upper() for item in output]
#     elif type(output) == str:
#         return output
#     else:
#         raise RuntimeError(
#             f"CloudDQ configs file `{file_path}` has empty config node type `{key}:`. "
#             "Please remove the node if it is not being used."
#         )
# 
# Path: clouddq/utils.py
# @contextlib.contextmanager
# def working_directory(path):
#     """Changes working directory and returns to previous on exit."""
#     prev_cwd = Path.cwd()
#     os.chdir(path)
#     try:
#         yield
#     finally:
#         os.chdir(prev_cwd)


from pathlib import Path
from pprint import pformat
from typing import Dict
from typing import Optional
from dbt.main import main as dbt
from clouddq.utils import assert_not_none_or_empty
from clouddq.utils import load_yaml
from clouddq.utils import working_directory
import json
import logging
import os
import re


def extract_dbt_env_var(text: str) -> str:
    var_env = re.search(ENV_VAR_PATTERN, text).group(1)
    var_env = [x.strip().strip("'\"") for x in var_env.split(",")]
    enrironment_variable = var_env.pop(0)
    default_value = None
    if var_env:
        default_value = var_env.pop()
    value = os.environ.get(enrironment_variable, default_value)
    assert_not_none_or_empty(
        value, f"Enviromment variable not found for dbt env_var variable: {text}"
    )
    return value


def get_bigquery_dq_summary_table_name(
    dbt_path: Path,
    dbt_profiles_dir: Path,
    environment_target: str,
    table_name: str = "dq_summary",
) -> str:
    # Get bigquery project and dataset for dq_summary table names
    dbt_project_path = dbt_path.joinpath("dbt_project.yml")
    if not dbt_project_path.is_file():
        raise ValueError(
            "Not able to find 'dbt_project.yml' config file at "
            "input path {dbt_project_path}."
        )
    dbt_profiles_key = load_yaml(dbt_project_path, "profile")

# Path: clouddq/utils.py
# def assert_not_none_or_empty(value: typing.Any, error_msg: str) -> None:
#     """
# 
#     Args:
#       value: typing.Any:
#       error_msg: str:
# 
#     Returns:
# 
#     """
#     if not value:
#         raise ValueError(error_msg)
# 
# Path: clouddq/utils.py
# def load_yaml(file_path: Path, key: str = None) -> typing.Any:
#     with file_path.open() as f:
#         yaml_configs = yaml.safe_load(f)
#     if not yaml_configs:
#         return dict()
#     output = yaml_configs.get(key, dict())
#     if type(output) == dict:
#         return {key.upper(): value for key, value in output.items()}
#     elif type(output) == list:
#         return [item.upper() for item in output]
#     elif type(output) == str:
#         return output
#     else:
#         raise RuntimeError(
#             f"CloudDQ configs file `{file_path}` has empty config node type `{key}:`. "
#             "Please remove the node if it is not being used."
#         )
# 
# Path: clouddq/utils.py
# @contextlib.contextmanager
# def working_directory(path):
#     """Changes working directory and returns to previous on exit."""
#     prev_cwd = Path.cwd()
#     os.chdir(path)
#     try:
#         yield
#     finally:
#         os.chdir(prev_cwd)


# Path: clouddq/runners/dbt/dbt_utils.py
from pathlib import Path
from pprint import pformat
from typing import Dict
from typing import Optional
from dbt.main import main as dbt
from clouddq.utils import assert_not_none_or_empty
from clouddq.utils import load_yaml
from clouddq.utils import working_directory
import json
import logging
import os
import re



def extract_dbt_env_var(text: str) -> str:
    var_env = re.search(ENV_VAR_PATTERN, text).group(1)
    var_env = [x.strip().strip("'\"") for x in var_env.split(",")]
    enrironment_variable = var_env.pop(0)
    default_value = None
    if var_env:
        default_value = var_env.pop()
    value = os.environ.get(enrironment_variable, default_value)
    assert_not_none_or_empty(
        value, f"Enviromment variable not found for dbt env_var variable: {text}"
    )
    return value


def get_bigquery_dq_summary_table_name(
    dbt_path: Path,
    dbt_profiles_dir: Path,
    environment_target: str,
    table_name: str = "dq_summary",
) -> str:
    # Get bigquery project and dataset for dq_summary table names
    dbt_project_path = dbt_path.joinpath("dbt_project.yml")
    if not dbt_project_path.is_file():
        raise ValueError(
            "Not able to find 'dbt_project.yml' config file at "
            "input path {dbt_project_path}."
        )
    dbt_profiles_key = load_yaml(dbt_project_path, "profile")

    dbt_profiles_config = load_yaml(dbt_profiles_dir / "profiles.yml", dbt_profiles_key)