#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复忙医考600题.txt格式
将答案从题干括号中提取出来，添加"正确答案：X"行
"""

import re

def fix_mangyikao():
    """修复忙医考600题.txt"""
    input_file = r"D:\cloud\OneDrive\root\0.学习资料\db\忙医考600题.txt"
    output_file = r"D:\cloud\OneDrive\root\0.学习资料\db\忙医考600题_fixed.txt"

    with open(input_file, 'r', encoding='utf-8') as f:
        content = f.read()

    lines = content.split('\n')
    result = []
    i = 0

    while i < len(lines):
        line = lines[i].strip()

        # 匹配题号行，答案在括号中
        # 支持多种格式：
        # - 1题目（ A ）
        # - 1. 题目（ A ）
        # - 13.题目（ D ）
        # - 19"题目"：（ D ）
        match = re.match(r'^(\d+)[.．、\s]*?(.*?)（\s*([A-Da-d])\s*）', line)
        if match:
            q_num = match.group(1)
            stem = match.group(2).strip()
            answer = match.group(3).upper()

            # 清理题干中的多余符号
            stem = stem.rstrip('：:')

            # 写入题目行（去掉括号中的答案）
            result.append(f"{q_num}. {stem}")

            # 读取选项行
            i += 1
            while i < len(lines):
                opt_line = lines[i].strip()
                if not opt_line:
                    i += 1
                    continue

                # 检查是否是下一题（带括号答案的）
                if re.match(r'^\d+[.．、\s]', opt_line) and '（' in opt_line and '）' in opt_line:
                    break

                # 检查是否是下一题（标准格式的）
                if re.match(r'^\d+[.．、]\s*\S', opt_line) and '（' not in opt_line:
                    break

                # 写入选项行
                result.append(opt_line)
                i += 1

            # 添加正确答案行
            result.append(f"正确答案：{answer}")
            result.append("")
            continue

        # 其他行直接写入
        result.append(lines[i])
        i += 1

    # 写入文件
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write('\n'.join(result))

    print(f"已修复: {output_file}")

if __name__ == "__main__":
    fix_mangyikao()
