"""
常用工具函数
提供 YAML、JSON 等常用操作的便捷方法
"""
import os
from io import StringIO
from cpbox.tool import file
from tibase.core import cls


class YAMLInitializer(cls.Singleton):
    """YAML 实例初始化器（使用 SIP 模式）"""

    def _init_once(self):
        """初始化 YAML 实例，只执行一次"""
        from ruamel.yaml import YAML
        self.yaml = YAML(typ='rt')
        self.yaml.indent(mapping=2, sequence=4, offset=2)
        self.yaml.allow_unicode = True
        self.yaml.sort_keys = False
        self.yaml.default_flow_style = False
        self.yaml.default_style = None

yaml = YAMLInitializer().yaml

def pyaml(data) -> str:
    """将数据转换为 YAML 字符串"""
    stream = StringIO()
    yaml.dump(data, stream=stream)
    return stream.getvalue()


def pjson(data):
    """将数据转换为 JSON 字符串（延迟加载）"""
    import json
    return json.dumps(data, ensure_ascii=False, indent=2)


def load_yaml_file(fn, fallback=None):
    """从 YAML 文件加载数据（延迟加载）"""
    if not os.path.isfile(fn):
        return fallback
    data = None
    with open(fn, 'r', encoding='utf-8') as f:
        data = yaml.load(f)
    return data if data is not None else fallback


def dump_yaml_file(fn, data):
    """将数据写入 YAML 文件（延迟加载）"""
    file.ensure_dir_for_file(str(fn))
    with open(fn, 'w', encoding='utf-8') as outfile:
        yaml.dump(data, outfile)

def load_json_file(fn, fallback=None):
    """从 JSON 文件加载数据（延迟加载）"""
    import json
    if not os.path.isfile(fn):
        return fallback
    try:
        with open(fn, 'r', encoding='utf-8') as f:
            data = json.load(f)
        return data if data is not None else fallback
    except Exception:
        return fallback


def dump_json_file(fn, data):
    """将数据写入 JSON 文件（延迟加载）"""
    import json
    file.ensure_dir_for_file(str(fn))
    with open(fn, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)