# /*
#  * Copyright (C) 2020, KylinSoft Co., Ltd.
#  *
#  * This program is free software: you can redistribute it and/or modify
#  * it under the terms of the GNU General Public License as published by
#  * the Free Software Foundation, either version 3 of the License, or
#  * (at your option) any later version.
#  *
#  * This program is distributed in the hope that it will be useful,
#  * but WITHOUT ANY WARRANTY; without even the implied warranty of
#  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  * GNU General Public License for more details.
#  *
#  * You should have received a copy of the GNU General Public License
#  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
#  */

import os
import json
import logging
DEFAULT_SETTINGS = "/etc/kylin-system-updater/settings-default.json"
OPT_DEFAULT_SETTINGS = "/opt/update-module/current/etc/kylin-system-updater/settings-default.json"
RUN_SETTINGS = "/var/cache/kylin-system-updater/settings.json"

class JSONConfig:
    def __init__(self, settings_files=None):
        self.settings_files = settings_files or []
        self.configs = {}
        self.skip_log = {"history", "update_history", "system","active_revision"}

        # 初始化时加载一次
        self.load()

    # -------------------------
    # 核心：配置加载与刷新
    # -------------------------
    def load(self):
        """从所有配置文件重新加载配置（后者覆盖前者）"""
        merged = {}
        for file in self.settings_files:
            try:
                with open(file, "r") as f:
                    data = json.load(f)
                    if isinstance(data, dict):
                        merged.update(data)
            except Exception as e:
                pass

        self.configs = merged

    def reload(self):
        self.load()

    # -------------------------
    # Dict-like 操作
    # -------------------------
    def get(self, key, default=None):
        return self.configs.get(key, default)

    def set(self, key, value):
        self.__setitem__(key, value)

    def __getitem__(self, key):
        return self.configs[key]

    def __setitem__(self, key, value):
        if key not in self.skip_log:
            logging.info(f"Settings: set '{key}' = '{value}'")
        self.configs[key] = value
        self.save()

    def __iter__(self):
        return iter(self.configs)

    def items(self):
        return self.configs.items()

    def keys(self):
        return self.configs.keys()

    def values(self):
        return self.configs.values()

    def update(self, new_data):
        if not isinstance(new_data, dict):
            raise TypeError("update() expects a dictionary")
        self.configs.update(new_data)
        self.save()

    def as_dict(self):
        return dict(self.configs)

    # -------------------------
    # 保存配置
    # -------------------------
    def save(self):
        """只保存到主配置文件 settings_files[0]"""
        if not self.settings_files:
            raise RuntimeError("No settings file provided for saving configuration.")

        file = self.settings_files[0]
        os.makedirs(os.path.dirname(file), exist_ok=True)

        try:
            with open(file, "w") as f:
                json.dump(self.configs, f, indent=4, ensure_ascii=False)
        except Exception as e:
            pass


"""
 使用方式：
    获取值
    1、settings.get("name")  == "Bob"
    2、settings.get("name1", "default") == "default"
    3、settings.get("local",{}).get("pre",{}).get("en") == "xxxxx"

    设置值
    1、settings.set("name", "Bob")
    # 仅支持一级设置
    2、settings["name"] = "Bob"
    3、支持多级设置
        a、locals = settings.get("local",{})
        b、locals["pre"]["en"] = "xxxxx"

    保存
    settings.save()
"""
# 配置文件读取的顺序，/opt自更新的配置优先级最高-> /etc -> /var/cache下面的配置文件 优先级高的覆盖优先级低的
G_settings = JSONConfig(
    settings_files=[
        RUN_SETTINGS,
        DEFAULT_SETTINGS,
        OPT_DEFAULT_SETTINGS,
    ]
)