# -*- coding: utf-8 -*-
"""
底层 YAML 读写与深合并，不依赖默认路径。供 YamlConfigManager 及模块级 API 使用。
"""

import copy
from pathlib import Path
from typing import Any, Dict, Optional

import yaml


def deep_merge(base: Dict[str, Any], updates: Dict[str, Any]) -> Dict[str, Any]:
    """
    深合并：用 updates 中的键覆盖或递归合并 base 对应节点；未在 updates 中出现的键保留原样。
    列表采用「按 key 覆盖」策略：若 updates 中某 key 对应 list，则整体替换 base 中该 key。
    """
    result = copy.deepcopy(base)
    for key, up_val in updates.items():
        if key not in result:
            result[key] = copy.deepcopy(up_val)
        elif isinstance(result[key], dict) and isinstance(up_val, dict):
            result[key] = deep_merge(result[key], up_val)
        else:
            result[key] = copy.deepcopy(up_val)
    return result


def read_yaml_file(yaml_path: str) -> dict:
    """
    读取任意 YAML 文件，返回字典。文件不存在或空/非合法 YAML 时返回空 dict。
    """
    path = Path(yaml_path)
    if not path.exists() or not path.is_file():
        return {}
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = yaml.safe_load(f)
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}


def update_yaml_file(
    yaml_path: str,
    updates: dict,
    output_path: Optional[str] = None,
) -> None:
    """
    读取 yaml_path 对应文件，用 updates 深合并后写回。
    output_path is None 时写回 yaml_path；否则写出到 output_path（新建或覆盖）。
    """
    path = Path(yaml_path)
    base = read_yaml_file(yaml_path)
    merged = deep_merge(base, updates)
    out = Path(output_path) if output_path is not None else path
    out.parent.mkdir(parents=True, exist_ok=True)
    with open(out, "w", encoding="utf-8") as f:
        yaml.dump(merged, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
