import json
import os
import time
from datetime import datetime, timedelta

# --- 配置文件路径 ---
DATA_FILE = "vocab_lib.json"

class VocabApp:
    def __init__(self):
        self.vocab_list = []
        self.load_data()

    def load_data(self):
        """加载词库数据"""
        if not os.path.exists(DATA_FILE):
            print(f"📁 未找到词库文件，正在初始化默认单词...")
            self.init_sample_data()
        else:
            try:
                with open(DATA_FILE, 'r', encoding='utf-8') as f:
                    self.vocab_list = json.load(f)
                print(f"✅ 成功加载 {len(self.vocab_list)} 个单词。")
            except Exception as e:
                print(f"❌ 读取数据失败: {e}，将重置词库。")
                self.vocab_list = []

    def save_data(self):
        """保存数据到文件"""
        try:
            with open(DATA_FILE, 'w', encoding='utf-8') as f:
                json.dump(self.vocab_list, f, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"❌ 保存失败: {e}")

    def init_sample_data(self):
        """初始化一些示例单词"""
        # 确保新单词的状态是 new，且没有时间戳，这样会被强制筛选出来
        sample_words = [
            {"word": "safety", "meaning": "安全", "status": "new"},
            {"word": "safe", "meaning": "安全的", "status": "new"},
            {"word": "safely", "meaning": "安全地", "status": "new"}
        ]
        self.vocab_list = sample_words
        self.save_data()
        print("✨ 示例词库创建成功！")

    def add_word(self):
        """手动添加单词"""
        print("\n--- ➕ 添加新单词 ---")
        word = input("输入英文: ").strip()
        if not word: return
        
        # 检查是否重复
        for w in self.vocab_list:
            if w['word'] == word:
                print("⚠️ 该单词已存在！")
                return

        meaning = input("输入中文释义: ").strip()
        
        new_word = {
            "word": word,
            "meaning": meaning,
            "status": "new"  # 关键：状态设为 new
            # 注意：这里故意不设置 next_review，让它默认为 None
        }
        self.vocab_list.append(new_word)
        self.save_data()
        print(f"✅ 单词 '{word}' 添加成功！")

    def review(self):
        """开始复习模式"""
        print("\n--- 🧠 开始背诵 ---")
        
        now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 【核心修复】：筛选逻辑修改
        # 只要满足以下任一条件，就需要复习：
        # 1. 没有复习时间记录的 (新词)
        # 2. 复习时间小于等于现在的 (到期了)
        due_words = []
        for w in self.vocab_list:
            next_time = w.get('next_review')
            if next_time is None or next_time <= now_str:
                due_words.append(w)

        if not due_words:
            print("🎉 太棒了！目前没有待复习的单词。快去添加新单词吧！")
            return

        print(f"本次共有 {len(due_words)} 个单词需要复习。\n按回车键开始...")
        input()

        correct_count = 0

        for i, word_obj in enumerate(due_words):
            print("\n" * 50) 
            
            print(f"\n>>> 进度: [{i+1}/{len(due_words)}]")
            print("=" * 40)
            print(f"\n      单词 : 【  {word_obj['word']}  】\n")
            print("=" * 40)
            
            show_ans = input("\n提示: 按 [回车] 显示答案 (输入 q 退出): ")
            if show_ans.lower() == 'q': 
                break
            
            print("-" * 40)
            print(f"      释义 : {word_obj['meaning']}")
            print("-" * 40)
            
            grade = input("\n结果如何? (按 y=认识 / 其他键=忘了): ").lower()
            
            if grade == 'y':
                self.update_schedule(word_obj, success=True)
                correct_count += 1
                print("✅ 很好！下次复习时间已推迟。")
            else:
                self.update_schedule(word_obj, success=False)
                print("💪 没关系，稍后会再次出现。")
            
            time.sleep(0.8) 

        print("\n" + "="*30)
        print(f"背诵结束！本次正确率: {correct_count}/{len(due_words)}")
        print("="*30)
        self.save_data()

    def update_schedule(self, word_obj, success):
        """更新下次复习时间"""
        count = word_obj.get('review_count', 0)
        
        if success:
            # 如果认识，按照艾宾浩斯曲线推迟
            # 第一次背对：1天后；第二次：2天后...
            days_map = {0: 1, 1: 2, 2: 4, 3: 7, 4: 15} 
            days = days_map.get(count, 30) 
            next_time = datetime.now() + timedelta(days=days)
            word_obj['status'] = 'mastered' if days >= 15 else 'learning'
        else:
            # 如果忘了，1小时后马上再测
            next_time = datetime.now() + timedelta(hours=1) 
            word_obj['status'] = 'pending'
            # 这里的计数器不归零，但会缩短间隔

        # 写入时间字符串
        word_obj['next_review'] = next_time.strftime("%Y-%m-%d %H:%M:%S")
        word_obj['review_count'] = count + 1

    def list_words(self):
        """查看所有单词"""
        print(f"\n--- 📖 词库列表 (共{len(self.vocab_list)}个) ---")
        print(f"{'单词':<15} | {'状态':<10} | {'下次复习'}")
        print("-" * 50)
        for w in self.vocab_list:
            # 处理新词没有时间的情况
            r_time = w.get('next_review', '待背诵')
            if r_time == '待背诵': r_time = "立即"
            print(f"{w['word']:<15} | {w.get('status', 'new'):<10} | {r_time}")
        input("\n按回车返回菜单...")

# --- 主程序入口 ---
def main():
    app = VocabApp()
    
    while True:
        print("\n" + "="*30)
        print("   📘 Python 智能背单词 V3.0")
        print("="*30)
        print("1. 开始背诵 / 复习")
        print("2. 添加新单词")
        print("3. 查看词库列表")
        print("4. 退出程序")
        
        choice = input("\n请选择功能 [1-4]: ")
        
        if choice == '1':
            app.review()
        elif choice == '2':
            app.add_word()
        elif choice == '3':
            app.list_words()
        elif choice == '4':
            print("👋 再见，坚持背单词哦！")
            break
        else:
            print("❌ 输入无效，请重试。")

if __name__ == "__main__":
    main()