from pathlib import Path

from nanoid import generate


def ensure_file_exists(file_path: str):
    """
    检查文件是否存在，如果不存在则创建一个空文件。
    """
    path = Path(file_path)
    if not path.exists():
        # parents=True: 自动创建不存在的父目录 (如 ./data/config/)
        # exist_ok=True: 防止多线程环境下目录被同时创建导致的冲突
        path.parent.mkdir(parents=True, exist_ok=True)
        # 创建文件
        path.touch(exist_ok=True)


def cuid(size=10):
    """
    生成唯一字符串 cuid，只包含小写字母和数字。默认为 10 位
    """
    return generate("0123456789abcdefghijklmnopqrstuvwxyz", size)


def get_tokenizer(base_model: str):
    try:
        from modelscope import AutoTokenizer
        from modelscope.utils.logger import get_logger
    except ImportError:
        raise ImportError(
            "Detected missing 'modelscope'. This operation requires it. "
            "Install via 'pip install modelscope transformers'"
        )

    logger = get_logger()
    old_level = logger.level

    try:
        logger.setLevel("ERROR")
        return AutoTokenizer.from_pretrained(base_model, local_files_only=True)
    except Exception:
        print(f"Tokenizer not found locally, downloading: {base_model}")
        logger.setLevel("ERROR")
        tokenizer = AutoTokenizer.from_pretrained(base_model, local_files_only=False)
        return tokenizer
    finally:
        logger.setLevel(old_level)
