import tkinter as tk
from tkinter import messagebox
import random
import json
import os

WORD_FILE = "words_gui.json"
ERROR_FILE = "error_gui.json"


def init_word_data():
    default_words = {
        "apple": "苹果",
        "banana": "香蕉",
        "computer": "电脑",
        "book": "书本",
        "water": "水",
        "sun": "太阳",
        "moon": "月亮",
        "student": "学生",
        "teacher": "老师",
        "family": "家庭"
    }
    with open(WORD_FILE, "w", encoding="utf-8") as f:
        json.dump(default_words, f, ensure_ascii=False, indent=2)
    return default_words


def load_words(file_path):
    if not os.path.exists(file_path):
        if file_path == WORD_FILE:
            return init_word_data()
        else:
            return {}
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            return json.load(f)
    except Exception:
        return {}


def save_words(word_dict, file_path):
    with open(file_path, "w", encoding="utf-8") as f:
        json.dump(word_dict, f, ensure_ascii=False, indent=2)


class WordApp:
    def __init__(self, root):
        self.root = root
        self.root.title("英语单词背诵工具")
        self.root.geometry("520x380")
        self.words = load_words(WORD_FILE)
        self.error_words = load_words(ERROR_FILE)

        self.review_pool = []  # 当前背诵单词池
        self.current_eng = ""
        self.current_cn = ""
        self.mode_eng2cn = True  # True英译中，False中译英
        self.right_count = 0
        self.wrong_count = 0

        self.build_ui()

    def build_ui(self):
        # 标题
        tk.Label(self.root, text="英语单词背诵", font=("微软雅黑", 18)).pack(pady=10)

        # 单词显示区域
        self.label_word = tk.Label(self.root, text="点击【开始背诵】", font=("微软雅黑", 20), fg="#225599")
        self.label_word.pack(pady=12)

        # 输入框
        self.entry_answer = tk.Entry(self.root, font=("微软雅黑", 14), width=28)
        self.entry_answer.pack(pady=6)
        self.entry_answer.bind("<Return>", self.check_answer)

        # 结果提示
        self.label_result = tk.Label(self.root, text="", font=("微软雅黑", 13))
        self.label_result.pack(pady=6)

        # 统计信息
        self.label_stat = tk.Label(self.root, text="正确：0 | 错误：0", font=("微软雅黑", 11))
        self.label_stat.pack(pady=4)

        # 按钮容器
        frame_btn = tk.Frame(self.root)
        frame_btn.pack(pady=10)

        tk.Button(frame_btn, text="开始背诵全部", command=self.start_all, width=11).grid(row=0, column=0, padx=4)
        tk.Button(frame_btn, text="复习错题本", command=self.start_error, width=11).grid(row=0, column=1, padx=4)
        tk.Button(frame_btn, text="切换答题模式", command=self.switch_mode, width=11).grid(row=0, column=2, padx=4)

        frame_btn2 = tk.Frame(self.root)
        frame_btn2.pack(pady=4)
        tk.Button(frame_btn2, text="添加新单词", command=self.add_word_window, width=12).grid(row=0, column=0, padx=5)
        tk.Button(frame_btn2, text="下一题(跳过)", command=self.next_question, width=12).grid(row=0, column=1, padx=5)

    def switch_mode(self):
        self.mode_eng2cn = not self.mode_eng2cn
        if self.mode_eng2cn:
            messagebox.showinfo("模式切换", "当前模式：英文 → 中文")
        else:
            messagebox.showinfo("模式切换", "当前模式：中文 → 英文")

    def start_all(self):
        self.review_pool = list(self.words.items())
        self.start_review()

    def start_error(self):
        if not self.error_words:
            messagebox.showwarning("提示", "错题本为空！先去背诵产生错题")
            return
        self.review_pool = list(self.error_words.items())
        self.start_review()

    def start_review(self):
        random.shuffle(self.review_pool)
        self.right_count = 0
        self.wrong_count = 0
        self.label_stat.config(text=f"正确：{self.right_count} | 错误：{self.wrong_count}")
        self.next_question()

    def next_question(self):
        self.label_result.config(text="")
        self.entry_answer.delete(0, tk.END)
        if not self.review_pool:
            messagebox.showinfo("完成", f"本轮结束！\n正确{self.right_count} 错误{self.wrong_count}")
            self.label_word.config(text="背诵结束，请重新开始")
            return
        self.current_eng, self.current_cn = self.review_pool.pop(0)
        if self.mode_eng2cn:
            self.label_word.config(text=self.current_eng)
        else:
            self.label_word.config(text=self.current_cn)

    def check_answer(self, event=None):
        user_ans = self.entry_answer.get().strip()
        if not user_ans:
            return
        if self.mode_eng2cn:
            standard = self.current_cn
        else:
            standard = self.current_eng

        if user_ans == standard:
            self.label_result.config(text="✅ 回答正确！", fg="green")
            self.right_count += 1
        else:
            self.label_result.config(text=f"❌ 错误，答案：{standard}", fg="red")
            self.wrong_count += 1
            # 存入错题
            self.error_words[self.current_eng] = self.current_cn
            save_words(self.error_words, ERROR_FILE)

        self.label_stat.config(text=f"正确：{self.right_count} | 错误：{self.wrong_count}")
        self.root.after(1100, self.next_question)  # 1.1秒自动跳下一题

    def add_word_window(self):
        win = tk.Toplevel(self.root)
        win.title("添加单词")
        win.geometry("320x180")

        tk.Label(win, text="英文单词：").pack()
        eng_entry = tk.Entry(win, width=25)
        eng_entry.pack()

        tk.Label(win, text="中文释义：").pack()
        cn_entry = tk.Entry(win, width=25)
        cn_entry.pack()

        def save_new():
            eng = eng_entry.get().strip()
            cn = cn_entry.get().strip()
            if eng and cn:
                self.words[eng] = cn
                save_words(self.words, WORD_FILE)
                messagebox.showinfo("成功", f"单词 {eng}:{cn} 已添加")
                win.destroy()
            else:
                messagebox.showerror("错误", "单词和释义不能为空！")

        tk.Button(win, text="保存单词", command=save_new).pack(pady=12)


if __name__ == "__main__":
    window = tk.Tk()
    app = WordApp(window)
    window.mainloop()