import requests
import json
import hashlib
import random
import uuid
import os
import time
import datetime
import re
import filecmp
import shutil
        
# 定义读取文件和写入文件的函数
def read_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    return lines

def write_file(file_path, lines):
    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(lines)

# 定义提取中文函数
def extract_chinese(line):
    parts = line.split(' -- ')
    if len(parts) > 2:
        return parts[2].strip()  # 获取中间的中文部分并去除两端空白字符
    return ""

# 定义主函数
def script_8():
    print("\n运行功能15：为文件添加注释")

    # 提示用户输入文件路径
    input_file_path = input("请输入要加注释的文件路径（py或txt）：")
    search_file_path = input("请输入和平代码文件路径：")

    # 读取输入文件
    lines = read_file(input_file_path)
    
    # 读取搜索文件，提前构建一个数字到中文的映射
    number_to_chinese = {}
    search_lines = read_file(search_file_path)
    for line in search_lines:
        parts = line.split(' -- ')
        if len(parts) > 2:
            number = parts[1].strip()
            chinese = parts[2].strip()
            number_to_chinese[number] = chinese

    # 存储最终结果
    modified_lines = []

    # 遍历每一行
    for line in lines:
        # 使用正则表达式提取数字
        numbers = re.findall(r'\d+', line)
        
        # 按照数字顺序构建注释
        comments = []
        for number in numbers:
            if number in number_to_chinese:
                comments.append(number_to_chinese[number])
        
        # 如果有匹配的中文部分，追加到原行的#号后面
        if comments:
            additional_text = '改'.join(comments)
            new_line = line.rstrip('\n') + ' # ' + additional_text + '\n'
            modified_lines.append(new_line)
        else:
            modified_lines.append(line)  # 如果没有匹配的中文部分，保持原样
    
    # 写入修改后的内容回输入文件
    write_file(input_file_path, modified_lines)

    print(f"注释已添加到文件：{input_file_path}")
def read_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    return lines

# 定义读取文件和写入文件的函数
def read_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    return lines

def write_file(file_path, lines):
    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(lines)

# 定义提取中文函数
def extract_chinese(line):
    parts = line.split(' -- ')
    if len(parts) > 2:
        return parts[2].strip()  # 获取中间的中文部分并去除两端空白字符
    return ""

# 定义搜索函数
def search_in_file(search_lines, number):
    search_results = {}
    for line in search_lines:
        if f' {number} ' in line:
            chinese = extract_chinese(line)
            if chinese:
                search_results[number] = chinese
            break
    return search_results

# 定义主函数
def script_13(input_file_path):
    print("\n运行功能13：为文件添加注释")

    # 内置的和平代码文本内容
    peace_code_text = """
    61001 -- 61001 -- 砖
    61002 -- 61002 -- 铁
    61003 -- 61003 -- 电子元件
    61004 -- 61004 -- 复合建材
    9837017 -- 9837017 -- 鎏金花纹铜镜 -- 0x7448
    9837018 -- 9837018 -- 描金彩绘菱花镜 -- 0x7460
    """

    # 读取输入文件
    lines = read_file(input_file_path)
    
    # 提前构建一个数字到中文的映射
    number_to_chinese = {}
    for line in peace_code_text.splitlines():
        parts = line.split(' -- ')
        if len(parts) > 2:
            number = parts[1].strip()
            chinese = parts[2].strip()
            number_to_chinese[number] = chinese

    # 存储最终结果
    modified_lines = []

    # 遍历每一行
    for line in lines:
        # 使用正则表达式提取数字
        numbers = re.findall(r'\d+', line)
        
        # 按照数字顺序构建注释
        comments = []
        for number in numbers:
            if number in number_to_chinese:
                comments.append(number_to_chinese[number])
        
        # 如果有匹配的中文部分，追加到原行的#号后面
        if comments:
            additional_text = '改'.join(comments)
            new_line = line.rstrip('\n') + ' # ' + additional_text + '\n'
            modified_lines.append(new_line)
        else:
            modified_lines.append(line)  # 如果没有匹配的中文部分，保持原样
    
    # 写入修改后的内容回输入文件
    write_file(input_file_path, modified_lines)

    print(f"注释已添加到文件：{input_file_path}")

def write_file(file_path, lines):
    with open(file_path, 'w', encoding='utf-8') as file:
        file.writelines(lines)

# 定义提取中文函数
def extract_chinese(line):
    parts = line.split(' -- ')
    if len(parts) > 2:
        return parts[2].strip()  # 获取中间的中文部分并去除两端空白字符
    return ""

# 定义搜索函数
def search_in_file(lines, numbers):
    search_results = []
    for line in lines:
        for number in numbers:
            if f' {number} ' in line:
                search_results.append(line.strip())
                break
    return search_results

# 定义 find_hex_sequences 函数
def find_hex_sequences(file_path1, file_path2, search_sequence):
    # 将搜索序列转换为字节
    search_bytes = bytes.fromhex(search_sequence.replace(' ', ''))

    # 读取两个文件的内容
    with open(file_path1, "rb") as file1:
        file1_contents = file1.read()
    with open(file_path2, "rb") as file2:
        file2_contents = file2.read()

    # 确保两个文件大小相同
    if len(file1_contents) != len(file2_contents):
        raise ValueError("Files are not the same size.")

    # 查找所有序列的位置
    positions1 = [pos for pos in range(len(file1_contents) - len(search_bytes) + 1)
                  if file1_contents[pos:pos + len(search_bytes)] == search_bytes]
    positions2 = [pos for pos in range(len(file2_contents) - len(search_bytes) + 1)
                  if file2_contents[pos:pos + len(search_bytes)] == search_bytes]

    # 确保两个文件中序列的数量相同
    if len(positions1) != len(positions2):
        raise ValueError("The number of sequences is not the same in both files.")

    # 比较两个文件中序列之前的序列，并生成包含差异的字符串
    differences = []
    for pos1, pos2 in zip(positions1, positions2):
        sequence1 = file1_contents[pos1 - 4:pos1].hex().upper()  # 比较序列前4个字节
        sequence2 = file2_contents[pos2 - 4:pos2].hex().upper()
        if sequence1 != sequence2:
            differences.append(f"Position {pos1}: {sequence1} != {sequence2}")

    return differences

# 定义 extract_and_convert 函数
def extract_and_convert(differences, output_file):
    data = []
    for line in differences:
        parts = line.split('!= ')
        if len(parts) == 2:
            hex_values = parts[0].split()[-1], parts[1].strip().strip('\n')
            decimal_number1 = reverse_hex_array_and_convert(hex_values[0])
            decimal_number2 = reverse_hex_array_and_convert(hex_values[1])
            data.append((decimal_number1, decimal_number2))

    data = remove_one_of_reversed_rows(data)

    with open(output_file, 'w') as file:
        for line in data:
            file.write(f"[{line[0]},{line[1]}],#\n")

    print(f"转换完成，结果已写入文件：{output_file}")

# 定义 reverse_hex_array_and_convert 函数
def reverse_hex_array_and_convert(hex_number):
    if len(hex_number) != 8:
        raise ValueError("Input must be an 8-digit hexadecimal number.")
    hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
    reversed_hex_array = hex_array[::-1]
    reversed_hex_number = ''.join(reversed_hex_array)
    decimal_number = int(reversed_hex_number, 16)
    return decimal_number

# 定义 remove_one_of_reversed_rows 函数
def remove_one_of_reversed_rows(data):
    reverse_index = {}
    for idx, row in enumerate(data):
        sorted_row = tuple(sorted(row))
        if sorted_row in reverse_index:
            reverse_index[sorted_row].append(idx)
        else:
            reverse_index[sorted_row] = [idx]

    to_remove = []
    for indices in reverse_index.values():
        if len(indices) > 1:
            to_remove.extend(indices[1:])

    for index in sorted(to_remove, reverse=True):
        del data[index]

    return data
# 脚本 1 的功能
def script_1():
    print("\n运行脚本 1")
    folder_path = input("请输入小包文件夹路径: ")
    fixed_hex = input("最新特征码0B85: ")
    array_file_path = input("请输入包含数组的文件路径: ")

    try:
        with open(array_file_path, 'r') as file:
            array = eval(file.read())
    except Exception as e:
        print(f"读取或解析数组文件时出错: {e}")
        return

    original_files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
    merged_content = merge_files_in_folder(folder_path)

    for i in range(len(array)):
        A = DEC_to_HEX(array[i][0])
        B = DEC_to_HEX(array[i][1])
        merged_content = modify_file_hex(merged_content, A, B, fixed_hex)

    write_back_to_files(folder_path, merged_content, original_files)
    print("文件夹中的所有文件已编辑")

def script_2():
    print("\n运行功能2：dat自动")

    # 获取文件路径
    file_path = input("请输入dat文件的路径: ")

    # 获取array数组文件路径
    array_file_path = input("请输入txt配置的路径: ")

    # 获取要添加的十六进制字符串
    additional_hex = input("请输入特征码最新5CF5: ")

    # 读取array数组文件内容
    def read_array_from_file(file_path):
        with open(file_path, 'r') as file:
            lines = file.readlines()
        array = []
        for line in lines:
            line = line.strip()
            if line:  # 确保不处理空行
                parts = line.split(',')
                array.append([int(part.strip()) for part in parts])
        return array

    array = read_array_from_file(array_file_path)

    # 创建一个函数
    def DEC_to_HEX(decimal_number, additional_hex):
        # 将十进制数转换为十六进制并格式化输出
        hex_number = format(int(decimal_number), '08X')  # '08X' 表示输出为8位十六进制数,不足部分用0填充
        # 将十六进制数拆分成数组并反转顺序
        hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
        reversed_hex_array = hex_array[::-1]  # 反转数组
        # 重新组合反转后的十六进制数并输出
        reversed_hex_number = ''.join(reversed_hex_array)
        print(decimal_number, end='')
        print("转换为：", end='')
        print(reversed_hex_number)
        return reversed_hex_number + additional_hex  # 添加用户输入的十六进制字符串

    # 修改文件十六进制函数
    def modify_file_hex(file_path, A, B):
        # 要搜索的十六进制序列
        search_seq1 = bytes.fromhex(A)
        search_seq2 = bytes.fromhex(B)

        # 读取文件内容
        with open(file_path, "rb") as file:
            file_contents = file.read()

        # 查找第一个和第二个搜索序列的位置
        search_index1 = file_contents.find(search_seq1)
        search_index2 = file_contents.find(search_seq2)

        # 检查是否找到了两个序列
        if search_index1 == -1 or search_index2 == -1:
            print("未找到指定的搜索序列。")
            return

        # 提取要替换的数据
        data_to_replace1 = file_contents[search_index1:search_index1 + len(search_seq1)]
        data_to_replace2 = file_contents[search_index2:search_index2 + len(search_seq2)]

        # 创建一个新文件内容的副本,用于修改
        new_contents = bytearray(file_contents)

        # 将第一个序列的数据写入到第二个序列的位置
        new_contents[search_index2:search_index2 + len(search_seq1)] = data_to_replace1
        # 将第二个序列的数据写入到第一个序列的位置
        new_contents[search_index1:search_index1 + len(search_seq2)] = data_to_replace2

        # 将修改后的内容写回文件
        with open(file_path, "wb") as file:
            file.write(new_contents)

        print("文件已编辑")

    # 循环遍历二维数组
    for i in range(len(array)):
        modify_file_hex(file_path, DEC_to_HEX(array[i][0], additional_hex), DEC_to_HEX(array[i][1], additional_hex))
        print("------------------------------------------------------")

def script_3():
    print("\n运行脚本 6：修改 .dat 文件")
    
    # 提示用户输入文件路径
    file_path = input("请输入dat文件的路径: ")
    array_file_path = input("请输入配置数组文件的路径: ")

    # 读取数组文件内容
    def read_array_from_file(file_path):
        with open(file_path, 'r') as file:
            lines = file.readlines()
        array = []
        for line in lines:
            line = line.strip()
            if line:  # 确保不处理空行
                parts = line.split(',')
                array.append([int(part.strip()) for part in parts])
        return array

    # 定义 DEC_to_HEX 函数
    def DEC_to_HEX(decimal_number):
        hex_number = format(int(decimal_number), '08X')  
        hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
        reversed_hex_array = hex_array[::-1]  
        reversed_hex_number = ''.join(reversed_hex_array)
        print(decimal_number, end=': ')
        print("转换为：", end='')
        print(reversed_hex_number)
        return reversed_hex_number

    # 定义 modify_file_hex 函数
    def modify_file_hex(file_path, A, B):
        search_seq1 = bytes.fromhex(A)
        replace_seq = bytes.fromhex(B)

        with open(file_path, "rb") as file:
            file_contents = file.read()

        new_contents = file_contents.replace(search_seq1, replace_seq)

        with open(file_path, "wb") as file:
            file.write(new_contents)
        print("已经修改")

    # 从用户输入的数组文件路径读取数组
    array = read_array_from_file(array_file_path)

    # 遍历数组并修改文件
    for i in range(len(array)):
        A = DEC_to_HEX(array[i][0])
        B = DEC_to_HEX(array[i][1])
        modify_file_hex(file_path, A, B)
        print("------------------------------------------------------")
# 脚本 4 的功能：修改文件夹中的 .dat 文件
def script_4():
    print("\n")

    # 获取用户输入的文件夹路径
    folder_path = input("请输入小包文件夹路径: ")

    # 获取用户输入的固定特征码
    fixed_hex = input("请输入最新特征码（0B85）: ")

    # 获取用户输入的数组文件路径
    array_file_path = input("请输入包含数组的文件路径: ")

    # 读取数组文件内容
    def read_array_from_file(file_path):
        array = []
        try:
            with open(file_path, 'r') as file:
                for line in file:
                    line = line.strip()
                    if not line:
                        continue  # 跳过空行
                    parts = line.split(',')
                    if len(parts) != 2:
                        print(f"忽略格式错误的行: {line}")
                        continue
                    try:
                        a = int(parts[0])
                        b = int(parts[1])
                        array.append([a, b])
                    except ValueError:
                        print(f"无法转换为整数: {line}")
                        continue
        except Exception as e:
            print(f"读取或解析数组文件时出错: {e}")
            return []
        return array

    # 定义 DEC_to_HEX 函数
    def DEC_to_HEX(decimal_number):
        hex_number = format(int(decimal_number), '08X')
        hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
        reversed_hex_array = hex_array[::-1]
        reversed_hex_number = ''.join(reversed_hex_array)
        print(decimal_number, end=': ')
        print("转换为：", end='')
        print(reversed_hex_number)
        return reversed_hex_number

    # 定义 modify_file_hex 函数
    def modify_file_hex(file_contents, A, B, fixed_hex):
        search_seq1 = bytes.fromhex(A)
        search_seq2 = bytes.fromhex(B)
        fixed_hex = bytes.fromhex(fixed_hex)

        search_index1 = file_contents.find(search_seq1)
        search_index2 = file_contents.find(search_seq2)

        if search_index1 == -1 or search_index2 == -1:
            print("未找到指定的搜索序列。")
            return file_contents

        start_index1 = find_hex_reverse(file_contents, fixed_hex, search_index1)
        if start_index1 == -1:
            print(f"未找到十六进制数 {fixed_hex.hex()}")
            return file_contents

        start_index2 = find_hex_reverse(file_contents, fixed_hex, search_index2)
        if start_index2 == -1:
            print(f"未找到十六进制数 {fixed_hex.hex()}")
            return file_contents

        data_to_replace1 = file_contents[start_index1 - 8:start_index1]
        data_to_replace2 = file_contents[start_index2 - 8:start_index2]

        new_contents = bytearray(file_contents)
        new_contents[start_index1 - 8:start_index1] = data_to_replace2
        new_contents[start_index2 - 8:start_index2] = data_to_replace1

        return new_contents

    # 辅助函数，用于从给定位置向上查找十六进制数
    def find_hex_reverse(data, hex_to_find, start):
        return data.rfind(hex_to_find, 0, start)

    # 合并文件夹中的所有文件内容
    def merge_files_in_folder(folder_path):
        merged_content = bytearray()
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            if os.path.isfile(file_path):
                with open(file_path, "rb") as file:
                    merged_content += file.read()
        return merged_content

    # 将修改后的内容写回原来的文件
    def write_back_to_files(folder_path, modified_content, original_files):
        offset = 0
        for filename in original_files:
            file_path = os.path.join(folder_path, filename)
            if os.path.isfile(file_path):
                with open(file_path, "rb") as file:
                    file_size = len(file.read())
                with open(file_path, "wb") as file:
                    file.write(modified_content[offset:offset + file_size])
                offset += file_size

    # 读取数组文件内容
    array = read_array_from_file(array_file_path)

    # 合并文件夹中的所有文件内容
    original_files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
    merged_content = merge_files_in_folder(folder_path)

    # 对合并后的内容进行操作
    for i in range(len(array)):
        A = DEC_to_HEX(array[i][0])
        B = DEC_to_HEX(array[i][1])
        merged_content = modify_file_hex(merged_content, A, B, fixed_hex)

    # 将修改后的内容写回原来的文件
    write_back_to_files(folder_path, merged_content, original_files)

    print("文件夹中的所有文件已编辑")

def script_5():
    print("\n运行功能18：比较两个文件夹并复制差异到目标文件夹")

    # 提示用户输入文件夹路径
    folder1_path = input("请输入第一个文件夹路径：")
    folder2_path = input("请输入第二个文件夹路径：")
    target_folder_path = input("请输入目标文件夹路径：")

    # 确保目标文件夹存在
    if not os.path.exists(target_folder_path):
        os.makedirs(target_folder_path)
        print(f"目标文件夹不存在，已创建：{target_folder_path}")

    # 比较两个文件夹并复制差异到目标文件夹
    compare_and_copy(folder1_path, folder2_path, target_folder_path)

# 比较两个文件夹并复制差异到目标文件夹的函数
def compare_and_copy(folder1, folder2, target_folder):
    # 获取两个文件夹中的所有文件和文件夹名称
    files1 = set(os.listdir(folder1))
    files2 = set(os.listdir(folder2))
    
    # 找出两个文件夹中都存在的文件
    common_files = files1.intersection(files2)
    
    # 比较相同名称的文件内容
    for file in common_files:
        path1 = os.path.join(folder1, file)
        path2 = os.path.join(folder2, file)
        
        # 如果是文件夹，则递归比较
        if os.path.isdir(path1) and os.path.isdir(path2):
            compare_and_copy(path1, path2, target_folder)
        # 如果是文件，则比较内容
        elif os.path.isfile(path1) and os.path.isfile(path2):
            if not filecmp.cmp(path1, path2, shallow=False):
                print(f"文件内容不同: {file}")
                # 复制不同文件到目标文件夹
                target_path = os.path.join(target_folder, file)
                shutil.copy2(path2, target_path)
                print(f"已复制到: {target_path}")
        else:
            print(f"类型不匹配: {file}")

    # 找出folder2中独有的文件
    unique_files = files2 - files1
    for file in unique_files:
        path2 = os.path.join(folder2, file)
        if os.path.isfile(path2):
            print(f"folder2独有文件: {file}")
            # 复制folder2独有文件到目标文件夹
            target_path = os.path.join(target_folder, file)
            shutil.copy2(path2, target_path)
            print(f"已复制到: {target_path}")
        elif os.path.isdir(path2):
            print(f"folder2独有文件夹: {file}")
            # 复制folder2独有文件夹到目标文件夹
            target_path = os.path.join(target_folder, file)
            shutil.copytree(path2, target_path)
            print(f"已复制到: {target_path}")


def script_6():
    print("\n")

    # 提示用户输入文件路径
    input_file_path = input("请输入输入文件的路径: ")
    output_file_path = input("请输入输出文件的路径: ")

    # 用于存储提取结果的列表
    extracted_data = []

    # 读取输入文件
    try:
        with open(input_file_path, 'r', encoding='utf-8') as file:
            for line in file:
                # 使用正则表达式提取中括号内的内容
                match = re.search(r'\[(.*?)\]', line)
                if match:
                    # 将提取到的内容添加到列表中，去掉中括号
                    extracted_data.append(match.group(1).strip())  # 去掉前后空格

        # 将提取结果写入输出文件
        with open(output_file_path, 'w', encoding='utf-8') as file:
            for item in extracted_data:
                file.write(f'{item}\n')  # 写入文件，去掉中括号

        print(f'提取完成，结果已输出到 {output_file_path}')

    except FileNotFoundError:
        print(f"文件未找到，请确保路径 {input_file_path} 正确无误。")
    except Exception as e:
        print(f"发生了一个错误: {e}")

# 脚本 7 的功能（预留）
def script_7():
    print("\n运行脚本 6：修改 .dat 文件")
    
    # 提示用户输入文件路径
    file_path = input("请输入dat文件的路径: ")
    array_file_path = input("请输入配置数组文件的路径: ")

    # 读取数组文件内容
    def read_array_from_file(file_path):
        with open(file_path, 'r') as file:
            lines = file.readlines()
        array = []
        for line in lines:
            line = line.strip()
            if line:  # 确保不处理空行
                parts = line.split(',')
                array.append([int(part.strip()) for part in parts])
        return array

    # 定义 DEC_to_HEX 函数
    def DEC_to_HEX(decimal_number):
        hex_number = format(int(decimal_number), '08X')  
        hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
        reversed_hex_array = hex_array[::-1]  
        reversed_hex_number = ''.join(reversed_hex_array)
        print(decimal_number, end=': ')
        print("转换为：", end='')
        print(reversed_hex_number)
        return reversed_hex_number

    # 定义 modify_file_hex 函数
    def modify_file_hex(file_path, A, B):
        search_seq1 = bytes.fromhex(A)
        replace_seq = bytes.fromhex(B)

        with open(file_path, "rb") as file:
            file_contents = file.read()

        new_contents = file_contents.replace(search_seq1, replace_seq)

        with open(file_path, "wb") as file:
            file.write(new_contents)
        print("已经修改")

    # 从用户输入的数组文件路径读取数组
    array = read_array_from_file(array_file_path)

    # 遍历数组并修改文件
    for i in range(len(array)):
        A = DEC_to_HEX(array[i][0])
        B = DEC_to_HEX(array[i][1])
        modify_file_hex(file_path, A, B)
        print("------------------------------------------------------")

# 定义运行时输入文件夹路径和文件路径的函数
def script_9():
    print("\n：修改文件夹中的文件内容")

    # 运行时输入文件夹路径
    folder_path = input("请输入载具小包路径：")
    if not os.path.isdir(folder_path):
        print("输入的路径不是有效的文件夹路径！")
        return

    # 运行时输入array文件路径
    array_file_path = input("请输入txt配置路径：")
    if not os.path.isfile(array_file_path):
        print("输入的array文件路径不是有效的文件路径！")
        return

    # 运行时输入特征码
    hex_suffix = input("请输入特征码67F5：").strip().upper()
    hex_to_find = input("请输入特征码66F5：").strip().upper()

    # 从文件中读取array内容
    array = []
    try:
        with open(array_file_path, "r") as file:
            for line in file:
                line = line.strip()
                if line:  # 跳过空行
                    values = line.split(",")
                    if len(values) == 2:
                        array.append([int(values[0]), int(values[1])])
                    else:
                        print(f"警告：跳过无效行 - {line}")
    except Exception as e:
        print("读取array文件时出错，错误信息：", e)
        return

    # 创建一个函数
    def DEC_to_HEX(decimal_number, hex_suffix):
        # 将十进制数转换为十六进制并格式化输出
        hex_number = format(int(decimal_number), '08X')  # '08X' 表示输出为8位十六进制数，不足部分用0填充
        # 将十六进制数拆分成数组并反转顺序
        hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
        reversed_hex_array = hex_array[::-1]  # 反转数组
        # 重新组合反转后的十六进制数并输出
        reversed_hex_number = ''.join(reversed_hex_array)
        # 在十六进制字符串后面加上用户指定的后缀
        final_hex_number = reversed_hex_number + hex_suffix
        print(decimal_number, end='')
        print("转换为：", end='')
        print(final_hex_number)
        return final_hex_number

    # 修改字节流的函数
    def modify_data(data, A, B, hex_to_find):
        # 要搜索的十六进制序列
        search_seq1 = bytes.fromhex(A)
        search_seq2 = bytes.fromhex(B)
        hex_to_find_bytes = bytes.fromhex(hex_to_find)

        # 查找第一个和第二个搜索序列的位置
        search_index1 = data.find(search_seq1)
        search_index2 = data.find(search_seq2)

        # 检查是否找到了两个序列
        if search_index1 == -1 or search_index2 == -1:
            print("未找到指定的搜索序列。")
            return data

        # 从第一个搜索到序列位置后面开始搜索十六进制数
        end_index1 = find_hex(data, hex_to_find_bytes, search_index1 + len(search_seq1))
        if end_index1 == -1:
            print("未找到指定的十六进制序列。")
            return data

        # 从第二个搜索到序列位置后面开始搜索十六进制数
        end_index2 = find_hex(data, hex_to_find_bytes, search_index2 + len(search_seq2))
        if end_index2 == -1:
            print("未找到指定的十六进制序列。")
            return data

        # 提取要替换的数据
        data_to_replace1 = data[search_index1 + len(search_seq1):end_index1]
        data_to_replace2 = data[search_index2 + len(search_seq2):end_index2]

        # 创建一个新数据的副本，用于修改
        new_data = bytearray(data)

        # 将第一个序列的数据写入到第二个序列的位置
        new_data[search_index2 + len(search_seq2):end_index2] = data_to_replace1
        # 将第二个序列的数据写入到第一个序列的位置
        new_data[search_index1 + len(search_seq1):end_index1] = data_to_replace2

        print("数据已修改")
        return new_data

    # 辅助函数，用于查找十六进制数
    def find_hex(data, hex_to_find, start):
        index = data.find(hex_to_find, start)
        return index

    # 合并文件夹中的所有文件内容
    def merge_files(folder_path):
        files = sorted(os.listdir(folder_path))  # 获取文件夹中的所有文件并排序
        merged_data = bytearray()
        file_sizes = []  # 用于记录每个文件的大小

        for file_name in files:
            file_path = os.path.join(folder_path, file_name)
            if os.path.isfile(file_path):
                with open(file_path, "rb") as file:
                    file_data = file.read()
                    merged_data.extend(file_data)
                    file_sizes.append(len(file_data))

        return merged_data, file_sizes

    # 根据文件大小分割合并后的内容
    def split_data(merged_data, file_sizes):
        split_data_list = []
        start_index = 0
        for size in file_sizes:
            end_index = start_index + size
            split_data_list.append(merged_data[start_index:end_index])
            start_index = end_index
        return split_data_list

    # 主逻辑
    merged_data, file_sizes = merge_files(folder_path)

    for i in range(len(array)):
        merged_data = modify_data(merged_data, DEC_to_HEX(array[i][0], hex_suffix), DEC_to_HEX(array[i][1], hex_suffix), hex_to_find)
        print("------------------------------------------------------")

    split_data_list = split_data(merged_data, file_sizes)

    files = sorted(os.listdir(folder_path))  # 获取文件夹中的所有文件并排序
    for i, file_name in enumerate(files):
        file_path = os.path.join(folder_path, file_name)
        if os.path.isfile(file_path):
            with open(file_path, "wb") as file:
                file.write(split_data_list[i])
            print(f"文件 {file_name} 已更新")


def script_10():
    print("\n运行脚本 10")
    file_path1 = input("原版或者改了的文件路径: ")
    file_path2 = input("原版或者改了的文件路径: ")
    search_sequence = input("特征码: ")
    output_file = input("输出文件路径: ")
    differences = find_hex_sequences(file_path1, file_path2, search_sequence)
    extract_and_convert(differences, output_file)
def script_11():
    print("\n运行功能20：为文件添加注释")

    # 提示用户输入文件路径
    input_file_path = input("请输入要加注释的文件路径（py或txt）：")
    search_file_path = input("请输入和平代码文件路径：")

    # 定义读取文件和写入文件的函数
    def read_file(file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        return lines

    def write_file(file_path, lines):
        with open(file_path, 'w', encoding='utf-8') as file:
            file.writelines(lines)

    # 定义提取中文函数
    def extract_chinese(line):
        parts = line.split(' -- ')
        if len(parts) > 2:
            return parts[2].strip()  # 获取中间的中文部分并去除两端空白字符
        return ""

    # 定义搜索函数
    def search_in_file(search_file_path, number):
        search_results = {}
        with open(search_file_path, 'r', encoding='utf-8') as file:
            for line in file:
                if f' {number} ' in line:
                    chinese = extract_chinese(line)
                    if chinese:
                        search_results[number] = chinese
                    break
        return search_results

    # 读取输入文件
    lines = read_file(input_file_path)
    
    # 读取搜索文件，提前构建一个数字到中文的映射
    number_to_chinese = {}
    with open(search_file_path, 'r', encoding='utf-8') as file:
        for line in file:
            parts = line.split(' -- ')
            if len(parts) > 2:
                number = parts[1].strip()
                chinese = parts[2].strip()
                number_to_chinese[number] = chinese

    # 存储最终结果
    modified_lines = []

    # 遍历每一行
    for line in lines:
        # 使用正则表达式提取数字
        numbers = re.findall(r'\d+', line)
        
        # 按照数字顺序构建注释
        comments = []
        for number in numbers:
            if number in number_to_chinese:
                comments.append(number_to_chinese[number])
        
        # 如果有匹配的中文部分，追加到原行的#号后面
        if comments:
            additional_text = '改'.join(comments)
            new_line = line.rstrip('\n') + ' # ' + additional_text + '\n'
            modified_lines.append(new_line)
        else:
            modified_lines.append(line)  # 如果没有匹配的中文部分，保持原样
    
    # 写入修改后的内容回输入文件
    write_file(input_file_path, modified_lines)

    print(f"注释已添加到文件：{input_file_path}")

# 脚本 13 的功能（预留）
def script_20():
    print("\n运行功能20：为文件添加注释")

    # 提示用户输入文件路径
    input_file_path = input("请输入要加注释的文件路径（py或txt）：")
    search_file_path = input("请输入和平代码文件路径：")

    # 定义读取文件和写入文件的函数
    def read_file(file_path):
        with open(file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        return lines

    def write_file(file_path, lines):
        with open(file_path, 'w', encoding='utf-8') as file:
            file.writelines(lines)

    # 定义提取中文函数
    def extract_chinese(line):
        parts = line.split(' -- ')
        if len(parts) > 2:
            return parts[2].strip()  # 获取中间的中文部分并去除两端空白字符
        return ""

    # 定义搜索函数
    def search_in_file(search_file_path, number):
        search_results = {}
        with open(search_file_path, 'r', encoding='utf-8') as file:
            for line in file:
                if f' {number} ' in line:
                    chinese = extract_chinese(line)
                    if chinese:
                        search_results[number] = chinese
                    break
        return search_results

    # 读取输入文件
    lines = read_file(input_file_path)
    
    # 读取搜索文件，提前构建一个数字到中文的映射
    number_to_chinese = {}
    with open(search_file_path, 'r', encoding='utf-8') as file:
        for line in file:
            parts = line.split(' -- ')
            if len(parts) > 2:
                number = parts[1].strip()
                chinese = parts[2].strip()
                number_to_chinese[number] = chinese

    # 存储最终结果
    modified_lines = []

    # 遍历每一行
    for line in lines:
        # 使用正则表达式提取数字
        numbers = re.findall(r'\d+', line)
        
        # 按照数字顺序构建注释
        comments = []
        for number in numbers:
            if number in number_to_chinese:
                comments.append(number_to_chinese[number])
        
        # 如果有匹配的中文部分，追加到原行的#号后面
        if comments:
            additional_text = '改'.join(comments)
            new_line = line.rstrip('\n') + ' # ' + additional_text + '\n'
            modified_lines.append(new_line)
        else:
            modified_lines.append(line)  # 如果没有匹配的中文部分，保持原样
    
    # 写入修改后的内容回输入文件
    write_file(input_file_path, modified_lines)

    print(f"注释已添加到文件：{input_file_path}")
def script_12():
    print("\n运行功能20：修改文件夹中的文件十六进制内容")

    # 运行时输入文件夹路径
    folder_path = input("请输入载具小包文件夹路径：")

    # 运行时输入 array 数组文件路径
    array_file_path = input("请输入配置文件文件路径：")

    # 运行时输入附加的十六进制后
    hex_suffix = input("请输入特征码（3.17最新5CF5）：").strip().upper()

    # 从文件中读取 array 数据
    def load_array_from_file(file_path):
        array = []
        try:
            with open(file_path, "r", encoding="utf-8") as file:
                for line in file:
                    line = line.strip()
                    if line:  # 确保不处理空行
                        values = line.split(",")
                        if len(values) == 2:
                            try:
                                pair = [int(values[0]), int(values[1])]
                                array.append(pair)
                            except ValueError:
                                print(f"警告：无法解析行 '{line}'，跳过此行。")
                        else:
                            print(f"警告：行 '{line}' 格式不正确，跳过此行。")
        except FileNotFoundError:
            print(f"错误：文件 {file_path} 未找到。")
        except Exception as e:
            print(f"读取文件时发生错误：{e}")
        return array

    array = load_array_from_file(array_file_path)

    # 检查 array 是否为空
    if not array:
        print("未加载到有效的 array 数据，程序退出。")
        return

    # 创建一个函数，将十进制转换为十六进制并反转字节序
    def DEC_to_HEX(decimal_number, suffix):
        hex_number = format(int(decimal_number), '08X')
        hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
        reversed_hex_array = hex_array[::-1]
        reversed_hex_number = ''.join(reversed_hex_array)
        return reversed_hex_number + suffix

    # 查找并修改文件十六进制函数
    def find_and_modify_hex(folder_path, A, B):
        search_seq1 = bytes.fromhex(DEC_to_HEX(A, hex_suffix))
        search_seq2 = bytes.fromhex(DEC_to_HEX(B, hex_suffix))
        found_file1 = None
        found_index1 = -1
        found_file2 = None
        found_index2 = -1

        # 遍历文件夹中的所有文件
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                with open(file_path, "rb") as file:
                    file_contents = file.read()
                    # 查找第一个序列
                    index1 = file_contents.find(search_seq1)
                    if index1 != -1:
                        found_file1 = file_path
                        found_index1 = index1
                    # 查找第二个序列
                    index2 = file_contents.find(search_seq2)
                    if index2 != -1:
                        found_file2 = file_path
                        found_index2 = index2
            except IOError:
                print(f"无法读取文件 {file_path}")

        # 检查是否找到了两个序列
        if found_index1 != -1 and found_index2 != -1:
            # 如果两个序列在同一文件中
            if found_file1 == found_file2:
                with open(found_file1, "rb+") as file:
                    file.seek(found_index1)
                    file.write(search_seq2)
                    file.seek(found_index2)
                    file.write(search_seq1)
                print(f"文件 {found_file1} 中的序列已交换")
            else:  # 如果两个序列在不同文件中
                with open(found_file1, "rb+") as file1:
                    file1.seek(found_index1)
                    file1.write(search_seq2)
                with open(found_file2, "rb+") as file2:
                    file2.seek(found_index2)
                    file2.write(search_seq1)
                print(f"文件 {found_file1} 和 {found_file2} 中的序列已交换")
        else:
            print("未找到指定的搜索序列。")

    # 循环遍历二维数组
    for i in range(len(array)):
        find_and_modify_hex(folder_path, array[i][0], array[i][1])
        print("------------------------------------------------------")
# 脚本 14 的功能（预留）
def script_14():
    print("\n运行脚本 14")
    print("这是预留的脚本 14 的内容")


# 脚本 14 的功能（预留）
def script_15():
    print("\n运行脚本 14")
    print("这是预留的脚本 14 的内容")
# 脚本 16 的功能（预留）
def script_16():
    print("\n运行脚本 16")
    print("这是预留的脚本 16 的内容")

# 脚本 17 的功能（预留）
def script_17():
    print("\n运行脚本 17")
    print("这是预留的脚本 17 的内容")

# 脚本 18 的功能（预留）
def script_18():
    print("\n运行脚本 18")
    print("这是预留的脚本 18 的内容")

# 脚本 19 的功能（预留）
def script_19():
    print("\n运行脚本 19")
    print("这是预留的脚本 19 的内容")

# 脚本 20 的功能（预留）
def script_20():
    print("\n运行脚本 20")
    print("这是预留的脚本 20 的内容")

# 退出程序
def exit_program():
    print("\n退出程序")
    sys.exit(0)

# 辅助函数
def DEC_to_HEX(decimal_number, additional_hex=""):
    hex_number = format(int(decimal_number), '08X')
    hex_array = [hex_number[i:i + 2] for i in range(0, len(hex_number), 2)]
    reversed_hex_array = hex_array[::-1]
    reversed_hex_number = ''.join(reversed_hex_array)
    print(decimal_number, end=': ')
    print("转换为：", end='')
    print(reversed_hex_number)
    return reversed_hex_number + additional_hex

def modify_file_hex(file_contents, A, B, fixed_hex=""):
    search_seq1 = bytes.fromhex(A)
    search_seq2 = bytes.fromhex(B)
    fixed_hex = bytes.fromhex(fixed_hex) if fixed_hex else b""

    search_index1 = file_contents.find(search_seq1)
    search_index2 = file_contents.find(search_seq2)

    if search_index1 == -1 or search_index2 == -1:
        print("未找到指定的搜索序列。")
        return file_contents

    start_index1 = find_hex_reverse(file_contents, fixed_hex, search_index1)
    start_index2 = find_hex_reverse(file_contents, fixed_hex, search_index2)

    if start_index1 == -1 or start_index2 == -1:
        print(f"未找到十六进制数 {fixed_hex.hex()}")
        return file_contents

    data_to_replace1 = file_contents[start_index1 - 8:start_index1]
    data_to_replace2 = file_contents[start_index2 - 8:start_index2]

    new_contents = bytearray(file_contents)
    new_contents[start_index1 - 8:start_index1] = data_to_replace2
    new_contents[start_index2 - 8:start_index2] = data_to_replace1

    return new_contents

def find_hex_reverse(data, hex_to_find, start):
    return data.rfind(hex_to_find, 0, start)

def merge_files_in_folder(folder_path):
    merged_content = bytearray()
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path):
            with open(file_path, "rb") as file:
                merged_content += file.read()
    return merged_content

def write_back_to_files(folder_path, modified_content, original_files):
    offset = 0
    for filename in original_files:
        file_path = os.path.join(folder_path, filename)
        if os.path.isfile(file_path):
            with open(file_path, "rb") as file:
                file_size = len(file.read())
            with open(file_path, "wb") as file:
                file.write(modified_content[offset:offset + file_size])
            offset += file_size

def read_array_from_file(file_path):
    with open(file_path, 'r') as file:
        lines = file.readlines()
    array = []
    for line in lines:
        line = line.strip()
        if line:
            parts = line.split(',')
            array.append([int(part.strip()) for part in parts])
    return array

# 主菜单
def main_menu():
    while True:
        print("\n=== 功能菜单 ===")
        print("报错看自己配置、路径别来问我")
        print("1. 伪实体工具py")
        print("2. dat普通美化txt")
        print("3. 地铁原枪txt")
        print("4. 伪实体工具txt")
        print("5. 对比工具")
        print("6. py转txt")
        print("7. 大厅完美枪皮txt")
        print("8. 加配料表pytxt通用")
        print("9. 局内伪实体txt注:不能改太多")
        print("10. 偷单py配置")
        print("11. pytxt加配置")
        print("12. 载具小包txt")
        print("13. 待添加😋13")
        print("14. 待添加😋14")
        print("15. 待添加😋15")
        print("16. 待添加😋16")
        print("17. 待添加😋17")
        print("18. 待添加😋18")
        print("19. 待添加😋19")
        print("20. 待添加😋20")
        print("21. 退出")
        
        choice = input("请输入您的选择（1-21）: ")
        
        if choice == '1':
            script_1()
        elif choice == '2':
            script_2()
        elif choice == '3':
            script_3()
        elif choice == '4':
            script_4()
        elif choice == '5':
            script_5()
        elif choice == '6':
            script_6()
        elif choice == '7':
            script_7()
        elif choice == '8':
            script_8()
        elif choice == '9':
            script_9()
        elif choice == '10':
            script_10()
        elif choice == '11':
            script_11()
        elif choice == '12':
            script_12()
        elif choice == '13':
            script_13()
        elif choice == '14':
            script_14()
        elif choice == '15':
            script_15()
        elif choice == '16':
            script_16()
        elif choice == '17':
            script_17()
        elif choice == '18':
            script_18()
        elif choice == '19':
            script_19()
        elif choice == '20':
            script_20()
        elif choice == '21':
            exit_program()
        else:
            print("无效的选择，请重新输入！")

# 程序入口
if __name__ == "__main__":
    main_menu()