#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import shutil
import subprocess
from itertools import cycle
import hashlib
from datetime import datetime
import importlib
import importlib.machinery
import importlib.util
import time
import re
from colorama import Fore, Style

# 添加 paks 文件的正确路径
PAKS_PATH = "/data/data/com.termux/files/home/无莫工具/无莫nb/paks"

# 确保 paks 文件有执行权限
if os.path.exists(PAKS_PATH):
    os.chmod(PAKS_PATH, 0o755)  # 添加执行权限
else:
    print(f"错误: 找不到 paks 文件: {PAKS_PATH}")

viod = "           "
# 标准目录（去重并确保顺序）
directories = [
    "/storage/emulated/0/无莫制作区/",
    "/storage/emulated/0/无莫制作区/pak/",  # 待解包的pak位置
    "/storage/emulated/0/无莫制作区/uexp打包/",  # dat文件存放地点
    "/storage/emulated/0/无莫制作区/uexp解包/64kbuexp限制/",  # 解包pak输出位置
    "/storage/emulated/0/无莫制作区/dat打包/",  # dat文件存放地点
    "/storage/emulated/0/无莫制作区/dat解包/",  # 解包pak输出位置
    "/storage/emulated/0/无莫制作区/全自动美化/",
    "/storage/emulated/0/无莫制作区/配置/",
    "/storage/emulated/0/无莫制作区/全自动美化/配置/载具/",
    "/storage/emulated/0/无莫制作区/全自动美化/配置/伪实体/",
    "/storage/emulated/0/无莫制作区/全自动美化/配置/完美枪/",
    "/storage/emulated/0/无莫制作区/全自动美化/配置/水印/",
    "/storage/emulated/0/无莫制作区/全自动美化/配置/局内伪实体/",
    "/storage/emulated/0/无莫制作区/全自动美化/配置/仓库品质/",
    "/storage/emulated/0/无莫制作区/小包存放区/载具小包/",
    "/storage/emulated/0/无莫制作区/小包存放区/伪实体小包/",
    "/storage/emulated/0/无莫制作区/自动美化存放区/",
]

# 创建目录
for directory in directories:
    try:
        os.makedirs(directory, exist_ok=True)
        pass
    except Exception as e:
        print(f"Failed to create directory {directory}. Error: {e}")

# ---------------------- 基础工具函数 ----------------------
def copy_file(src, dst):
    """复制文件从src到dst"""
    try:
        shutil.copyfile(src, dst)
    except IOError as e:
        print(f"Unable to copy file. {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

def toast(message):
    """进度提示函数"""
    count = 0
    total = 3
    start = time.time()
    while count < total:
        time.sleep(1)
        cur = time.time()
        count += 1
        percent = count * 100 // total
        tenths = (count * 1000 // total) % 10
        runtime = int(cur - start)
        estremain = (runtime * total // count) - runtime
        minutes = estremain // 60
        seconds = estremain % 60
        print(f"{percent}.{tenths}% complete - est {minutes}:{seconds:02d} remaining", end="\r")
    print(f"\n{message}完成")

def gradient_text(text, start_color, end_color):
    """创建渐变文本（统一实现）"""
    start_rgb = [int(start_color[i:i+2], 16) for i in (0, 2, 4)]
    end_rgb = [int(end_color[i:i+2], 16) for i in (0, 2, 4)]
    gradient = ''
    for i, ch in enumerate(text):
        ratio = i / max(len(text) - 1, 1)
        rgb = [int(start_rgb[j] + (end_rgb[j] - start_rgb[j]) * ratio) for j in range(3)]
        gradient += f"\033[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m{ch}"
    return gradient + "\033[0m"

def get_current_datetime():
    """返回格式化的当前时间"""
    return datetime.now().strftime("%Y-%m-%d %H:%M")

def print_main_menu():
    """打印主菜单（统一实现）"""
    print(viod + gradient_text(f" {get_current_datetime()} │ by@可多樂 │ Repacker • Beautify Tool", "0000FF", "00FFFF"))
    print()
    print(viod + gradient_text("┌───────────────────────────────┐", "0000FF", "00FFFF"))
    print(viod + gradient_text("│  PUBG Mobile  │  Peace Elite  │", "0000FF", "00FFFF"))
    print(viod + gradient_text("│───────────────────────────────│", "0000FF", "00FFFF"))
    print(viod + gradient_text("│[1] 通用解包   │[3] 和平解包   │", "0000FF", "00FFFF"))
    print(viod + gradient_text("│[2] 通用打包   │[4] 和平打包   │", "0000FF", "00FFFF"))
    print(viod + gradient_text("│───────────────────────────────│", "0000FF", "00FFFF"))
    print(viod + gradient_text("│[5] 帮助                       │", "0000FF", "00FFFF"))
    print(viod + gradient_text("│───────────────────────────────│", "0000FF", "00FFFF"))
    print(viod + gradient_text("│[0] 退出                       │", "0000FF", "00FFFF"))
    print(viod + gradient_text("└───────────────────────────────┘", "0000FF", "00FFFF"))
    print()

def execute_command(command):
    """执行shell命令并输出结果"""
    try:
        result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
        print(result.stdout.strip())
    except subprocess.CalledProcessError as e:
        print(f"命令执行错误: {e}{e.stderr.strip()}")

# ---------------------- 彩虹文本相关 ----------------------
rainbow = [
    "[38;5;196m",  # 红色
    "[38;5;202m",  # 橙色
    "[38;5;226m",  # 黄色
    "[38;5;40m",   # 绿色
    "[38;5;45m",   # 青色
    "[38;5;21m",   # 蓝色
    "[38;5;54m",   # 紫色
]
color_cycle = cycle(rainbow)

def rainbow_text(text, color=None):
    """生成彩虹文本"""
    if color is None:
        color = next(color_cycle)
    return f"{color}{text}[0m"

def print_divider(color=None):
    """打印彩虹分隔线"""
    print(rainbow_text("-" * 50, color))

# ---------------------- 文件列表与解包 ----------------------
def list_files_in_directory(directory, extension):
    """列出目录中指定后缀的文件"""
    if not os.path.exists(directory):
        print(f"目录不存在: {directory}")
        return []
    return [f for f in os.listdir(directory) if f.endswith(extension)]

def list_pak_files_and_unpack(directory):
    """列出Pak文件并执行解包"""
    files = list_files_in_directory(directory, '.pak')
    if not files:
        print("未找到任何.pak文件")
        return None, None
    
    print("找到的Pak文件：")
    for idx, file in enumerate(files, 1):
        print(f"{idx}) {file}")
    
    while True:
        index_input = input("输入要解包的pak索引（或输入0返回）: ")
        if index_input == '0':
            print_main_menu()
            return None, None
        if not index_input:
            print("输入不能为空，请再试一次")
            continue
        try:
            index = int(index_input) - 1
            if 0 <= index < len(files):
                base_name = os.path.splitext(files[index])[0]
                OUTPUTNC = os.path.join("/storage/emulated/0/无莫制作区/uexp解包/64kbuexp限制/", base_name)
                PACKNC = os.path.join("/storage/emulated/0/无莫制作区/uexp打包", base_name)
                
                # 清空并重建目录
                if os.path.isdir(OUTPUTNC):
                    shutil.rmtree(OUTPUTNC)
                if os.path.isdir(PACKNC):
                    shutil.rmtree(PACKNC)
                os.makedirs(OUTPUTNC)
                os.makedirs(PACKNC)
                print(f"已重建文件夹：{OUTPUTNC}、{PACKNC}")
                
                # 执行解包命令 - 使用正确的 paks 路径
                pak_path = os.path.join(directory, files[index])
                command = f"\"{PAKS_PATH}\" -a \"{pak_path}\" {OUTPUTNC}"
                subprocess.run(command, shell=True)
                print("解包完成")
                return OUTPUTNC, base_name
            else:
                print("无效索引，请再试一次")
        except ValueError:
            print("请输入有效的整数")

# ---------------------- 小包提取与处理 ----------------------
def search_and_extract(source_path, pattern_bytes):
    """搜索并提取指定字节序列的内容（统一实现）"""
    found_files = []
    extracted_bytes_list = []
    for root, dirs, files in os.walk(source_path):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with open(file_path, "rb") as f:
                    content = f.read()
                index = content.find(pattern_bytes)
                if index != -1 and len(found_files) < 4:
                    found_files.append(file_path)
                    extracted_bytes = content[index + len(pattern_bytes):index + len(pattern_bytes) + 10]
                    extracted_bytes_list.append((extracted_bytes, file_path))
            except Exception as e:
                print(f"读取文件 {file_path} 错误: {e}")
    return extracted_bytes_list

def copy_files_with_pattern(source_path, pattern_bytes, target_path):
    """复制包含指定字节序列的文件"""
    count = 0
    os.makedirs(target_path, exist_ok=True)
    for root, dirs, files in os.walk(source_path):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with open(file_path, "rb") as f:
                    if pattern_bytes in f.read():
                        shutil.copy(file_path, target_path)
                        count += 1
            except Exception as e:
                print(f"复制文件 {file_path} 错误: {e}")
    return count

def grab_small_packages(unpacked_path):
    """提取载具和伪实体小包"""
    hex_pattern = "0B270600"
    pattern_bytes = bytes.fromhex(hex_pattern)
    a_path = "/storage/emulated/0/无莫制作区/小包存放区/载具小包/"
    b_path = "/storage/emulated/0/无莫制作区/小包存放区/伪实体小包/"
    
    # 清空目标目录
    for path in [a_path, b_path]:
        os.makedirs(path, exist_ok=True)
        for file in os.listdir(path):
            os.remove(os.path.join(path, file))
    
    # 提取匹配内容
    extracted_bytes_list = search_and_extract(unpacked_path, pattern_bytes)
    if not extracted_bytes_list:
        print("未找到任何匹配项")
        return
    
    # 统计复制数量
    counts = []
    for extracted_bytes, _ in extracted_bytes_list:
        count = copy_files_with_pattern(unpacked_path, extracted_bytes, a_path)
        counts.append(count)
    
    # 判断提取结果
    if any(600 <= c <= 680 for c in counts) and any(681 <= c <= 710 for c in counts):
        print("载具和伪实体都抓到")
        for i, (c, (bytes_val, file_path)) in enumerate(zip(counts, extracted_bytes_list)):
            if 600 <= c <= 680:
                print(f"载具小包数量: {c}（提取自 {file_path}）")
                shutil.rmtree(a_path)
                os.makedirs(a_path)
                copy_files_with_pattern(unpacked_path, bytes_val, a_path)
            elif 681 <= c <= 710:
                print(f"伪实体小包数量: {c}（提取自 {file_path}）")
                shutil.rmtree(b_path)
                os.makedirs(b_path)
                copy_files_with_pattern(unpacked_path, bytes_val, b_path)
    elif any(600 <= c <= 800 for c in counts):
        print("只有载具抓到")
        for c, (bytes_val, file_path) in zip(counts, extracted_bytes_list):
            if 600 <= c <= 680:
                print(f"载具小包数量: {c}（提取自 {file_path}）")
                shutil.rmtree(a_path)
                os.makedirs(a_path)
                copy_files_with_pattern(unpacked_path, bytes_val, a_path)
                break
    elif any(c > 620 for c in counts):
        print("只有伪实体抓到")
        for c, (bytes_val, file_path) in zip(counts, extracted_bytes_list):
            if 681 <= c <= 710:
                print(f"伪实体小包数量: {c}（提取自 {file_path}）")
                shutil.rmtree(b_path)
                os.makedirs(b_path)
                copy_files_with_pattern(unpacked_path, bytes_val, b_path)
                break
    else:
        print("载具和伪实体都没抓到")

# ---------------------- 十六进制处理 ----------------------
def DEC_to_HEX(decimal_number, additional_hex=""):
    """十进制转十六进制（带后缀）"""
    try:
        hex_num = format(int(decimal_number), '08X')
        hex_array = [hex_num[i:i+2] for i in range(0, 8, 2)]
        reversed_hex = ''.join(hex_array[::-1])
        return reversed_hex + additional_hex
    except ValueError:
        print(rainbow_text(f"无效的十进制数: {decimal_number}"))
        return None

def modify_file_hex(file_path, A, B, start_seq=None, end_seq=None):
    """修改文件十六进制内容"""
    try:
        search_seq1 = bytes.fromhex(A)
        search_seq2 = bytes.fromhex(B)
        with open(file_path, "rb") as f:
            content = f.read()
    except FileNotFoundError:
        print(rainbow_text(f"文件未找到: {file_path}"))
        return False, False, None
    
    modification_details = []
    new_contents = bytearray(content)
    
    if start_seq and end_seq:
        # 提取指定序列间的值并交换
        start_seq = bytes.fromhex(start_seq)
        end_seq = bytes.fromhex(end_seq)
        
        # 处理第一个序列
        value1_start = content.rfind(start_seq, 0, content.rfind(search_seq1))
        value1_end = content.rfind(end_seq, value1_start, content.rfind(search_seq1))
        if value1_start == -1 or value1_end == -1:
            print(rainbow_text("未找到起始/结束序列"))
            return False, False, None
        value1 = content[value1_start + len(start_seq):value1_end]
        
        # 处理第二个序列
        value2_start = content.rfind(start_seq, 0, content.rfind(search_seq2))
        value2_end = content.rfind(end_seq, value2_start, content.rfind(search_seq2))
        if value2_start == -1 or value2_end == -1:
            print(rainbow_text("未找到起始/结束序列"))
            return False, False, None
        value2 = content[value2_start + len(start_seq):value2_end]
        
        # 交换值
        new_contents[value1_start + len(start_seq):value1_end] = value2
        new_contents[value2_start + len(start_seq):value2_end] = value1
        
        # 记录详情
        modification_details = [
            {"position": f"0x{value1_start + len(start_seq):X}", "original_bytes": value1.hex().upper(), "new_bytes": value2.hex().upper()},
            {"position": f"0x{value2_start + len(start_seq):X}", "original_bytes": value2.hex().upper(), "new_bytes": value1.hex().upper()}
        ]
    else:
        # 直接交换两个序列
        search_index1 = content.find(search_seq1)
        search_index2 = content.find(search_seq2)

        if search_index1 == -1 or search_index2 == -1:
            print(rainbow_text("未找到指定的搜索序列"))
            return False, False, None

        data_to_replace1 = content[search_index1:search_index1 + len(search_seq1)]
        data_to_replace2 = content[search_index2:search_index2 + len(search_seq2)]

        new_contents = bytearray(content)
        new_contents[search_index2:search_index2 + len(search_seq1)] = data_to_replace1
        new_contents[search_index1:search_index1 + len(search_seq2)] = data_to_replace2

        # 记录修改详情
        modification_details = [
            {
                "position": f"0x{search_index1:X}",
                "original_bytes": data_to_replace1.hex().upper(),
                "new_bytes": data_to_replace2.hex().upper()
            },
            {
                "position": f"0x{search_index2:X}",
                "original_bytes": data_to_replace2.hex().upper(),
                "new_bytes": data_to_replace1.hex().upper()
            }
        ]

    # 检查是否真正修改了内容
    if new_contents == content:
        return True, False, None  # 文件未修改

    try:
        with open(file_path, "wb") as file:
            file.write(new_contents)
    except Exception as e:
        print(rainbow_text(f"写入文件时出错: {e}"))
        return False, False, None

    return True, True, modification_details  # 文件已修改，返回修改详情

def merge_files(folder_path, output_file_path):
    try:
        with open(output_file_path, "wb") as outfile:
            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 infile:
                        outfile.write(infile.read())
        return output_file_path
    except Exception as e:
        print(rainbow_text(f"合并文件时出错: {e}"))
        return None

def split_and_write_back(folder_path, merged_file_path, output_folder_path, modified_files):
    try:
        with open(merged_file_path, "rb") as merged_file:
            merged_contents = merged_file.read()
            file_offset = 0
            for filename in os.listdir(folder_path):
                file_path = os.path.join(folder_path, filename)
                if os.path.isfile(file_path):
                    file_size = os.path.getsize(file_path)
                    new_file_path = os.path.join(output_folder_path, filename)  # 新路径
                    modified_contents = merged_contents[file_offset:file_offset + file_size]
                    if modified_contents != open(file_path, "rb").read():
                        with open(new_file_path, "wb") as file:
                            file.write(modified_contents)
                        modified_files.append(new_file_path)  # 记录修改过的文件
                    file_offset += file_size
    except Exception as e:
        print(rainbow_text(f"回写文件时出错: {e}"))

def parse_py_file(py_file_path):
    try:
        with open(py_file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            matches = re.findall(r'\s*(\d+)\s*,\s*(\d+)\s*', content)
            code_list = [(int(original), int(new_)) for original, new_ in matches]
            return code_list
    except Exception as e:
        print(rainbow_text(f"解析.py 文件时出错: {e}"))
        return []

def get_feature_code_from_dat(file_path, search_hex):
    try:
        search_seq = bytes.fromhex(search_hex.replace(" ", ""))
        with open(file_path, "rb") as file:
            file_contents = file.read()

        matches = []
        start = 0
        while True:
            start = file_contents.find(search_seq, start)
            if start == -1:
                break
            matches.append(start)
            start += len(search_seq)

        if len(matches) >= 2:
            second_match_index = matches[1]
            feature_code = file_contents[second_match_index + len(search_seq):second_match_index + len(search_seq) + 2]
            return feature_code.hex().upper()
        else:
            print(f"在文件 {file_path} 中未找到第二个匹配项")
            return None
    except Exception as e:
        print(f"读取文件 {file_path} 时出错: {e}")
        return None

def search_files_in_path(path, search_hex):
    try:
        search_seq = bytes.fromhex(search_hex.replace(" ", ""))
    except ValueError as e:
        print(f"无效的16进制序列: {e}")
        return None

    for root, _, files in os.walk(path):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with open(file_path, "rb") as f:
                    content = f.read()
                if search_seq in content:
                    print(f"在文件 {file_path} 中找到匹配的16进制序列")
                    feature_code = get_feature_code_from_dat(file_path, search_hex)
                    if feature_code:
                        print(f"文件 {file_path} 的特征码为: {feature_code}")
                        return feature_code  # 返回找到的特征码
                    else:
                        print(f"文件 {file_path} 未找到特征码")
            except Exception as e:
                print(f"无法读取文件 {file_path}: {e}")
    return None

def get_feature_codes(folder_path, hex_str):
    """从文件夹中自动获取特征码"""
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                with open(file_path, 'rb') as f:
                    file_content = f.read()
                    file_hex = file_content.hex().upper()  # 将文件内容转换为十六进制字符串
                    if hex_str in file_hex:
                        index = file_hex.find(hex_str)
                        if index >= 150 * 2:  # 150字节 = 300个十六进制字符
                            first_byte_hex = file_hex[index - 300:index]
                            if len(first_byte_hex) >= 264:
                                first_byte_hex = first_byte_hex[218:-46]
                            else:
                                first_byte_hex = first_byte_hex[218:]
                            if len(first_byte_hex) >= 4:
                                first_two_bytes = first_byte_hex[:4]
                                last_two_bytes = first_byte_hex[-4:]
                                return first_two_bytes, last_two_bytes
                            else:
                                print("提取的内容不足，无法获取完整的字节")
                        else:
                            print("未找到足够的字节")
            except Exception as e:
                print(f"无法读取文件 {file_path}：{e}")
    return None, None

def organize_modified_files(modified_files, output_folder_path, target_base_path):
    """根据文件名的第5位数字将修改过的文件分类到对应的文件夹中"""
    for file_path in modified_files:
        file_name = os.path.basename(file_path)
        if len(file_name) >= 5 and file_name[4].isdigit():
            fifth_digit = file_name[4]  # 获取文件名的第5位数字
            if fifth_digit == '0':
                target_folder_name = "file_0"  # 如果第5位是0，放入file_0
            else:
                target_folder_name = f"file_{fifth_digit}000"  # 如果第5位是1-9，放入对应的file_1000等
            target_folder_path = os.path.join(target_base_path, target_folder_name)
            os.makedirs(target_folder_path, exist_ok=True)
            
            # 移动文件到目标文件夹
            shutil.move(file_path, os.path.join(target_folder_path, file_name))
            print(f"文件 {file_name} 已移动到 {target_folder_path}")



from colorama import Fore, Style

# 定义颜色常量
YELLOW = Fore.YELLOW
RESET = Style.RESET_ALL
RED = Fore.RED
GREEN = Fore.GREEN

def modify_uexp(unpacked_path, pak_name, config_file_path, config_file_path1, modify_path):
    # 固定输出路径
    output_folder_path = "/storage/emulated/0/无莫制作区/自动美化存放区/"
    if not os.path.isdir(output_folder_path):
        os.makedirs(output_folder_path)

    # 使用传入的配置文件路径
    code_list = parse_py_file(config_file_path)
    if not code_list:
        print(rainbow_text("配置文件中没有有效的代码对"))
        return

    code_list1 = parse_py_file(config_file_path1)
    if not code_list1:
        print(rainbow_text("配置文件中没有有效的代码对"))
        return

    # 自动获取伪实体和载具的文件夹路径
    icon_folder_path = "/storage/emulated/0/无莫制作区/小包存放区/伪实体小包/"  # 修复：使用正确的路径
    transparency_folder_path = "/storage/emulated/0/无莫制作区/小包存放区/载具小包/"  # 修复：使用正确的路径

    # 自动获取伪实体特征码
    print(rainbow_text("自动获取伪实体特征码..."))
    decimal_num = 901178  # 固定皮肤代码
    hex_str = DEC_to_HEX(decimal_num)
    icon_start_seq_hex, icon_end_seq_hex = get_feature_codes(icon_folder_path, hex_str)
    if not icon_start_seq_hex or not icon_end_seq_hex:
        print(rainbow_text("未能自动获取伪实体特征码，跳过伪实体修改"))
    else:
        print(rainbow_text(f"自动获取的起始特征码：{icon_start_seq_hex}"))
        print(rainbow_text(f"自动获取的结束特征码：{icon_end_seq_hex}"))

    # 自动获取载具特征码
    print(rainbow_text("自动获取载具特征码..."))
    transparency_search_hex = "A4 1E 06 00"  # 假设这是载具特征码的搜索序列
    transparency_start_seq_hex = search_files_in_path(transparency_folder_path, transparency_search_hex)
    if not transparency_start_seq_hex:
        print(rainbow_text("未能自动获取载具特征码，跳过载具修改"))
        return

    # 处理载具修改
    print(rainbow_text("开始处理载具修改..."))
    merged_transparency_file_path = merge_files(transparency_folder_path, os.path.join(output_folder_path, "merged_transparency.dat"))
    if not merged_transparency_file_path:
        print(rainbow_text("载具修改失败，未成功合并文件"))
        return

    modified_transparency_files = []  # 记录修改过的透明人文件
    for i, (original_decimal, new_decimal) in enumerate(code_list):
        current_color = next(color_cycle)  # 获取当前颜色
        print_divider(current_color)  # 打印分隔线
        print(rainbow_text(f"第{i + 1}组 {original_decimal} -> {new_decimal}", current_color))
        A = DEC_to_HEX(original_decimal, transparency_start_seq_hex)
        if A is None:
            print(rainbow_text(f"跳过无效的原皮美化代码: {original_decimal}", current_color))
            continue
        B = DEC_to_HEX(new_decimal, transparency_start_seq_hex)
        if B is None:
            print(rainbow_text(f"跳过无效的被改美化代码: {new_decimal}", current_color))
            continue

        success, modified, modification_details = modify_file_hex(merged_transparency_file_path, A, B)
        if not success:
            print(rainbow_text(f"处理载具代码失败: {original_decimal} -> {new_decimal}", current_color))
        else:
            if modified:
                print(rainbow_text(f"修改成功", current_color))
                if modification_details:
                    for detail in modification_details:
                        print(rainbow_text(f"位置: {detail['position']}, 原始字节: {detail['original_bytes']}, 新字节: {detail['new_bytes']}", current_color))
            else:
                print(rainbow_text(f"载具代码未修改: {original_decimal} -> {new_decimal}", current_color))
    split_and_write_back(transparency_folder_path, merged_transparency_file_path, output_folder_path, modified_transparency_files)
    os.remove(merged_transparency_file_path)  # 删除合并的文件


#局内伪实体
    folder_path = output_folder_path
    if not os.path.exists(folder_path):
        print(f"错误：小包目录不存在 {folder_path}")
        return

    # 配置文件路径
    skip_in_game_fake_entity = False  # 添加一个标志变量，默认为 False
    config_folder_path = "/storage/emulated/0/无莫制作区/全自动美化/配置/局内伪实体/"
    config_files = list_files_in_directory(config_folder_path, ".py")  # 列出所有.py配置文件

    if not config_files:
        print(YELLOW + "配置目录中没有 PY 文件！跳过局内伪实体修改。" + RESET)
        skip_in_game_fake_entity = True  # 如果目录中没有配置文件，跳过局内伪实体修改
    else:
        if len(config_files) == 1:
            # 如果配置文件夹中只有一个配置文件，则自动选择该文件
            config_file_path = os.path.join(config_folder_path, config_files[0])
            print(rainbow_text(f"已自动选择配置文件：{config_file_path}"))
        else:
            # 如果有多个配置文件，让用户选择
            print(rainbow_text("请选择局内伪实体配置文件："))
            for idx, file_name in enumerate(config_files, start=1):
                print(f"{idx}) {file_name}")
            while True:
                choice = input(rainbow_text("请输入选择的文件编号："))
                if choice.isdigit() and 1 <= int(choice) <= len(config_files):
                    config_file_path = os.path.join(config_folder_path, config_files[int(choice) - 1])
                    print(rainbow_text(f"已选择配置文件：{config_file_path}"))
                    break
                else:
                    print(rainbow_text("输入无效，请重新选择！"))

    # 检查是否跳过局内伪实体修改
    if skip_in_game_fake_entity:
        print("跳过局内伪实体修改，继续后续操作")
    else:
        # 加载配置文件并执行局内伪实体修改操作
        if not os.path.isfile(config_file_path):
            print(f"错误：配置文件不存在 {config_file_path}")
            return

        suffix_hex = transparency_start_seq_hex

        # 先修改局内贴图
        process_files(folder_path, config_file_path, suffix_hex, "局内贴图")
        # 再修改背包贴图
        process_files(folder_path, config_file_path, suffix_hex, "背包贴图")



#完美枪
    # 输入处理（自动去空格）
    folder_path = output_folder_path.strip()

    # 配置文件路径
    skip_perfect_gun = False  # 添加一个标志变量，默认为 False
    config_folder_path = "/storage/emulated/0/无莫制作区/全自动美化/配置/完美枪/"
    config_files = list_files_in_directory(config_folder_path, ".py")  # 列出所有.py配置文件

    if not config_files:
        print(YELLOW + "配置目录中没有 PY 文件！跳过完美枪修改。" + RESET)
        skip_perfect_gun = True  # 如果目录中没有配置文件，跳过完美枪修改
    else:
        if len(config_files) == 1:
            config_file_path = os.path.join(config_folder_path, config_files[0])  # 只有一个文件时直接使用
            print(rainbow_text(f"已自动选择配置文件：{config_file_path}"))
        else:
            print(rainbow_text("请选择完美枪配置文件："))
            for idx, file_name in enumerate(config_files, start=1):
                print(f"{idx}) {file_name}")
            while True:
                choice = input(rainbow_text("请输入选择的文件编号："))
                if choice.isdigit() and 1 <= int(choice) <= len(config_files):
                    config_file_path = os.path.join(config_folder_path, config_files[int(choice) - 1])
                    print(rainbow_text(f"已选择配置文件：{config_file_path}"))
                    break
                else:
                    print(rainbow_text("输入无效，请重新选择！"))

    # 检查路径有效性
    if not os.path.isdir(folder_path):
        print(f"错误：文件夹路径 {folder_path} 不存在")
        exit(1)
    if not os.path.isfile(config_file_path):
        print(f"错误：配置文件 {config_file_path} 不存在")
        exit(1)

    # 导入配置模块
    print("\n导入配置模块...")
    try:
        config_module = importlib.machinery.SourceFileLoader('config_module', config_file_path).load_module()
        integers = config_module.array
    except ImportError:
        print("配置错误")
        exit()
    except AttributeError:
        print("配置中格式错误")
        exit()
    if not integers:
        print("配置中格式错误")
        exit()

    # 检查是否跳过完美枪修改
    if skip_perfect_gun:
        print("跳过完美枪修改，继续后续操作")
    else:
        suffix = transparency_start_seq_hex

        # 合并文件内容
        print("\n合并文件内容...")
        merged_content, file_sizes = merge_files_in_folder1(folder_path)

        # 执行替换操作
        print("\n开始执行替换...")
        for idx, (a_val, b_val) in enumerate(integers, 1):
            print(f"处理第{idx}组: {a_val} → {b_val}")
            A = DEC_to_HEX1(a_val, suffix)
            B = DEC_to_HEX1(b_val, suffix)
            merged_content = modify_file_hex1(merged_content, A, B)

        # 写回文件
        print("\n写入修改后内容...")
        write_back_to_files1(folder_path, merged_content, file_sizes)

        print("\n操作完成！")



    # 组织修改过的文件到对应的文件夹
    target_base_path = os.path.join("/storage/emulated/0/无莫制作区/uexp打包/", pak_name)
    organize_modified_files(modified_transparency_files, output_folder_path, target_base_path)



    # 处理伪实体修改（替换为自动uexp美化逻辑）
    print(rainbow_text("开始处理伪实体修改..."))


    folder_path = "/storage/emulated/0/无莫制作区/小包存放区/伪实体小包/"
    output_folder = "/storage/emulated/0/无莫制作区/自动美化存放区/"

    marker1 = icon_start_seq_hex
    marker2 = icon_end_seq_hex

    merged_content, file_sizes = merge_files_in_folder1(folder_path)

    try:
        integers = parse_py_file(config_file_path1)  # 使用伪实体配置文件
    except Exception as e:
        print(f"{Fore.RED}配置错误: {e}")
        return

    if not integers:
        print(f"{Fore.RED}配置中格式错误")
        return

    color_index = 0  # 初始化颜色索引

    for group_num, (int1, int2) in enumerate(integers, start=1):
        color = rainbow[color_index % len(rainbow)]
        if int1 > 0xFFFFFFFF or int2 > 0xFFFFFFFF:
            print(f"{color}------------------------------------------------")
            print(f"{color}第{group_num}组 {int1} -> {int2}")
            print(f"{color}警告: 值过大，跳过这一组")
            color_index += 1  # 更新颜色索引
            continue  # 跳过这一组

        success, result = find_and_swap(merged_content, marker1, marker2, int1, int2)
        if success:
            merged_content = result
            print(f"{color}------------------------------------------------")
            print(f"{color}第{group_num}组 {int1} -> {int2}")
            print(f"{color}修改成功")
            color_index += 1  # 更新颜色索引
        else:
            print(f"{Style.BRIGHT + Fore.RED}------------------------------------------------")
            print(f"{Style.BRIGHT + Fore.RED}第{group_num}组 {int1} -> {int2}")
            print(f"{Style.BRIGHT + Fore.RED}修改失败")

    write_modified_files(output_folder, merged_content, file_sizes)

    # 比较文件并记录修改过的文件
    modified_fake_entity_files = []
    compare_and_record_modified_files(folder_path, output_folder, modified_fake_entity_files)

    print(f"{Style.BRIGHT + Fore.GREEN}全部修改完成")

    remove_pycache()

    # ==================== 水印处理部分 ====================
    print(rainbow_text("开始处理水印修改..."))
    
    # 水印配置和搜索目录
    WATERMARK_CONFIG_FOLDER = "/storage/emulated/0/无莫制作区/全自动美化/配置/水印/"
    WATERMARK_SEARCH_FOLDER = "/storage/emulated/0/无莫制作区/自动美化存放区/"
    
    skip_watermark = False
    
    # 检查水印配置目录
    if not os.path.exists(WATERMARK_CONFIG_FOLDER):
        os.makedirs(WATERMARK_CONFIG_FOLDER)
        print(f"已创建水印配置文件目录: {WATERMARK_CONFIG_FOLDER}")
        skip_watermark = True
        print("跳过水印修改，继续后续操作")
    else:
        configs = [f for f in os.listdir(WATERMARK_CONFIG_FOLDER) if f.endswith(".txt")]
        if not configs:
            print("水印配置目录中没有 TXT 文件！")
            skip_watermark = True
            print("跳过水印修改，继续后续操作")
        else:
            if len(configs) == 1:
                # 如果配置文件夹中只有一个配置文件，则自动选择该文件
                selected_config = os.path.join(WATERMARK_CONFIG_FOLDER, configs[0])
                print(f"自动选择水印配置文件: {selected_config}")
            else:
                # 如果有多个配置文件，让用户选择
                print("水印配置文件列表:")
                for i, f in enumerate(configs, 1):
                    print(f"{i}. {f}")

                while True:
                    choice = input("请选择水印配置文件(输入编号): ").strip()
                    if choice.isdigit() and 1 <= int(choice) <= len(configs):
                        selected_config = os.path.join(WATERMARK_CONFIG_FOLDER, configs[int(choice) - 1])
                        break
                    print("输入无效！")

    # 检查是否跳开水印修改
    if skip_watermark:
        print("跳开水印修改，继续后续操作")
    else:
        # 加载规则并执行水印修改操作
        rules = load_rules(selected_config)
        if not rules:
            print("加载水印规则失败")
        else:
            print("\n开始扫描水印...")
            process_files_watermark(WATERMARK_SEARCH_FOLDER, rules)
    # ==================== 水印处理结束 ====================

    # 组织修改过的文件到对应的文件夹
    target_base_path = os.path.join("/storage/emulated/0/无莫制作区/uexp打包/", pak_name)
    organize_modified_files(modified_fake_entity_files, output_folder_path, target_base_path)

    # 自动打包
    pack_pak_file(target_base_path, pak_name)

# ---------------------- 水印相关函数 ----------------------
def load_rules(config_file):
    """读取替换规则并验证 UTF-16-LE 编码"""
    rules = []
    try:
        with open(config_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                parts = line.split(maxsplit=1)
                if len(parts) != 2:
                    print(f"格式错误: 需要两个用空格分隔的文本 → {line}")
                    continue
                old_text, new_text = parts
                rules.append((old_text, new_text))
        return rules
    except Exception as e:
        print(f"读取配置文件失败: {e}")
        return []

def process_files_watermark(search_folder, rules):
    """以 UTF-16-LE 编码严格替换"""
    if not os.path.exists(search_folder):
        print(f"错误：搜索目录不存在 {search_folder}")
        return

    total = modified = 0
    for root, _, files in os.walk(search_folder):
        for file in files:
            file_path = os.path.join(root, file)
            total += 1
            try:
                with open(file_path, 'rb') as f:
                    data = bytearray(f.read())

                changed = False
                for old_text, new_text in rules:
                    old_bytes = old_text.encode('utf-16-le')
                    new_bytes = new_text.encode('utf-16-le')

                    if old_bytes in data:
                        data = data.replace(old_bytes, new_bytes)
                        changed = True
                        print(f"\n修改文件: {file_path}")
                        print(f"  匹配值: {old_bytes.hex(' ').upper()}")
                        print(f"  替换为: {new_bytes.hex(' ').upper()}")

                if changed:
                    modified += 1
                    with open(file_path, 'wb') as f:
                        f.write(data)

            except Exception as e:
                print(f"跳过 {file_path}（错误: {e}）")

    print(f"\n水印处理完成！扫描 {total} 个文件，修改 {modified} 个文件")

# ---------------------- 伪实体相关函数 ----------------------
def remove_pycache():
    """删除 __pycache__ 目录"""
    for dirpath, dirnames, filenames in os.walk('.'):
        if "__pycache__" in dirnames:
            pycache_dir = os.path.join(dirpath, "__pycache__")
            shutil.rmtree(pycache_dir)

def hex_to_bytes(hex_str):
    return bytes.fromhex(hex_str)

def bytes_to_hex(bytes_obj):
    return bytes_obj.hex()

def find_and_swap(data, marker1, marker2, int1, int2):
    """查找并交换两个整数位置"""
    marker1 = hex_to_bytes(marker1)
    marker2 = hex_to_bytes(marker2)
    marker_len = len(marker1)

    def find_marker_above_int(data, marker1, marker2, int_pos):
        pos1 = data.rfind(marker1, 0, int_pos)
        if pos1 == -1:
            return None, None

        pos2 = data.find(marker2, pos1 + marker_len, int_pos)
        if pos2 == -1:
            return None, None

        byte_start = pos1 + marker_len
        byte_end = pos2
        return byte_start, data[byte_start:byte_end]

    int1_pos = data.find(int1.to_bytes(4, byteorder='little'))
    int2_pos = data.find(int2.to_bytes(4, byteorder='little'))

    if int1_pos == -1 or int2_pos == -1:
        return False, f"{int1}或{int2}没有在dat中搜索到"

    byte1_start, byte1 = find_marker_above_int(data, marker1, marker2, int1_pos)
    if byte1_start is None:
        return False, f"{int1}没有在dat中搜索到"

    byte2_start, byte2 = find_marker_above_int(data, marker1, marker2, int2_pos)
    if byte2_start is None:
        return False, f"{int2}没有在dat中搜索到"

    temp_data = bytearray(data)
    temp_data[byte1_start:byte1_start + len(byte1)] = byte2
    temp_data[byte2_start:byte2_start + len(byte2)] = byte1
    data = bytes(temp_data)

    return True, data

def merge_files_in_folder1(folder_path):
    """合并文件夹中的所有文件内容"""
    merged_content = bytearray()
    file_sizes = {}
    try:
        for filename in sorted(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:
                    file_data = file.read()
                    merged_content += file_data
                    file_sizes[filename] = len(file_data)
        return merged_content, file_sizes
    except Exception as e:
        print(f"{Fore.RED}合并文件失败: {e}")
        exit(1)

def write_modified_files(output_folder, modified_content, file_sizes):
    """将修改后的内容写回文件"""
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    offset = 0
    try:
        for filename, file_size in file_sizes.items():
            output_path = os.path.join(output_folder, filename)
            with open(output_path, "wb") as file:
                file.write(modified_content[offset:offset+file_size])
            offset += file_size
    except Exception as e:
        print(f"{Fore.RED}写入文件失败: {e}")
        exit(1)

def calculate_md5(file_path):
    """计算文件的MD5哈希值"""
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def compare_and_record_modified_files(folder1, folder2, modified_files):
    """比较两个文件夹中的文件，记录修改过的文件"""
    try:
        # 获取 folder1 中的所有文件的 MD5 哈希值
        folder1_hashes = {}
        for filename in os.listdir(folder1):
            file_path = os.path.join(folder1, filename)
            if os.path.isfile(file_path):
                folder1_hashes[filename] = calculate_md5(file_path)

        # 遍历 folder2 中的文件，比较哈希值
        for filename in os.listdir(folder2):
            file_path = os.path.join(folder2, filename)
            if os.path.isfile(file_path):
                file_hash = calculate_md5(file_path)
                if filename not in folder1_hashes or folder1_hashes[filename] != file_hash:
                    modified_files.append(file_path)  # 记录修改过的文件路径
    except Exception as e:
        print(f"比较文件失败: {e}")

# ---------------------- 局内伪实体相关函数 ----------------------
def convert_decimal_to_hex(decimal_number):
    """十进制转十六进制（用于局内伪实体）"""
    hex_number = format(int(decimal_number), '08X')
    hex_array = [hex_number[i:i + 2] for i in range(0, 8, 2)]
    reversed_hex_array = hex_array[::-1]
    reversed_hex_number = ''.join(reversed_hex_array)
    print(f"{decimal_number}: 转换为 {reversed_hex_number}")
    return reversed_hex_number

def update_file_hex_data(file_contents, start_hex, end_hex, fixed_hex, suffix_hex):
    """更新文件十六进制数据（用于局内伪实体）"""
    search_seq1 = bytes.fromhex(start_hex + suffix_hex)
    search_seq2 = bytes.fromhex(end_hex + suffix_hex)
    fixed_bytes = 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:
        return file_contents, False

    start_index1 = file_contents.find(fixed_bytes, search_index1)
    start_index2 = file_contents.find(fixed_bytes, search_index2)

    if start_index1 == -1 or start_index2 == -1:
        print(f"未找到固定特征码 {fixed_hex}")
        return file_contents, False

    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, True

def concatenate_files(directory_path):
    """连接目录中的所有文件"""
    merged_content = bytearray()
    for filename in os.listdir(directory_path):
        file_path = os.path.join(directory_path, filename)
        if os.path.isfile(file_path):
            with open(file_path, "rb") as file:
                merged_content += file.read()
    return merged_content

def save_modified_files_to_directory(directory_path, modified_content, original_files):
    """将修改后的内容保存到目录"""
    offset = 0
    for filename in original_files:
        file_path = os.path.join(directory_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 compute_fixed_hex_from_suffix1(suffix_hex, mode):
    """根据后缀计算固定特征码"""
    if mode == "局内贴图":
        big_endian_suffix = suffix_hex[2:4] + suffix_hex[0:2]
        big_endian_int = int(big_endian_suffix, 16) + 0x11
        fixed_hex = format(big_endian_int, '04X')[2:4] + format(big_endian_int, '04X')[0:2]
    elif mode == "背包贴图":
        big_endian_suffix = suffix_hex[2:4] + suffix_hex[0:2]
        big_endian_int = int(big_endian_suffix, 16) + 0x0D
        fixed_hex = format(big_endian_int, '04X')[2:4] + format(big_endian_int, '04X')[0:2]
    return fixed_hex

def generate_new_suffix(fixed_hex, mode):
    """生成新的后缀"""
    if mode == "局内贴图":
        big_endian = bytes.fromhex(fixed_hex)
        little_endian = big_endian[::-1]
        little_endian_int = int(little_endian.hex(), 16)
        result_int = little_endian_int - 0x06
        result_hex = format(result_int, '04X')
        result_bytes = bytes.fromhex(result_hex)
        final_result_hex = result_bytes[::-1].hex()
    elif mode == "背包贴图":
        big_endian = bytes.fromhex(fixed_hex)
        little_endian = big_endian[::-1]
        little_endian_int = int(little_endian.hex(), 16)
        result_int = little_endian_int - 0x02
        result_hex = format(result_int, '04X')
        result_bytes = bytes.fromhex(result_hex)
        final_result_hex = result_bytes[::-1].hex()
    return final_result_hex

def read_config_file(config_file_path):
    """读取配置文件"""
    try:
        with open(config_file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            matches = re.findall(r'\s*(\d+)\s*,\s*(\d+)\s*', content)
            code_list = [(int(original), int(new_)) for original, new_ in matches]
            return code_list
    except Exception as e:
        print(f"解析配置文件时出错: {e}")
        return []

def process_files(directory_path, config_file_path, suffix_hex, mode):
    """处理文件（局内伪实体）"""
    fixed_hex = compute_fixed_hex_from_suffix1(suffix_hex, mode)
    print(f"开始修改 {mode}")

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

    array = read_config_file(config_file_path)
    not_found_pairs = []
    for pair in array:
        A = convert_decimal_to_hex(pair[0])
        B = convert_decimal_to_hex(pair[1])
        merged_content, modified = update_file_hex_data(merged_content, A, B, fixed_hex, suffix_hex)
        if not modified:
            not_found_pairs.append((A, B, pair[0], pair[1]))

    if not_found_pairs:
        print(f"\n尝试使用备用方案 ({mode})")
        new_suffix_hex = generate_new_suffix(fixed_hex, mode)
        print(f"备用方案特征码: {new_suffix_hex}")
        for A, B, a_val, b_val in not_found_pairs:
            print(f"重新处理 {a_val} → {b_val}")
            merged_content, modified = update_file_hex_data(merged_content, A, B, fixed_hex, new_suffix_hex)
            if not modified:
                print(f"警告: {a_val} → {b_val} 仍未找到")

    save_modified_files_to_directory(directory_path, merged_content, original_files)
    print(f"\n{mode} 修改完成！")

# ---------------------- 完美枪相关函数 ----------------------
def DEC_to_HEX1(decimal_number, suffix):
    """十进制转十六进制（用于完美枪）"""
    hex_number = format(int(decimal_number), '08X')
    hex_array = [hex_number[i:i+2] for i in range(0, 8, 2)]
    reversed_hex_array = hex_array[::-1]
    reversed_hex_number = ''.join(reversed_hex_array)
    final_hex_number = f"{reversed_hex_number}{suffix}"
    print(f"{decimal_number}: 转换为 {final_hex_number}")
    return final_hex_number

def modify_file_hex1(file_contents, A, B):
    """修改文件十六进制（用于完美枪）"""
    try:
        search_seq = bytes.fromhex(A)
        replace_seq = bytes.fromhex(B)
        new_contents = file_contents.replace(search_seq, replace_seq)
        return new_contents
    except ValueError as e:
        print(f"十六进制转换错误: {e}")
        exit(1)

def write_back_to_files1(folder_path, modified_content, file_sizes):
    """将修改后的内容写回文件（用于完美枪）"""
    offset = 0
    try:
        for filename, file_size in file_sizes.items():
            file_path = os.path.join(folder_path, filename)
            with open(file_path, "wb") as file:
                file.write(modified_content[offset:offset+file_size])
            offset += file_size
            print(f"更新文件: {filename}")
    except Exception as e:
        print(f"写入文件失败: {e}")
        exit(1)

# ---------------------- 打包和清理函数 ----------------------
def pack_pak_file(target_base_path, pak_name):
    """打包Pak文件"""
    directory = "/storage/emulated/0/无莫制作区/pak/"  # 待打包的pak文件夹路径
    file_path = os.path.join(directory, pak_name + ".pak")
    target_path = os.path.join("/storage/emulated/0/无莫制作区/uexp打包/", os.path.basename(file_path))
    
    # 复制文件
    copy_file(file_path, target_path)
    
    # 计算MD5
    md5 = hashlib.md5(open(target_path, 'rb').read()).hexdigest()
    
    # 打包命令 - 使用正确的 paks 路径
    command = f"\"{PAKS_PATH}\" -a -r \"{target_path}\" \"{os.path.splitext(target_path)[0]}\""
    subprocess.run(command, shell=True)
    
    # 打包完成提示
    toast("打包")
    
    # 计算新的MD5
    newmd5 = hashlib.md5(open(target_path, 'rb').read()).hexdigest()
    print(f"原MD5: {md5}")
    print(f"现MD5: {newmd5}")

def clear_directory(directory):
    """清空指定目录"""
    if os.path.exists(directory):
        for item in os.listdir(directory):
            item_path = os.path.join(directory, item)
            if os.path.isfile(item_path) or os.path.islink(item_path):
                os.remove(item_path)
            elif os.path.isdir(item_path):
                shutil.rmtree(item_path)
    else:
        print(f"目录不存在: {directory}")

def check_and_fix_config_file():
    """检查和修复配置文件"""
    config_dir_path = "/storage/emulated/0/无莫制作区/全自动美化/配置/"
    
    if not os.path.isdir(config_dir_path):
        print(f"错误：目录不存在 {config_dir_path}")
        return
    
    for root, dirs, files in os.walk(config_dir_path):
        for file in files:
            if file.endswith('.py'):
                config_file_path = os.path.join(root, file)
                try:
                    with open(config_file_path, 'r') as f:
                        lines = f.readlines()
                    
                    # 检查第一行是否为 'array = ['
                    if not lines[0].strip().startswith("array = ["):
                        lines.insert(0, "array = [\n")
                    
                    # 检查最后一行是否为 ']'
                    if not lines[-1].strip().endswith("]"):
                        lines.append("]\n")
                    
                    # 检查每行是否符合格式
                    fixed_lines = [lines[0]]
                    start_config = False
                    for line in lines[1:-1]:
                        comment = ""
                        if '#' in line:
                            comment = line.split('#', 1)[1].strip()
                            line = line.split('#', 1)[0].strip()
                        
                        if line:
                            if not re.match(r'^\s* $$\s*\d+\s*,\s*\d+\s*$$ \s*,', line):
                                numbers = re.findall(r'\d+', line)
                                if len(numbers) == 2:
                                    fixed_line = f"[{numbers[0]},{numbers[1]}],"
                                    line = fixed_line
                                else:
                                    continue
                            else:
                                line = line.rstrip(',') + ','
                            if comment:
                                line += f"  # {comment}"
                            fixed_lines.append(line + "\n")
                            start_config = True
                        elif start_config:
                            fixed_lines.append("\n")
                    
                    fixed_lines.append(lines[-1])
                    
                    if fixed_lines != lines:
                        with open(config_file_path, 'w') as f:
                            f.writelines(fixed_lines)
                except Exception as e:
                    print(f"修复配置文件 {config_file_path} 时出错: {e}")

def main():
    """主函数"""
    check_and_fix_config_file()
    pak_directory = "/storage/emulated/0/无莫制作区/pak/"
    
    # 清空自动美化存放区
    output_folder_path = "/storage/emulated/0/无莫制作区/自动美化存放区/"
    clear_directory(output_folder_path)

    # 选择载具配置文件
    config_folder_path = "/storage/emulated/0/无莫制作区/全自动美化/配置/载具/"
    config_files = list_files_in_directory(config_folder_path, ".py")
    if not config_files:
        print(rainbow_text("未找到载具配置文件"))
        return
    elif len(config_files) == 1:
        config_file_path = os.path.join(config_folder_path, config_files[0])
        print(rainbow_text(f"已自动选择配置文件：{config_file_path}"))
    else:
        print(rainbow_text("请选择载具配置文件："))
        for idx, file_name in enumerate(config_files, start=1):
            print(f"{idx}) {file_name}")
        while True:
            choice = input(rainbow_text("请输入选择的文件编号："))
            if choice.isdigit() and 1 <= int(choice) <= len(config_files):
                config_file_path = os.path.join(config_folder_path, config_files[int(choice) - 1])
                print(rainbow_text(f"已选择配置文件：{config_file_path}"))
                break
            else:
                print(rainbow_text("输入无效，请重新选择！"))

    # 选择伪实体配置文件
    config_folder_path = "/storage/emulated/0/无莫制作区/全自动美化/配置/伪实体/"
    config_files = list_files_in_directory(config_folder_path, ".py")
    if not config_files:
        print(rainbow_text("未找到伪实体配置文件"))
        return
    elif len(config_files) == 1:
        config_file_path1 = os.path.join(config_folder_path, config_files[0])
        print(rainbow_text(f"已自动选择配置文件：{config_file_path1}"))
    else:
        print(rainbow_text("请选择伪实体配置文件："))
        for idx, file_name in enumerate(config_files, start=1):
            print(f"{idx}) {file_name}")
        while True:
            choice = input(rainbow_text("请输入选择的文件编号："))
            if choice.isdigit() and 1 <= int(choice) <= len(config_files):
                config_file_path1 = os.path.join(config_folder_path, config_files[int(choice) - 1])
                print(rainbow_text(f"已选择配置文件：{config_file_path1}"))
                break
            else:
                print(rainbow_text("输入无效，请重新选择！"))

    # 解包操作
    unpacked_path, pak_name = list_pak_files_and_unpack(pak_directory)
    if unpacked_path:
        print(rainbow_text(f"解包完成，路径为: {unpacked_path}"))
        print(rainbow_text("开始抓小包操作..."))
        grab_small_packages(unpacked_path)
        print(rainbow_text("开始修改uexp操作..."))
        modify_uexp(unpacked_path, pak_name, config_file_path, config_file_path1, unpacked_path)
    else:
        print(rainbow_text("解包失败，程序退出"))

if __name__ == "__main__":
    main()