import sys
from pathlib import Path
from typing import Dict, Any

# 尝试导入 TOML 解析/写入库，处理缺失情况
try:
    import tomli as toml_parser
except ImportError:
    try:
        import tomllib as toml_parser   # Python 3.11+
    except ImportError:
        toml_parser = None

try:
    import tomli_w
except ImportError:
    tomli_w = None


def _ensure_toml_support():
    """检查 TOML 解析/写入库是否可用，否则报错退出"""
    if toml_parser is None:
        print("❌ 错误：未找到 TOML 解析库。请安装 tomli 或使用 Python 3.11+。", file=sys.stderr)
        print("   安装命令：pip install tomli", file=sys.stderr)
        sys.exit(1)
    if tomli_w is None:
        print("❌ 错误：未找到 TOML 写入库 tomli-w。", file=sys.stderr)
        print("   安装命令：pip install tomli-w", file=sys.stderr)
        sys.exit(1)


def load_toml(path: Path) -> Dict[str, Any]:
    """读取 TOML 文件并返回字典"""
    _ensure_toml_support()
    with open(path, 'rb') as f:
        return toml_parser.load(f)


def dump_toml(data: Dict[str, Any], path: Path) -> None:
    """将字典写入 TOML 文件"""
    _ensure_toml_support()
    with open(path, 'wb') as f:
        tomli_w.dump(data, f)