import os

def create_transformation_map(mapping_file):
    """
    读取 “词头扩充.txt” 文件，创建一个转换映射字典。
    键是'|'前的词，值是'|'后的词。
    例如：{'abdominal': 'abdominale', 'aberrant': 'aberrante'}
    """
    transformation_map = {}
    try:
        with open(mapping_file, 'r', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                if '|' in line:
                    parts = line.split('|')
                    base_word = parts[0].strip()
                    variant_word = parts[1].strip()
                    if base_word and variant_word:
                        transformation_map[base_word] = variant_word
    except FileNotFoundError:
        print(f"错误：映射文件 '{mapping_file}' 未找到。")
        return None
    return transformation_map

def process_source_file(source_file, output_file, transformation_map):
    """
    根据转换映射处理源文件，并生成输出文件。
    """
    try:
        with open(source_file, 'r', encoding='utf-8') as f_in, \
             open(output_file, 'w', encoding='utf-8') as f_out:
            
            lines = f_in.readlines()
            i = 0
            while i < len(lines):
                # 检查是否为一个完整的条目 (3行)
                if i + 2 >= len(lines):
                    # 如果文件末尾有不完整的行，直接写入并结束
                    f_out.writelines(lines[i:])
                    break

                headword = lines[i].strip()
                content = lines[i+1].strip()
                closing_tag = lines[i+2].strip()

                transformed = False

                # 新的判断逻辑：检查词头是否包含逗号 ','
                if ',' in headword:
                    # 提取逗号前的基础词 (例如从 "abdominal,e" 提取 "abdominal")
                    # 使用 split(',', 1) 确保只在第一个逗号处分割
                    base_word = headword.split(', ', 1)[0].strip()
                    
                    # 检查这个基础词是否存在于我们的转换映射中
                    if base_word in transformation_map:
                        variant_word = transformation_map[base_word]
                        
                        # 1. 写入修改后的原始条目，词头替换为基础词
                        f_out.write(f"{base_word}\n")
                        f_out.write(f"{content}\n")
                        f_out.write(f"{closing_tag}\n")
                        
                        # 2. 写入新增的链接条目
                        f_out.write(f"{variant_word}\n")
                        f_out.write(f"@@@LINK={base_word}\n")
                        f_out.write(f"{closing_tag}\n")
                        
                        transformed = True

                # 如果没有发生转换，则按原样写入条目
                if not transformed:
                    f_out.write(f"{headword}\n")
                    f_out.write(f"{content}\n")
                    f_out.write(f"{closing_tag}\n")
                
                # 移动到下一个条目 (步长为3)
                i += 3
                
    except FileNotFoundError:
        print(f"错误：源文件 '{source_file}' 未找到。")
        return False
        
    return True

# --- 主程序 ---
if __name__ == "__main__":
    # 定义文件名
    source_filename = "法汉小词典.txt"
    mapping_filename = "词头扩充.txt"
    output_filename = "法汉小词典_02.txt"

    print(f"步骤 1: 正在读取映射文件 '{mapping_filename}'...")
    trans_map = create_transformation_map(mapping_filename)

    if trans_map is not None:
        print(f"映射加载成功，共 {len(trans_map)} 条规则。")
        print(f"\n步骤 2: 正在处理源文件 '{source_filename}'...")
        
        success = process_source_file(source_filename, output_filename, trans_map)
        
        if success:
            print(f"\n处理完成！结果已保存到 '{output_filename}'。")
            # 打印生成的文件内容以供验证
            print("\n--- 生成的文件内容预览 ---")
            with open(output_filename, 'r', encoding='utf-8') as f:
                print(f.read())