import os
import re
from datetime import datetime
import glob

def parse_header_file(h_path):
    """
    解析.h文件，构建完整描述与数字的映射关系
    格式示例：61010 -- 6101000 -- 召回信标 -- 0x52ee0000
    """
    mapping = {}
    with open(h_path, 'r', encoding='utf-8') as f:
        for line in f:
            # 匹配格式：数字 -- 数字 -- 描述 -- 十六进制
            match = re.match(r'(\d+)\s*--\s*(\d+)\s*--\s*([^—]+?)\s*--', line)
            if match:
                short_num, long_num, description = match.groups()
                # 只使用长数字作为键，保留完整描述
                mapping[long_num] = description.strip()
    return mapping

def list_config_files(directory):
    """列出配置文件目录中的所有文件"""
    config_files = glob.glob(os.path.join(directory, '*'))
    return {i+1: {'path': f, 'name': os.path.basename(f), 'mtime': os.path.getmtime(f)}
            for i, f in enumerate(config_files) if os.path.isfile(f)}

def annotate_config_file(file_path, mapping):
    """
    为配置文件添加注释
    格式：2200101,3000100#描述1改描述2
    """
    annotated_lines = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line or not line[0].isdigit():
                # 跳过空行和非数字开头的行
                annotated_lines.append(line)
                continue
                
            # 提取行中的多个数字
            numbers = re.findall(r'\d+', line)
            if len(numbers) < 2:
                # 不是数字对，保留原样
                annotated_lines.append(line)
                continue
                
            # 获取两个描述
            desc1 = mapping.get(numbers[0])
            desc2 = mapping.get(numbers[1])
            
            if desc1 and desc2:
                # 添加注释：数字1,数字2#描述1改描述2
                annotated_lines.append(f"{line}#{desc1}改{desc2}")
            elif desc1 or desc2:
                # 部分描述缺失
                annotated_lines.append(f"{line}#未找到完整描述")
            else:
                # 无描述
                annotated_lines.append(line)
    
    return annotated_lines

def main():
    # 配置头文件路径
    H_FILE_PATH = "/data/user/0/com.termux/files/home/鬼戮美化工具1.0/代码表.h"
    
    # 配置文件目录路径
    CONFIG_DIR = "/data/user/0/com.termux/files/home/鬼戮美化工具1.0/配置文件/"
    
    print("正在解析头文件...")
    mapping = parse_header_file(H_FILE_PATH)
    
    if not mapping:
        print("无法解析头文件，请检查路径和格式")
        return
    
    print("\n可用的配置文件:")
    config_files = list_config_files(CONFIG_DIR)
    
    if not config_files:
        print("未找到配置文件")
        return
    
    # 显示文件列表供用户选择
    for num, file_info in config_files.items():
        print(f"{num}. {file_info['name']}")
    
    # 用户选择
    selection = input("\n请选择要处理的文件（输入编号或文件名）: ")
    selected_file = None
    
    # 处理数字选择
    try:
        if selection.isdigit():
            selected_num = int(selection)
            if selected_num in config_files:
                selected_file = config_files[selected_num]['path']
    except ValueError:
        pass
    
    # 处理文件名选择
    if not selected_file:
        for num, file_info in config_files.items():
            if selection == file_info['name']:
                selected_file = file_info['path']
                break
    
    if not selected_file:
        print("未找到匹配的文件")
        return
    
    file_name = os.path.basename(selected_file)
    print(f"\n开始处理文件: {file_name}")
    
    annotated_lines = annotate_config_file(selected_file, mapping)
    output_file = os.path.join(CONFIG_DIR, f"{os.path.splitext(file_name)[0]}已加注释.txt")
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write('\n'.join(annotated_lines))
    
    print(f"\n处理完成！结果已保存至: {output_file}")

if __name__ == "__main__":
    main()
