import random
import tkinter as tk
from tkinter import messagebox, ttk


# 都道府県と県庁所在地
PREFECTURES = {
    "北海道": "札幌市", "青森県": "青森市", "岩手県": "盛岡市", "宮城県": "仙台市",
    "秋田県": "秋田市", "山形県": "山形市", "福島県": "福島市", "茨城県": "水戸市",
    "栃木県": "宇都宮市", "群馬県": "前橋市", "埼玉県": "さいたま市", "千葉県": "千葉市",
    "東京都": "新宿区", "神奈川県": "横浜市", "新潟県": "新潟市", "富山県": "富山市",
    "石川県": "金沢市", "福井県": "福井市", "山梨県": "甲府市", "長野県": "長野市",
    "岐阜県": "岐阜市", "静岡県": "静岡市", "愛知県": "名古屋市", "三重県": "津市",
    "滋賀県": "大津市", "京都府": "京都市", "大阪府": "大阪市", "兵庫県": "神戸市",
    "奈良県": "奈良市", "和歌山県": "和歌山市", "鳥取県": "鳥取市", "島根県": "松江市",
    "岡山県": "岡山市", "広島県": "広島市", "山口県": "山口市", "徳島県": "徳島市",
    "香川県": "高松市", "愛媛県": "松山市", "高知県": "高知市", "福岡県": "福岡市",
    "佐賀県": "佐賀市", "長崎県": "長崎市", "熊本県": "熊本市", "大分県": "大分市",
    "宮崎県": "宮崎市", "鹿児島県": "鹿児島市", "沖縄県": "那覇市",
}


class App073:
    """都道府県クイズ"""

    def __init__(self, root):
        self.root = root
        self.root.title("都道府県クイズ")
        self.root.geometry("620x480")
        self.root.configure(bg="#f8f9fc")
        self.score = 0
        self.total = 0
        self.weights = {p: 1 for p in PREFECTURES}  # 苦手問題ほど重みが大きい
        self.current = None
        self.choices = []
        self.mode = "県庁→都道府県"  # クイズの方向
        self._build_ui()
        self.next_question()

    def _build_ui(self):
        """UI を構築する"""
        title = tk.Frame(self.root, bg="#3776ab", pady=12)
        title.pack(fill=tk.X)
        tk.Label(title, text="都道府県クイズ", font=("Noto Sans JP", 16, "bold"),
                 bg="#3776ab", fg="white").pack()

        top = tk.Frame(self.root, bg="#f8f9fc", pady=10)
        top.pack(fill=tk.X)
        ttk.Label(top, text="出題方向:").pack(side=tk.LEFT, padx=(20, 4))
        self.mode_var = tk.StringVar(value=self.mode)
        cb = ttk.Combobox(top, textvariable=self.mode_var, state="readonly", width=18,
                          values=["県庁→都道府県", "都道府県→県庁"])
        cb.pack(side=tk.LEFT)
        cb.bind("<<ComboboxSelected>>", lambda e: self._on_mode_change())

        self.score_label = tk.Label(top, text="正解 0 / 0  (0%)",
                                    font=("Noto Sans JP", 12, "bold"),
                                    bg="#f8f9fc", fg="#3776ab")
        self.score_label.pack(side=tk.RIGHT, padx=20)

        self.q_label = tk.Label(self.root, text="",
                                font=("Noto Sans JP", 18, "bold"),
                                bg="white", relief=tk.GROOVE, pady=18)
        self.q_label.pack(fill=tk.X, padx=20, pady=10)

        self.btn_frame = tk.Frame(self.root, bg="#f8f9fc")
        self.btn_frame.pack(pady=10)
        self.choice_btns = []
        for i in range(4):
            b = tk.Button(self.btn_frame, text="", width=18, height=2,
                          font=("Noto Sans JP", 11),
                          command=lambda idx=i: self._answer(idx))
            b.grid(row=i // 2, column=i % 2, padx=8, pady=6)
            self.choice_btns.append(b)
        self.default_btn_bg = self.choice_btns[0].cget("bg")  # OS 既定のボタン色

        self.fb = tk.Label(self.root, text="", bg="#f8f9fc",
                          font=("Noto Sans JP", 12))
        self.fb.pack(pady=8)

        ttk.Button(self.root, text="次の問題", command=self.next_question).pack(pady=4)

    def _on_mode_change(self):
        """モード変更時の処理"""
        self.mode = self.mode_var.get()
        self.next_question()

    def _weighted_choice(self):
        """重み付きで問題を選ぶ（苦手問題が出やすい）"""
        items = list(self.weights.items())
        total = sum(w for _, w in items)
        r = random.uniform(0, total)
        s = 0
        for k, w in items:
            s += w
            if r <= s:
                return k
        return items[-1][0]

    def next_question(self):
        """新しい問題を出題する"""
        self.current = self._weighted_choice()
        if self.mode == "県庁→都道府県":
            q_text = f"「{PREFECTURES[self.current]}」が県庁所在地の都道府県は？"
            correct = self.current
            pool = [p for p in PREFECTURES if p != self.current]
        else:
            q_text = f"「{self.current}」の県庁所在地は？"
            correct = PREFECTURES[self.current]
            pool = [PREFECTURES[p] for p in PREFECTURES if p != self.current]
        self.q_label.config(text=q_text)
        choices = random.sample(pool, 3) + [correct]
        random.shuffle(choices)
        self.choices = choices
        self._correct_answer = correct
        for i, b in enumerate(self.choice_btns):
            b.config(text=choices[i], bg=self.default_btn_bg, state=tk.NORMAL)
        self.fb.config(text="")

    def _answer(self, idx: int):
        """回答ボタン押下時の処理"""
        ans = self.choices[idx]
        self.total += 1
        if ans == self._correct_answer:
            self.score += 1
            self.fb.config(text="正解！", fg="green")
            self.choice_btns[idx].config(bg="#c8e6c9")
            self.weights[self.current] = max(1, self.weights[self.current] - 1)
        else:
            self.fb.config(text=f"不正解。正解: {self._correct_answer}", fg="red")
            self.choice_btns[idx].config(bg="#ffcdd2")
            self.weights[self.current] += 3
        for b in self.choice_btns:
            b.config(state=tk.DISABLED)
        rate = int(self.score / self.total * 100) if self.total else 0
        self.score_label.config(text=f"正解 {self.score} / {self.total}  ({rate}%)")


if __name__ == "__main__":
    root = tk.Tk()
    app = App073(root)
    root.mainloop()
