#!/usr/bin/python3
import sys
import os
import configparser
import sqlite3
import subprocess
import getpass
import json
from json import JSONDecodeError
import re
from datetime import datetime,timedelta
import shutil

def merge_json_files(file1, file2):
    """
    将file1中有而file2中没有的数据添加到file2中
    支持嵌套字典和列表的递归合并
    """
    try:
        # 1. 读取并解析JSON文件
        with open(file1, 'r', encoding='utf-8') as f1:
            data1 = json.load(f1)
        
        with open(file2, 'r', encoding='utf-8') as f2:
            data2 = json.load(f2)
        
        # 2. 递归合并函数（核心逻辑）
        def recursive_merge(target, source):
            """将source中有而target中没有的数据合并到target"""
            if isinstance(source, dict) and isinstance(target, dict):
                for key, value in source.items():
                    if key not in target:
                        target[key] = value  # 添加新键
                    else:
                        # 递归处理嵌套字典
                        target[key] = recursive_merge(target[key], value)
            
            elif isinstance(source, list) and isinstance(target, list):
                # 合并列表（只添加不存在的新元素）
                for item in source:
                    if item not in target:
                        target.append(item)
            
            # 其他类型（如字符串、数字）不处理
            return target
        
        # 3. 执行合并
        merged_data = recursive_merge(data2, data1)
        
        # 4. 备份原始文件后写入结果
        backup_path = f"{file2}.bak"
        os.rename(file2, backup_path)  # 创建备份
        
        with open(file2, 'w', encoding='utf-8') as f:
            json.dump(merged_data, f, ensure_ascii=False, indent=2)
        
        return True, "合并成功，原始文件已备份至: " + backup_path
    
    except FileNotFoundError as e:
        return False, f"文件不存在: {str(e)}"
    except json.JSONDecodeError as e:
        return False, f"JSON解析失败: {str(e)}"
    except PermissionError as e:
        return False, f"文件权限不足: {str(e)}"
    except Exception as e:
        return False, f"未知错误: {str(e)}"

if __name__ == "__main__":
    try:
        source_strategy_config_file="/usr/share/kylin-system-updater/kylin-update-strategy.json"
        if(os.path.exists("/opt/update-module/current/usr/share/kylin-system-updater/kylin-update-strategy.json")):
            source_strategy_config_file="/opt/update-module/current/usr/share/kylin-system-updater/kylin-update-strategy.json"
        print("kylin-update-strategy.json path:%s"%(source_strategy_config_file))
        if(not os.path.exists("/var/lib/unattended-upgrades/kylin-update-strategy.json")):
            shutil.copyfile(source_strategy_config_file,"/var/lib/unattended-upgrades/kylin-update-strategy.json")
        success, message = merge_json_files(source_strategy_config_file, "/var/lib/unattended-upgrades/kylin-update-strategy.json")
        print(f"{'成功' if success else '失败'}: {message}")
    except Exception as e:
        print(e)
    os._exit(0)


