from __future__ import annotations

import logging
import os
import tomllib
from pathlib import Path
from typing import Any, Final

from lang_main.errors import LangMainConfigNotFoundError

# from lang_main.loggers import logger_config as logger
from lang_main.search import search_cwd, search_iterative

_has_py4cyto: bool = True
try:
    import py4cytoscape as p4c
except ImportError:
    _has_py4cyto = False

# ** external packages config
# ** Huggingface Hub caching
os.environ['HF_HUB_DISABLE_SYMLINKS_WARNING'] = '1'

# ** py4cytoscape config
if _has_py4cyto:
    p4c.set_summary_logger(False)
    p4c.py4cytoscape_logger.detail_logger.setLevel('ERROR')
    p4c.py4cytoscape_logger.detail_logger.removeHandler(
        p4c.py4cytoscape_logger.detail_handler
    )
    p4c.py4cytoscape_logger.detail_logger.addHandler(logging.NullHandler())

# ** lang-main config
# ENV variable: LANG_MAIN_BASE_FOLDERNAME
BASE_FOLDERNAME: Final[str] = os.environ.get('LANG_MAIN_BASE_FOLDERNAME', 'lang-main')
CONFIG_FILENAME: Final[str] = 'lang_main_config.toml'
CYTO_STYLESHEET_FILENAME: Final[str] = r'cytoscape_config/lang_main.xml'
PKG_DIR: Final[Path] = Path(__file__).parent
STOP_FOLDER: Final[str] = os.environ.get('LANG_MAIN_STOP_SEARCH_FOLDERNAME', 'lang-main')


def load_toml_config(
    path_to_toml: str | Path,
) -> dict[str, Any]:
    with open(path_to_toml, 'rb') as f:
        data = tomllib.load(f)
    print('Loaded TOML config file successfully.', flush=True)

    return data


# ** load config data: internal/external
def get_config_paths(
    root_folder: Path,
    cfg_name: str,
    cyto_stylesheet_name: str,
) -> tuple[Path, Path]:
    cfg_path_internal = (root_folder / cfg_name).resolve()
    cyto_stylesheet_path = (root_folder / cyto_stylesheet_name).resolve()

    return cfg_path_internal, cyto_stylesheet_path


def load_cfg(
    starting_path: Path,
    glob_pattern: str,
    stop_folder_name: str | None,
    lookup_cwd: bool = False,
) -> dict[str, Any]:
    """Look for configuration file. Internal configs are not used any more because
    the library behaviour is only guaranteed by external configurations.

    Parameters
    ----------
    starting_path : Path
        path to start for the lookup
    glob_pattern : str
        pattern of the config file naming scheme
    stop_folder_name : str | None
        folder name at which the lookup should stop, the parent folder
        is also searched, e.g.
        if starting_path is path/to/start/folder and stop_folder_name is 'to',
        then path/ is also searched

    Returns
    -------
    dict[str, Any]
        loaded config file

    Raises
    ------
    LangMainConfigNotFoundError
        if no config file was found
    """
    cfg_path: Path | None = None
    if lookup_cwd:
        print('Looking for cfg file in CWD.', flush=True)
        cfg_path = search_cwd(glob_pattern)

    if cfg_path is None:
        print(
            (
                f'Looking iteratively for config file. Start: {starting_path}, '
                f'stop folder: {stop_folder_name}'
            ),
            flush=True,
        )
        cfg_path = search_iterative(
            starting_path=starting_path,
            glob_pattern=glob_pattern,
            stop_folder_name=stop_folder_name,
        )

    if cfg_path is None:
        raise LangMainConfigNotFoundError('Config file was not found.')

    config = load_toml_config(path_to_toml=cfg_path)
    print(f'Loaded config from: >>{cfg_path}<<')

    return config.copy()
