import json
import re
import os
from pathlib import Path


class ParamsManager:
    
    def __init__(self, params_dir='params'):
        self.params_dir = params_dir
        self._ensure_dir_exists()
    
    def _ensure_dir_exists(self):
        Path(self.params_dir).mkdir(parents=True, exist_ok=True)
    
    # def save(self, params, filename):
    #     if not filename.endswith('.json'):
    #         filename = filename + '.json'
    #
    #     filepath = os.path.join(self.params_dir, filename)
    #
    #     with open(filepath, 'w', encoding='utf-8') as f:
    #         json.dump(params, f, indent=2, separators=(',', ':'), ensure_ascii=False)

    def save(self, params, filename):
        if not filename.endswith(".json"):
            filename = filename + ".json"

        filepath = os.path.join(self.params_dir, filename)

        # 1. 正常生成带有标准缩进的 JSON 字符串
        raw_json = json.dumps(params, indent=2, ensure_ascii=False)

        # 2. 正则1：将简单的纯数值/字符串列表压缩成单行 [100, 200, 300]
        def _flatten_array(match):
            content = match.group(1)
            if "{" in content:  # 如果包含字典对象，不在这里处理
                return match.group(0)
            items = [item.strip() for item in content.split(",") if item.strip()]
            return "[" + ", ".join(items) + "]"

        compact_json = re.sub(r"\[([\s\S]*?)\]", _flatten_array, raw_json)

        # 3. 正则2：将列表里的单层字典对象压缩成单行 {"a": 1, "b": 2}
        def _flatten_object(match):
            content = match.group(1)
            if "{" in content or "[" in content:  # 包含嵌套对象的字典不压缩
                return match.group(0)
            # 清理换行和多余空格，格式化为单行
            lines = [line.strip() for line in content.split("\n") if line.strip()]
            return "{ " + " ".join(lines) + " }"

        final_json = re.sub(r"\{([^{}\[\]]*?)\}", _flatten_object, compact_json)

        with open(filepath, "w", encoding="utf-8") as f:
            f.write(final_json)




    
    def load(self, filename):
        if not filename.endswith('.json'):
            filename = filename + '.json'
        
        filepath = os.path.join(self.params_dir, filename)
        
        with open(filepath, 'r', encoding='utf-8') as f:
            params = json.load(f)
        return params



    
# from ParamsManager import ParamsManager

# # 创建参数管理器实例
# pm = ParamsManager('params')  # 参数保存在 params 文件夹中

# # 保存单个参数
# pm.save(params, 'AWG_NCO')  # 自动添加 .json 后缀

# # 加载单个参数
# params = pm.load('AWG_NCO')


