import logging
import os
import shutil
import sys
from pathlib import Path
from time import gmtime
from typing import Any, Final

from lang_main.io import load_toml_config

logging.Formatter.converter = gmtime
LOG_FMT: Final[str] = '%(asctime)s | %(module)s:%(levelname)s | %(message)s'
LOG_DATE_FMT: Final[str] = '%Y-%m-%d %H:%M:%S +0000'
logging.basicConfig(
    stream=sys.stdout,
    format=LOG_FMT,
    datefmt=LOG_DATE_FMT,
)

CONFIG_FILENAME: Final[str] = 'lang_main_config.toml'
USE_INTERNAL_CONFIG: Final[bool] = False
pkg_dir = Path(__file__).parent
cfg_path_internal = (pkg_dir / CONFIG_FILENAME).resolve()
# caller_file = Path(inspect.stack()[-1].filename)
# CALLER_PATH: Final[Path] = caller_file.parent.resolve()

# load config data: internal/external
if USE_INTERNAL_CONFIG:
    loaded_cfg = load_toml_config(path_to_toml=cfg_path_internal)
else:
    cfg_path_external = (Path.cwd() / CONFIG_FILENAME).resolve()
    if not cfg_path_external.exists():
        shutil.copy(cfg_path_internal, cfg_path_external)
        sys.exit(
            (
                'No config file was found. A new one with default values was created '
                'in the execution path. Please fill in the necessary values and '
                'restart the programm.'
            )
        )
    # raise NotImplementedError("External config data not implemented yet.")
    loaded_cfg = load_toml_config(path_to_toml=cfg_path_external)

CONFIG: Final[dict[str, Any]] = loaded_cfg.copy()

# append Graphviz binary folder to system path if not already contained
if sys.platform == 'win32':
    path = Path(r'C:\Program Files\Graphviz\bin')
    if path.is_dir() and str(path).lower() not in os.environ['PATH'].lower():
        os.environ['PATH'] += f';{path}'
