#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import os
import sys

FILE_PATH = "/home/QT_ADAS/settings/deviceConfig.json"

# 要替换的 VideoChnnlSetupArr 新内容（直接写成 JSON 字符串）
NEW_VIDEO_CHNNL_JSON = r'''
{
  "Source": "Master",
  "Type": "Config",
  "Content": {
    "Thumbnail": {
      "Channel": 1,
      "Width": 192,
      "Height": 108,
      "Format": "nv12",
      "StoragePath": "/dev",
      "StorageFile": "null"
    },
    "FrameMerge": {
      "Channel": 0,
      "Width": 1920,
      "Height": 1080,
      "Format": "nv12",
      "Framerate": 30,
      "Layout": {
        "Mode": 2
      },
      "Watermark": {
        "FontFile": "/opt/HXKJ/RENC/resource/font/SourceCodePro-Regular.ttf",
        "FontSize": 24,
        "PosX": 70,
        "PosY": 30,
        "Foreground": {
          "R": 255,
          "G": 0,
          "B": 0,
          "A": 0.7
        },
        "Background": {
          "R": 255,
          "G": 0,
          "B": 0,
          "A": 0.7
        }
      }
    },
    "Camera": [
      {
        "Enabled": true,
        "Use": "主摄",
        "Channel": 1,
        "Device": "/dev/video22",
        "Type": "AHD",
        "Width": 1920,
        "Height": 1080,
        "Framerate": 30,
        "Format": "nv12",
        "Watermark": {
          "FontFile": "/opt/HXKJ/RENC/resource/font/SourceCodePro-Regular.ttf",
          "FontSize": 24,
          "PosX": 70,
          "PosY": 30,
          "Foreground": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          },
          "Background": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          }
        }
      },
      {
        "Enabled": true,
        "Use": "仪表",
        "Channel": 2,
        "Device": "/dev/video24",
        "Type": "AHD",
        "Width": 1280,
        "Height": 720,
        "Framerate": 25,
        "Format": "nv12",
        "Watermark": {
          "FontFile": "/opt/HXKJ/RENC/resource/font/SourceCodePro-Regular.ttf",
          "FontSize": 24,
          "PosX": 70,
          "PosY": 30,
          "Foreground": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          },
          "Background": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          }
        }
      },
      {
        "Enabled": true,
        "Use": "中控",
        "Channel": 3,
        "Device": "/dev/video25",
        "Type": "AHD",
        "Width": 1280,
        "Height": 720,
        "Framerate": 25,
        "Format": "nv12",
        "Watermark": {
          "FontFile": "/opt/HXKJ/RENC/resource/font/SourceCodePro-Regular.ttf",
          "FontSize": 24,
          "PosX": 70,
          "PosY": 30,
          "Foreground": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          },
          "Background": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          }
        }
      },
      {
        "Enabled": true,
        "Use": "左轮",
        "Channel": 5,
        "Device": "/dev/video11",
        "Type": "AHD",
        "Width": 1280,
        "Height": 720,
        "Framerate": 25,
        "Format": "nv12",
        "Watermark": {
          "FontFile": "/opt/HXKJ/RENC/resource/font/SourceCodePro-Regular.ttf",
          "FontSize": 24,
          "PosX": 70,
          "PosY": 30,
          "Foreground": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          },
          "Background": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          }
        }
      },
      {
        "Enabled": true,
        "Use": "右轮",
        "Channel": 6,
        "Device": "/dev/video12",
        "Type": "AHD",
        "Width": 1280,
        "Height": 720,
        "Framerate": 25,
        "Format": "nv12",
        "Watermark": {
          "FontFile": "/opt/HXKJ/RENC/resource/font/SourceCodePro-Regular.ttf",
          "FontSize": 24,
          "PosX": 70,
          "PosY": 30,
          "Foreground": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          },
          "Background": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          }
        }
      },
      {
        "Enabled": true,
        "Use": "脚踏",
        "Channel": 4,
        "Device": "/dev/video13",
        "Type": "AHD",
        "Width": 1280,
        "Height": 720,
        "Framerate": 25,
        "Format": "nv12",
        "Watermark": {
          "FontFile": "/opt/HXKJ/RENC/resource/font/SourceCodePro-Regular.ttf",
          "FontSize": 24,
          "PosX": 70,
          "PosY": 30,
          "Foreground": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          },
          "Background": {
            "R": 255,
            "G": 0,
            "B": 0,
            "A": 0.7
          }
        }
      }
    ]
  }
}
'''

def main():
    # 1. 检查文件是否存在
    if not os.path.isfile(FILE_PATH):
        print(f"错误：文件未找到 -> {FILE_PATH}")
        sys.exit(1)

    # 2. 读取原始 JSON
    with open(FILE_PATH, "r", encoding="utf-8") as f:
        try:
            data = json.load(f)
        except json.JSONDecodeError as e:
            print(f"JSON 解析错误: {e}")
            sys.exit(1)

    # 3. 确保 HardwareConfig 存在
    hw_config = data.get("HardwareConfig")
    if hw_config is None:
        print("错误：JSON 中缺少 'HardwareConfig' 键")
        sys.exit(1)

    # 4. 修改 Can0Setup ~ Can5Setup 下的 Baudrate
    can_keys = [f"Can{i}Setup" for i in range(6)]
    for key in can_keys:
        if key in hw_config:
            can_setup = hw_config[key]
            if isinstance(can_setup, dict):
                # 将 Baudrate 设为字符串 "500K"
                can_setup["Baudrate"] = "500K"
                print(f"已修改 {key}.Baudrate = \"500K\"")
            else:
                print(f"警告：{key} 不是对象（可能是其他类型），跳过")
        else:
            print(f"警告：{key} 不存在，已跳过（未创建）")

    # 5. 替换 VideoChnnlSetupArr
    # 从 JSON 字符串解析为新对象
    try:
        new_video_chnnl = json.loads(NEW_VIDEO_CHNNL_JSON)
    except json.JSONDecodeError as e:
        print(f"新 VideoChnnlSetupArr JSON 字符串解析错误: {e}")
        sys.exit(1)

    hw_config["VideoChnnlSetupArr"] = new_video_chnnl
    print("已替换 VideoChnnlSetupArr 的值")
    

    log_record = data.get("UnconditionalNormalLogRecord")
    if log_record is None:
        print("警告：JSON 中缺少 'UnconditionalNormalLogRecord' 键，无法修改日志记录设置")
        sys.exit(1)
    
    log_record["Enable"] = True
    print(f"已设置 UnconditionalNormalLogRecord.Enable = true")



    # 6. 写回文件（先备份）
    backup_path = FILE_PATH + ".bak"
    try:
        # 复制原文件作为备份（如果已存在则覆盖）
        with open(FILE_PATH, "r", encoding="utf-8") as src:
            with open(backup_path, "w", encoding="utf-8") as dst:
                dst.write(src.read())
        print(f"备份已保存: {backup_path}")
    except Exception as e:
        print(f"警告：创建备份失败 ({e})，但将继续写回")

    # 写入修改后的数据（缩进 2 空格，保留中文）
    with open(FILE_PATH, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    print("修改已写入: " + FILE_PATH)

if __name__ == "__main__":
    main()






