# テキスト・ファイルから問題を読み込み、間違えた問題を復習する学習用ツール

import random
import os

# 問題用のテキストデータ
FILE_NAME = "data.txt"


def load_questions(filename):
    with open(filename, "r", encoding="utf-8") as f:
        lines = [line.strip() for line in f if line.strip()]

    if len(lines) % 2 != 0:
        raise ValueError("問題データの行数が奇数です。")

    pairs = []
    for i in range(0, len(lines), 2):
        pairs.append((lines[i], lines[i + 1]))

    return pairs


def ask_round(pairs):
    correct = 0
    total = 0
    wrong = []

    for q, a in pairs:
        user = input(f"{q} → ").strip()

        if user.lower() in ("exit", "quit", ":q"):
            return correct, total, wrong, True

        if user == "":
            print(f"× 無回答(正解:{a})\n")
            wrong.append((q, a))
        elif user == a:
            print("〇 正解!\n")
            correct += 1
        else:
            print(f"× 不正解(正解:{a})\n")
            wrong.append((q, a))

        total += 1

    return correct, total, wrong, False


def main():
    if not os.path.exists(FILE_NAME):
        print(f"{FILE_NAME} が見つかりません。")
        return

    pairs = load_questions(FILE_NAME)
    random.shuffle(pairs)

    print("平方・ルート練習")
    print("終了::q / exit\n")

    correct, total, wrong, aborted = ask_round(pairs)

    print("\n---- 結果 ----")
    print(f"{correct} / {total} 正解")

    round_no = 1
    while wrong and not aborted:
        print(f"\n=== 復習ラウンド {round_no} ===")
        random.shuffle(wrong)
        c, t, wrong, aborted = ask_round(wrong)
        print(f"{c} / {t} 正解")
        round_no += 1

    if not wrong and not aborted:
        print("\n🎉 全問正解!お疲れさまでした。")


if __name__ == "__main__":
    main()