import os
from pathlib import Path

from appdirs import user_data_dir

_DIR_APP_NAME = "mineru-flow"
_DATA_DIR_ENV_KEYS = ("MINERU_FLOW_DATA_DIR", "BASE_DATA_DIR")


def _get_data_dir_override() -> str | None:
    for key in _DATA_DIR_ENV_KEYS:
        value = os.getenv(key)
        if value:
            return value
    return None


def get_data_dir() -> str:
    override = _get_data_dir_override()
    if override:
        data_dir = Path(override).expanduser()
    else:
        data_dir = Path(user_data_dir(appname=_DIR_APP_NAME))
    data_dir.mkdir(parents=True, exist_ok=True)
    return str(data_dir.resolve())
