import json
import os
import random
import time
import tkinter as tk
from tkinter import ttk, messagebox


class App090:
    """英単語タイピング"""

    WORDS = {
        "easy": [
            "apple", "book", "cat", "dog", "egg", "fish", "go", "hat",
            "ice", "jump", "kid", "lion", "milk", "nose", "orange",
            "pig", "queen", "red", "sun", "tree", "up", "voice",
            "water", "yes", "zoo",
        ],
        "normal": [
            "morning", "evening", "school", "teacher", "student", "computer",
            "language", "library", "country", "weather", "history", "science",
            "picture", "garden", "kitchen", "holiday", "subject", "freedom",
            "journey", "promise",
        ],
        "hard": [
            "extraordinary", "responsibility", "communication", "international",
            "establishment", "infrastructure", "characteristic", "demonstration",
            "philosophical", "psychological", "consciousness", "manufacturer",
            "appreciation", "consideration",
        ],
    }
    GAME_DURATION = 30  # seconds
    SCORE_FILE = os.path.join(os.path.expanduser("~"), ".typing_scores.json")

    def __init__(self, root):
        self.root = root
        self.root.title("英単語タイピング")
        self.root.geometry("680x540")
        self.root.minsize(680, 540)
        self.root.configure(bg="#f8f9fc")
        self.level = "easy"
        self.current_word = ""
        self.correct_chars = 0
        self.correct_words = 0
        self.attempts = 0  # Enter を押した回数（正確度の分母）
        self.start_time = None
        self.remaining = self.GAME_DURATION
        self._timer_after = None
        self._build_ui()
        self._show_idle()

    def _build_ui(self):
        """UIを構築する"""
        title_frame = tk.Frame(self.root, bg="#3776ab", pady=12)
        title_frame.pack(fill=tk.X)
        tk.Label(
            title_frame, text="英単語タイピング",
            font=("Noto Sans JP", 16, "bold"),
            bg="#3776ab", fg="white"
        ).pack()

        main = tk.Frame(self.root, bg="#f8f9fc", padx=18, pady=12)
        main.pack(fill=tk.BOTH, expand=True)

        # 難易度
        ctrl = ttk.LabelFrame(main, text="設定", padding=10)
        ctrl.pack(fill=tk.X)
        ttk.Label(ctrl, text="難易度:").pack(side=tk.LEFT, padx=2)
        self.level_var = tk.StringVar(value="easy")
        ttk.Combobox(ctrl, textvariable=self.level_var,
                     values=["easy", "normal", "hard"],
                     width=8, state="readonly"
                     ).pack(side=tk.LEFT, padx=4)
        self.start_btn = ttk.Button(ctrl, text=f"スタート ({self.GAME_DURATION}秒)",
                                     command=self.start_game)
        self.start_btn.pack(side=tk.LEFT, padx=8)
        self.timer_var = tk.StringVar(value=f"残り {self.GAME_DURATION} 秒")
        tk.Label(ctrl, textvariable=self.timer_var, bg="#f8f9fc",
                 font=("Noto Sans JP", 12, "bold")).pack(side=tk.RIGHT, padx=4)

        # お題ラベル
        word_frame = ttk.LabelFrame(main, text="お題", padding=14)
        word_frame.pack(fill=tk.X, pady=8)
        self.word_var = tk.StringVar(value="準備中...")
        tk.Label(word_frame, textvariable=self.word_var, bg="white",
                 font=("Consolas", 22, "bold"), fg="#3776ab"
                 ).pack(fill=tk.X, ipady=8)

        # 入力欄
        input_frame = ttk.LabelFrame(main, text="ここに入力 (Enter で確定)", padding=10)
        input_frame.pack(fill=tk.X)
        self.input_var = tk.StringVar()
        self.entry = ttk.Entry(input_frame, textvariable=self.input_var,
                                font=("Consolas", 18))
        self.entry.pack(fill=tk.X)
        self.entry.bind("<Return>", lambda e: self._submit())

        # スコア表示
        self.status_var = tk.StringVar()
        tk.Label(main, textvariable=self.status_var, bg="#f8f9fc",
                 font=("Noto Sans JP", 11), justify=tk.LEFT
                 ).pack(anchor="w", pady=4)

        # ランキング
        rank_frame = ttk.LabelFrame(main, text="ハイスコアランキング (WPM)", padding=4)
        rank_frame.pack(fill=tk.BOTH, expand=True)
        cols = ("level", "wpm", "words", "accuracy")
        self.tree = ttk.Treeview(rank_frame, columns=cols, show="headings", height=6)
        for c, w, t in [("level", 80, "難易度"), ("wpm", 80, "WPM"),
                         ("words", 80, "単語数"), ("accuracy", 80, "正確度")]:
            self.tree.heading(c, text=t)
            self.tree.column(c, width=w, anchor="center")
        self.tree.pack(fill=tk.BOTH, expand=True)
        self._refresh_ranking()

    def _show_idle(self):
        """ゲーム待機状態の表示"""
        self.word_var.set("「スタート」ボタンを押して開始")
        self.input_var.set("")
        self.timer_var.set(f"残り {self.GAME_DURATION} 秒")
        self.status_var.set("難易度を選んで「スタート」を押してください。")

    def start_game(self):
        """ゲーム開始"""
        self.level = self.level_var.get()
        self.correct_chars = 0
        self.correct_words = 0
        self.attempts = 0
        self.remaining = self.GAME_DURATION
        self.start_time = time.time()
        self._next_word()
        self.input_var.set("")
        self.entry.focus_set()
        self.start_btn.state(["disabled"])
        self._tick()

    def _next_word(self):
        """次の単語を表示"""
        words = self.WORDS.get(self.level, self.WORDS["easy"])
        self.current_word = random.choice(words)
        self.word_var.set(self.current_word)

    def _submit(self):
        """Enter押下：単語の正誤判定"""
        if self.start_time is None:
            return
        typed = self.input_var.get().strip()
        self.attempts += 1  # 空欄で押した回も1回として数える
        if typed == self.current_word:
            self.correct_words += 1
            self.correct_chars += len(typed) + 1  # +1 for space
        # 間違いでも次へ進む
        self.input_var.set("")
        self._next_word()

    def _tick(self):
        """1秒ごとのタイマー"""
        if self.start_time is None:
            return
        elapsed = time.time() - self.start_time
        self.remaining = max(0, self.GAME_DURATION - int(elapsed))
        self.timer_var.set(f"残り {self.remaining} 秒")
        self.status_var.set(
            f"正解単語: {self.correct_words} 個 / 入力文字数: {self.correct_chars}"
        )
        if self.remaining > 0:
            self._timer_after = self.root.after(200, self._tick)
        else:
            self._end_game()

    def _end_game(self):
        """ゲーム終了処理"""
        elapsed = max(1, time.time() - (self.start_time or time.time()))
        wpm = self.correct_chars / 5.0 / (elapsed / 60.0)
        # 正確度: Enter を押した回数のうち正解した単語の割合（0回なら 0%）
        accuracy = self.correct_words / self.attempts * 100 if self.attempts else 0.0
        self.start_time = None
        self.start_btn.state(["!disabled"])
        msg = (f"終了！\nWPM: {wpm:.1f}\n"
               f"正解単語数: {self.correct_words}\n難易度: {self.level}")
        messagebox.showinfo("結果", msg)
        self._save_score({
            "level": self.level,
            "wpm": round(wpm, 1),
            "words": self.correct_words,
            "accuracy": f"{accuracy:.0f}%",
        })
        self._refresh_ranking()
        self._show_idle()

    def _save_score(self, entry):
        """スコアをファイルに保存"""
        scores = self._load_scores()
        scores.append(entry)
        scores.sort(key=lambda x: -x.get("wpm", 0))
        scores = scores[:10]
        try:
            with open(self.SCORE_FILE, "w", encoding="utf-8") as f:
                json.dump(scores, f, ensure_ascii=False, indent=2)
        except OSError:
            pass

    def _load_scores(self):
        """スコアをファイルから読込"""
        if not os.path.exists(self.SCORE_FILE):
            return []
        try:
            with open(self.SCORE_FILE, "r", encoding="utf-8") as f:
                data = json.load(f)
            return data if isinstance(data, list) else []
        except (OSError, json.JSONDecodeError):
            return []

    def _refresh_ranking(self):
        """ランキング表示を更新"""
        self.tree.delete(*self.tree.get_children())
        for s in self._load_scores():
            self.tree.insert("", tk.END, values=(
                s.get("level", "?"), s.get("wpm", 0),
                s.get("words", 0), s.get("accuracy", "-"),
            ))


if __name__ == "__main__":
    root = tk.Tk()
    app = App090(root)
    root.mainloop()
