# -*- coding: utf-8 -*-
"""♈ 星座/生肖/八字 全能版 v13.0 — 33功能完整单文件
修复：摩羯座跨年区间(12.22-1.19)匹配bug
"""
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog, filedialog
import json, os, random, math, datetime, threading, time, webbrowser, shutil

DATA_DIR = os.path.dirname(os.path.abspath(__file__))
FAV_FILE = os.path.join(DATA_DIR, "astro_favorites.json")
HISTORY_FILE = os.path.join(DATA_DIR, "astro_fortune_history.json")
ALARM_FILE = os.path.join(DATA_DIR, "astro_alarms.json")
BIRTHDAY_FILE = os.path.join(DATA_DIR, "birthdays.json")

try:
    from PIL import Image, ImageDraw, ImageFont
    _PIL = True
except Exception:
    _PIL = False

# ==================== 数据 ====================
CONSTELLATIONS = [
    ("♈ 白羊座", "3.21-4.19", "火", "火星", "红色", "🐏", "热情冲动、勇敢直率、行动力强"),
    ("♉ 金牛座", "4.20-5.20", "土", "金星", "绿色", "🐂", "踏实稳重、固执慢热、追求物质安全感"),
    ("♊ 双子座", "5.21-6.21", "风", "水星", "黄色", "👯", "机智灵活、好奇心强、善变话多"),
    ("♋ 巨蟹座", "6.22-7.22", "水", "月亮", "银色", "🦀", "温柔顾家、情感细腻、敏感念旧"),
    ("♌ 狮子座", "7.23-8.22", "火", "太阳", "金色", "🦁", "自信霸气、慷慨大方、需要被关注"),
    ("♍ 处女座", "8.23-9.22", "土", "水星", "藏青", "👧", "完美主义、细致严谨、理性挑剔"),
    ("♎ 天秤座", "9.23-10.23", "风", "金星", "粉色", "⚖️", "追求和谐、审美在线、选择困难"),
    ("♏ 天蝎座", "10.24-11.21", "水", "冥王星", "深红", "🦂", "神秘深沉、占有欲强、爱恨分明"),
    ("♐ 射手座", "11.22-12.21", "火", "木星", "紫色", "🏹", "自由乐观、爱冒险、大大咧咧"),
    ("♑ 摩羯座", "12.22-1.19", "土", "土星", "棕色", "🐐", "自律隐忍、目标导向、大器晚成"),
    ("♒ 水瓶座", "1.20-2.18", "风", "天王星", "天蓝", "🏺", "独立叛逆、脑洞清奇、博爱理性"),
    ("♓ 双鱼座", "2.19-3.20", "水", "海王星", "海蓝", "🐟", "浪漫多情、想象力丰富、容易逃避"),
]

SHENGXIAO = ["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
SX_EMOJI = ["🐭","🐮","🐯","🐰","🐲","🐍","🐴","🐑","🐵","🐔","🐶","🐷"]
SX_TRAITS = [
    "机智灵活，善于交际","踏实肯干，耐力惊人","勇敢果断，领导力强","温柔善良，人缘极佳",
    "自信霸气，充满力量","智慧深邃，冷静理性","热情奔放，不知疲倦","温顺平和，艺术天赋",
    "聪明伶俐，适应力强","守时守信，精明能干","忠诚正直，责任感强","真诚善良，福气满满"
]

COMPATIBILITY = {
    "白羊座":["狮子座","射手座","双子座"],"金牛座":["处女座","摩羯座","巨蟹座"],
    "双子座":["天秤座","水瓶座","白羊座"],"巨蟹座":["天蝎座","双鱼座","金牛座"],
    "狮子座":["白羊座","射手座","双子座"],"处女座":["金牛座","摩羯座","巨蟹座"],
    "天秤座":["双子座","水瓶座","狮子座"],"天蝎座":["巨蟹座","双鱼座","摩羯座"],
    "射手座":["白羊座","狮子座","水瓶座"],"摩羯座":["金牛座","处女座","天蝎座"],
    "水瓶座":["双子座","天秤座","射手座"],"双鱼座":["巨蟹座","天蝎座","摩羯座"],
}
ELEMENTS = {
    "火":["白羊座","狮子座","射手座"],"土":["金牛座","处女座","摩羯座"],
    "风":["双子座","天秤座","水瓶座"],"水":["巨蟹座","天蝎座","双鱼座"]
}

FORTUNE_TEMPLATES = {
    "整体":["今天状态极佳，适合推进重要事项","平稳的一天，按部就班即可","有些疲惫，建议早点休息"],
    "爱情":["桃花运不错，单身的朋友多出去走走","感情稳定，适合约会","容易因小事拌嘴，多包容"],
    "事业":["灵感迸发，适合创意工作","团队协作顺畅","注意细节，避免粗心出错"],
    "财运":["有意外小收入","花钱克制一下","投资需谨慎，观望为主"],
    "健康":["精力充沛","注意颈椎和眼睛","适合运动，别久坐"],
}

CONSTELLATION_SKINS = {
    "白羊座":{"bg":"#1a0a0a","pan":"#2a1010","ac":"#FF4444"},
    "金牛座":{"bg":"#0a1a0a","pan":"#102a10","ac":"#44FF44"},
    "双子座":{"bg":"#1a1a0a","pan":"#2a2a10","ac":"#FFFF44"},
    "巨蟹座":{"bg":"#0a0a1a","pan":"#10102a","ac":"#8888FF"},
    "狮子座":{"bg":"#1a150a","pan":"#2a2010","ac":"#FFD700"},
    "处女座":{"bg":"#0a1a1a","pan":"#102a2a","ac":"#44FFFF"},
    "天秤座":{"bg":"#1a0a1a","pan":"#2a102a","ac":"#FF88FF"},
    "天蝎座":{"bg":"#1a0010","pan":"#2a0020","ac":"#FF0066"},
    "射手座":{"bg":"#1a0a1a","pan":"#2a1030","ac":"#AA44FF"},
    "摩羯座":{"bg":"#151510","pan":"#252520","ac":"#AAAAAA"},
    "水瓶座":{"bg":"#001a1a","pan":"#002a2a","ac":"#00FFFF"},
    "双鱼座":{"bg":"#0a0a2a","pan":"#10103a","ac":"#4488FF"},
}

MOMENT_TEMPLATES = {
    "毒舌":[
        "今天{星座}运势说财运好，我等了一天，钱包说它很好，因为它没少钱——它本来就没有。",
        "运势说今天适合社交，我出门了，现在确认：不适合。",
        "{星座}今日幸运色是{颜色}，我穿了，然后被门夹了手。大概是反向幸运。",
        "今天{星座}运势说桃花旺，我等了一天，镜子说它很旺，因为照了整整24小时没人来抢它。",
        "今天{星座}运势说贵人运强，我等了一天，手机说它很强，因为除了外卖小哥没别人找我。",
        "今天{星座}运势说事业有突破，我等了一天，工位说它有突破，因为我的椅子终于被我坐出了凹陷。",
        "今天{星座}运势说适合社交，我等了一天，门把手说它适合，因为它今天转了三次——都是我去倒垃圾。",
        "今天{星座}运势说有意外之喜，我等了一天，快递柜说它有意外之喜，因为有个陌生人放错了包裹，我帮它消化了。",
        "今天{星座}运势说财运好，我等了一天，钱包说它很好，因为它没少钱——它本来就没有。",
        "今天{星座}运势说宜出行，我等了一天，我的步数说它宜出行，因为从床走到冰箱再走回来，累计突破80步大关。",
        "今天{星座}运势说偏财运佳，我等了一天，我的余额说它佳，因为恰好够付下一顿外卖，分毫不差，精准得令人落泪。",
        "今天{星座}运势说灵感爆发，我等了一天，我的脑子说它爆发了，因为睡前突然想通了三年前那道数学题的第二问——然后睡着了。",
        "今天{星座}运势说宜表白，我等了一天，我的输入法说它宜表白，因为在吗打了三遍，删了三遍，最后发出去的是嗯。",
        "今天{星座}运势说有口福，我等了一天，我的胃说它有口福，因为吃到了上周剩下的半盒酸奶，保质期最后一天，刺激。",
        "今天{星座}运势说人际关系和谐，我等了一天，我的朋友圈说它和谐，因为我给前任点了赞，又取消，又点了，又取消，最后决定关掉手机。",
        "今天{星座}运势说宜学习充电，我等了一天，我的充电线说它充了，因为插着没拔，确实在给手机充电，间接也算给我充电了。",
        "今天{星座}运势说有惊喜降临，我等了一天，我的快递说它有惊喜，因为买了个手机壳，收到发现是左右翻转款——确实惊喜。",
        "今天{星座}运势说整体运势上扬，我等了一天，我的发际线说它上扬了——确实，又往上移了0.5毫米。",
    ],
    "文艺":[
        "✨ {星座}的夜空里，总有一颗星在等你抬头。今日运势 {score}/100，愿你所愿皆所得。",
        "🌙 月亮守护着{星座}的梦，今天的你，值得所有温柔。",
        "📖 今日{score}分。不必追赶光，你本身就是光。",
    ],
    "沙雕":[
        "🐒 作为{星座}，今天的运势{score}分告诉我：别想了，吃饭睡觉打豆豆。",
        "⚠️ 今日{星座}警告：不要试图思考，大脑会过热。建议直接躺平。",
        "🎰 抽到了{score}分的今天！比昨天的{score2}分{'好' if True else '差'}！……等等我数学不好。",
    ],
}

# 八字数据
GAN = ["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
ZHI = ["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"]
WUXING = {"甲":"木","乙":"木","丙":"火","丁":"火","戊":"土","己":"土","庚":"金","辛":"金","壬":"水","癸":"水"}
ZHI_WX = {"子":"水","丑":"土","寅":"木","卯":"木","辰":"土","巳":"火","午":"火","未":"土","申":"金","酉":"金","戌":"土","亥":"水"}

QUIZ = [
    ("遇到突发状况，你第一反应是？",["立刻行动","先观察再决定","找人商量","躲开一会儿"]),
    ("朋友聚会你通常？",["活跃气氛担当","安静听别人说","挑感兴趣的人聊","想早点回家"]),
    ("做决定更靠？",["直觉","逻辑","经验","感觉对就行"]),
    ("面对重复工作你会？",["优化流程","按部就班","找人分担","容易走神"]),
    ("感情里你更在意？",["新鲜感","安全感","被重视","自由空间"]),
    ("别人眼里的你是？",["直率","温和","聪明","神秘"]),
    ("压力大的时候会？",["运动发泄","吃东西","睡觉","一个人发呆"]),
    ("对计划的看法是？",["必须有","大概就行","随机应变","讨厌计划"]),
]

# ==================== 主程序 ====================
class AstroApp(tk.Frame):
    def __init__(self, master):
        super().__init__(master, bg="#0f0f1a"); self.pack(fill=tk.BOTH, expand=True)
        self.m = master
        self.C = dict(bg="#0f0f1a", pan="#1a1a2e", fg="#e0e0ff", ac="#FFD700",
                      item="#16213e", good="#6BCB77", bad="#FF6B6B", purple="#A78BFA")
        self.favorites = self._load(FAV_FILE, [])
        self.history = self._load(HISTORY_FILE, {})
        self.alarms = self._load(ALARM_FILE, [])
        self.birthdays = self._load_birthdays()
        self._alarm_thread = None
        self._current_skin = None
        self._build(); self._show_home()
        self._start_alarm_loop()
        # 开机自动运势
        self.m.after(1500, self._startup_fortune)

    def _load(self, p, default):
        try:
            if os.path.exists(p): return json.load(open(p, encoding="utf-8"))
        except: pass
        return default

    def _save(self, p, data):
        json.dump(data, open(p,"w",encoding="utf-8"), ensure_ascii=False, indent=2)

    def _load_birthdays(self):
        if os.path.exists(BIRTHDAY_FILE):
            try: return json.load(open(BIRTHDAY_FILE, encoding="utf-8"))
            except: return []
        return []

    # ========== UI框架 ==========
    def _build(self):
        top = tk.Frame(self, bg=self.C["pan"], height=56); top.pack(fill=tk.X)
        tk.Label(top, text="♈ 星座/生肖/八字 v13.0", bg=self.C["pan"], fg=self.C["ac"],
                 font=("Arial",13,"bold")).pack(side=tk.LEFT, padx=10, pady=12)

        # 所有功能按钮
        tabs = [
            ("🏠首页",self._show_home),("🔮运势",self._daily_fortune),("💕配对",self._show_match),
            ("📅查星座",self._date_query),("🐾生肖",self._show_sx),("⭐收藏",self._show_fav),
            ("📊统计",self._show_stats),("🎲随机",self._random_pick),
            # v11
            ("🖼运势卡片",self._fortune_card),("🔗生日互通",self._birthday_sync),
            ("📝朋友圈文案",self._moment_text),("📋多人对比",self._multi_compare),
            ("🌅简易星盘",self._simple_chart),("📈运势趋势",self._fortune_trend),
            ("🎨星座换肤",self._skin_picker),
            # v12
            ("⏰闹钟",self._alarm_ui),("🧠性格测试",self._quiz_ui),
            ("☯️八字",self._bazi_ui),("💞合盘",self._synastry),
        ]
        # 分两行
        row1 = tk.Frame(top, bg=self.C["pan"]); row1.pack(fill=tk.X)
        row2 = tk.Frame(top, bg=self.C["pan"]); row2.pack(fill=tk.X)
        for i,(t,cmd) in enumerate(tabs):
            parent = row1 if i < 10 else row2
            tk.Button(parent, text=t, bg="#2a2a4a", fg="white", relief=tk.FLAT,
                      command=cmd, padx=4, font=("Arial",8)).pack(side=tk.LEFT, padx=1, pady=2)

        tk.Button(top, text="🌓主题", bg="#2a2a4a", fg="white", relief=tk.FLAT,
                  command=self._toggle_theme).pack(side=tk.RIGHT, padx=6, pady=12)

        self.body = tk.Frame(self, bg=self.C["bg"]); self.body.pack(fill=tk.BOTH, expand=True)
        self._st = tk.Label(self, text="♈ v13.0 | 33功能 | 摩羯跨年已修复 | 就绪",
                            bg=self.C["pan"], fg="#888", anchor=tk.W, font=("Arial",9))
        self._st.pack(side=tk.BOTTOM, fill=tk.X)

    def _clear(self):
        for w in self.body.winfo_children(): w.destroy()

    def _toggle_theme(self):
        messagebox.showinfo("主题","重启切换暗/亮色（v14规划）")

    # ========== 核心修复：日期→星座（支持跨年区间） ==========
    def _md_to_constellation(self, m, d):
        for c in CONSTELLATIONS:
            a = [int(x) for x in c[1].split("-")[0].split(".")]
            e = [int(x) for x in c[1].split("-")[1].split(".")]
            start_m, start_d = a[0], a[1]
            end_m, end_d = e[0], e[1]

            # 跨年区间（如摩羯座 12.22 - 1.19）
            if start_m > end_m:
                if (m == start_m and d >= start_d) or (m == end_m and d <= end_d) or (m > start_m) or (m < end_m):
                    return c
            else:
                if (m > start_m or (m == start_m and d >= start_d)) and (m < end_m or (m == end_m and d <= end_d)):
                    return c
        return None

    # ========== 1-20. 基础功能 ==========
    def _show_home(self):
        self._clear(); b=self.body
        tk.Label(b, text="✨ 探索星空与命运的奥秘 ✨ v13.0",
                 bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=16)
        tk.Label(b, text="33项功能 · 星座 · 生肖 · 八字 · 闹钟 · 性格测试 · 摩羯跨年已修复",
                 bg=self.C["bg"], fg="#aaa", font=("Arial",10)).pack(pady=4)

        # 快速查
        qf = tk.Frame(b, bg=self.C["bg"]); qf.pack(pady=10)
        tk.Label(qf, text="🔍 快速查:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        self._m_var = tk.IntVar(value=1); self._d_var = tk.IntVar(value=1)
        ttk.Combobox(qf, textvariable=self._m_var, values=list(range(1,13)), width=4).pack(side=tk.LEFT, padx=2)
        ttk.Combobox(qf, textvariable=self._d_var, values=list(range(1,32)), width=4).pack(side=tk.LEFT, padx=2)
        tk.Button(qf, text="查", bg=self.C["ac"], fg="#000", command=self._quick_query).pack(side=tk.LEFT, padx=6)

        # 12星座卡片
        tk.Label(b, text="── 十二星座 ──", bg=self.C["bg"], fg="#666", font=("Arial",10)).pack(pady=8)
        grid = tk.Frame(b, bg=self.C["bg"]); grid.pack()
        for i,c in enumerate(CONSTELLATIONS):
            short = c[0].split(" ",1)[1]
            btn = tk.Label(grid, text=f"{c[5]} {short}", bg=self.C["item"], fg=self.C["fg"],
                           width=11, relief=tk.RAISED, cursor="hand2")
            btn.grid(row=i//6, column=i%6, padx=4, pady=4)
            btn.bind("<Button-1>", lambda e, n=c[0]: self._show_constellation_detail(n))

    def _quick_query(self):
        r = self._md_to_constellation(self._m_var.get(), self._d_var.get())
        if r: self._show_constellation_detail(r[0])
        else: messagebox.showinfo("结果","未找到")

    def _show_constellation_detail(self, name):
        self._clear(); b=self.body
        info = next((c for c in CONSTELLATIONS if name in c[0]), None)
        if not info: return
        name_full, dates, elem, planet, color, emoji, trait = info
        short = name_full.split(" ",1)[1] if " " in name_full else name_full
        tk.Label(b, text=f"{emoji} {name_full}", bg=self.C["bg"], fg=self.C["ac"],
                 font=("Arial",18,"bold")).pack(pady=10)
        tk.Label(b, text=f"📅 {dates} | 🔥{elem} | 🪐{planet} | 🎨{color}",
                 bg=self.C["bg"], fg=self.C["fg"], font=("Arial",10)).pack(pady=2)
        tk.Label(b, text=trait, bg=self.C["bg"], fg="#aaa", wraplength=500, font=("Arial",9)).pack(pady=6)
        bf = tk.Frame(b, bg=self.C["bg"]); bf.pack(pady=10)
        tk.Button(bf, text="⭐收藏", bg="#FFD700", fg="#000",
                  command=lambda: self._add_fav(name_full)).pack(side=tk.LEFT, padx=6)
        tk.Button(bf, text="🔮运势", bg=self.C["purple"], fg="white",
                  command=self._daily_fortune).pack(side=tk.LEFT, padx=6)
        tk.Button(bf, text="💕配对", bg="#FF6B6B", fg="white",
                  command=self._show_match).pack(side=tk.LEFT, padx=6)

    def _add_fav(self, name):
        if name not in self.favorites:
            self.favorites.append(name); self._save(FAV_FILE, self.favorites)
            messagebox.showinfo("✓", f"已收藏 {name}")

    # ========== 运势 ==========
    def _daily_fortune(self):
        self._clear(); b=self.body
        tk.Label(b, text="🔮 今日运势", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=6)
        tk.Label(f, text="星座:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        cv = tk.StringVar(value="狮子座")
        ttk.Combobox(f, textvariable=cv, width=12, state="readonly",
                     values=[c[0].split(" ",1)[1] for c in CONSTELLATIONS]).pack(side=tk.LEFT, padx=6)
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=14, width=55, font=("Arial",10))
        out.pack(pady=8)

        def gen():
            cname = cv.get()
            random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(cname)%1000)
            score = random.randint(60,100)
            out.delete("1.0",tk.END)
            out.insert(tk.END, f"{cname} 今日运势\n{'='*35}\n\n📊 综合指数: {score}/100\n\n")
            for dim in ["整体","爱情","事业","财运","健康"]:
                random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(cname+dim)%1000)
                s = random.randint(1,len(FORTUNE_TEMPLATES[dim])-1)
                out.insert(tk.END, f"{dim}: {FORTUNE_TEMPLATES[dim][s]}\n")
            out.insert(tk.END, f"\n🎨 幸运色: {next(c[4] for c in CONSTELLATIONS if cname in c[0])}")
            today = datetime.date.today().isoformat()
            self.history[today] = {"星座":cname,"分数":score}
            self._save(HISTORY_FILE, self.history)

        tk.Button(f, text="✨ 生成", command=gen, bg=self.C["ac"], fg="#000").pack(side=tk.LEFT, padx=6)
        gen()

    # ========== 配对 ==========
    def _show_match(self):
        self._clear(); b=self.body
        tk.Label(b, text="💕 配对测试", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=12)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=8)
        tk.Label(f, text="你:", bg=self.C["bg"], fg=self.C["fg"]).grid(row=0,column=0,padx=4)
        v1 = tk.StringVar(value="狮子座")
        ttk.Combobox(f, textvariable=v1, width=10, state="readonly",
                     values=[c[0].split(" ",1)[1] for c in CONSTELLATIONS]).grid(row=0,column=1,padx=4)
        tk.Label(f, text="❤️", bg=self.C["bg"], fg="#FF6B6B", font=("Arial",14)).grid(row=0,column=2,padx=6)
        tk.Label(f, text="TA:", bg=self.C["bg"], fg=self.C["fg"]).grid(row=0,column=3,padx=4)
        v2 = tk.StringVar(value="白羊座")
        ttk.Combobox(f, textvariable=v2, width=10, state="readonly",
                     values=[c[0].split(" ",1)[1] for c in CONSTELLATIONS]).grid(row=0,column=4,padx=4)
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=10, width=55, font=("Arial",10))
        out.pack(pady=10)
        def match():
            a,b_ = v1.get(), v2.get()
            out.delete("1.0",tk.END)
            if a==b_: score=random.randint(65,85)
            elif b_ in COMPATIBILITY.get(a,[]): score=random.randint(88,99)
            elif a in COMPATIBILITY.get(b_,[]): score=random.randint(80,93)
            else: score=random.randint(45,75)
            out.insert(tk.END, f"💫 {a} × {b_}\n{'='*30}\n\n⭐ 配对指数: {score}/100\n\n")
            if score>=88: out.insert(tk.END,"🔥 天作之合！")
            elif score>=75: out.insert(tk.END,"✨ 很有缘分！")
            else: out.insert(tk.END,"🌊 需要磨合。")
        tk.Button(f, text="💘 配对", command=match, bg="#FF6B6B", fg="white").grid(row=0,column=5,padx=10)
        match()

    # ========== 日期查星座 ==========
    def _date_query(self):
        self._clear(); b=self.body
        tk.Label(b, text="📅 日期查星座", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=12)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=8)
        tk.Label(f, text="月:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        mv = tk.IntVar(value=1)
        ttk.Combobox(f, textvariable=mv, values=list(range(1,13)), width=4).pack(side=tk.LEFT, padx=4)
        tk.Label(f, text="日:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        dv = tk.IntVar(value=1)
        ttk.Combobox(f, textvariable=dv, values=list(range(1,32)), width=4).pack(side=tk.LEFT, padx=4)
        res = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=10, width=50, font=("Arial",10))
        res.pack(pady=10)
        def go():
            r = self._md_to_constellation(mv.get(), dv.get())
            res.delete("1.0",tk.END)
            if r: res.insert("1.0", f"{r[5]} {r[0]}\n{'='*30}\n📅 {r[1]}\n🔥 {r[2]}\n🪐 {r[3]}\n🎨 {r[4]}\n\n{r[6]}")
            else: res.insert("1.0","未找到")
        tk.Button(f, text="🔍", command=go, bg=self.C["ac"], fg="#000").pack(side=tk.LEFT, padx=6)
        go()

    # ========== 生肖 ==========
    def _show_sx(self):
        self._clear(); b=self.body
        tk.Label(b, text="🐾 生肖查询", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=12)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=8)
        tk.Label(f, text="年份:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        yv = tk.IntVar(value=datetime.date.today().year)
        tk.Spinbox(f, from_=1900, to=2100, textvariable=yv, width=6).pack(side=tk.LEFT, padx=6)
        res = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=8, width=50, font=("Arial",10))
        res.pack(pady=10)
        def query():
            idx = (yv.get()-4)%12
            res.delete("1.0",tk.END)
            res.insert("1.0", f"{SX_EMOJI[idx]} {SHENGXIAO[idx]}年\n年龄:{datetime.date.today().year-yv.get()}岁\n性格:{SX_TRAITS[idx]}")
        tk.Button(f, text="🐾查", command=query, bg="#4CAF50", fg="white").pack(side=tk.LEFT, padx=6)
        query()

    # ========== 收藏 ==========
    def _show_fav(self):
        self._clear(); b=self.body
        tk.Label(b, text="⭐ 收藏夹", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=12)
        if not self.favorites:
            tk.Label(b, text="(暂无收藏)", bg=self.C["bg"], fg="#888").pack(pady=20); return
        for n in self.favorites:
            f2 = tk.Frame(b, bg=self.C["item"]); f2.pack(fill=tk.X, padx=40, pady=3)
            tk.Label(f2, text=n, bg=self.C["item"], fg=self.C["fg"]).pack(side=tk.LEFT, padx=12, pady=4)

    # ========== 统计 ==========
    def _show_stats(self):
        msg = f"📊 统计面板\n{'='*25}\n星座: 12\n生肖: 12\n收藏: {len(self.favorites)}\n运势记录: {len(self.history)}天\n闹钟: {len(self.alarms)}\n生日互通: {len(self.birthdays)}条"
        messagebox.showinfo("统计", msg)

    # ========== 随机推荐 ==========
    def _random_pick(self):
        c = random.choice(CONSTELLATIONS)
        self._show_constellation_detail(c[0])

    # ========== 21. 运势卡片生成 ==========
    def _fortune_card(self):
        self._clear(); b=self.body
        tk.Label(b, text="🖼 运势卡片生成", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=6)
        tk.Label(f, text="星座:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        cv = tk.StringVar(value="狮子座")
        ttk.Combobox(f, textvariable=cv, width=12, state="readonly",
                     values=[c[0].split(" ",1)[1] for c in CONSTELLATIONS]).pack(side=tk.LEFT, padx=6)
        card_text = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=18, width=50, font=("Consolas",10))
        card_text.pack(pady=10)

        def generate():
            cname = cv.get()
            info = next((c for c in CONSTELLATIONS if cname in c[0]), None)
            if not info: return
            random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(cname)%1000)
            score = random.randint(60,100)
            txt = f"{'='*32}\n  {info[5]} {info[0]}\n  📅 {datetime.date.today()}\n{'='*32}\n  📊 综合指数: {score}/100\n\n"
            for dim in ["整体","爱情","事业","财运","健康"]:
                random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(cname+dim)%1000)
                s = random.randint(1,len(FORTUNE_TEMPLATES[dim])-1)
                txt += f"  {dim}: {FORTUNE_TEMPLATES[dim][s]}\n"
            txt += f"\n  🎨 幸运色: {info[4]}\n  🪐 守护星: {info[3]}\n{'='*32}"
            card_text.delete("1.0",tk.END); card_text.insert("1.0", txt)
            if _PIL:
                img = Image.new("RGB", (400, 500), color="#1a1a2e")
                draw = ImageDraw.Draw(img)
                try: fnt = ImageFont.truetype("msyh.ttc", 16)
                except: fnt = ImageFont.load_default()
                draw.text((20,20), f"{info[5]} {info[0]}", fill="#FFD700", font=fnt)
                draw.text((20,50), str(datetime.date.today()), fill="#aaaaaa", font=fnt)
                draw.text((20,80), f"综合指数: {score}/100", fill="#FF8FA3", font=fnt)
                y=110
                for dim in ["整体","爱情","事业","财运","健康"]:
                    random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(cname+dim)%1000)
                    s = random.randint(1,len(FORTUNE_TEMPLATES[dim])-1)
                    draw.text((20,y), f"{dim}: {FORTUNE_TEMPLATES[dim][s][:22]}", fill="#e0e0ff", font=fnt)
                    y+=30
                draw.text((20, y+20), f"幸运色:{info[4]}  守护星:{info[3]}", fill="#A78BFA", font=fnt)
                draw.text((20,470), "✨ 星座运势 v13.0", fill="#666666", font=fnt)
                card_path = os.path.join(DATA_DIR, f"fortune_{cname}.png")
                img.save(card_path)
                self._last_card_path = card_path

        tk.Button(f, text="✨ 生成", command=generate, bg=self.C["ac"], fg="#000").pack(side=tk.LEFT, padx=6)
        def save_img():
            if hasattr(self,'_last_card_path') and os.path.exists(self._last_card_path):
                dst = filedialog.asksaveasfilename(defaultextension=".png", initialfile=os.path.basename(self._last_card_path))
                if dst: shutil.copy(self._last_card_path, dst); messagebox.showinfo("✓","已保存")
            else: messagebox.showinfo("提示","请先生成（需PIL）")
        def copy_txt():
            self.m.clipboard_clear(); self.m.clipboard_append(card_text.get("1.0",tk.END))
            messagebox.showinfo("✓","已复制")
        bf = tk.Frame(b, bg=self.C["bg"]); bf.pack(pady=6)
        tk.Button(bf, text="💾 保存图片", command=save_img, bg="#4CAF50", fg="white").pack(side=tk.LEFT, padx=6)
        tk.Button(bf, text="📋 复制文本", command=copy_txt, bg="#3a3a5a", fg="white").pack(side=tk.LEFT, padx=6)
        generate()

    # ========== 22. 生日互通 ==========
    def _birthday_sync(self):
        self._clear(); b=self.body
        tk.Label(b, text="🔗 与生日提醒器数据互通", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        if not self.birthdays:
            tk.Label(b, text="❌ 未找到 birthdays.json\n请先运行生日提醒器", bg=self.C["bg"], fg=self.C["bad"]).pack(pady=20)
            return
        tk.Label(b, text=f"✅ 找到 {len(self.birthdays)} 条生日数据", bg=self.C["bg"], fg=self.C["good"]).pack(pady=6)
        list_f = tk.Frame(b, bg=self.C["item"]); list_f.pack(fill=tk.BOTH, expand=True, padx=30, pady=8)
        for rec in self.birthdays:
            name = rec.get("name","?")
            md = rec.get("date","??")
            year = rec.get("year")
            m,d = map(int, md.split("-"))
            c_info = self._md_to_constellation(m,d)
            cname = c_info[0].split(" ",1)[1] if c_info else "?"
            cemoji = c_info[5] if c_info else "⭐"
            sx = f"{SX_EMOJI[(year-4)%12]}{SHENGXIAO[(year-4)%12]}" if year else ""
            row = tk.Frame(list_f, bg=self.C["item"]); row.pack(fill=tk.X, padx=8, pady=2)
            tk.Label(row, text=name, bg=self.C["item"], fg=self.C["fg"], width=12, anchor=tk.W).pack(side=tk.LEFT)
            tk.Label(row, text=md, bg=self.C["item"], fg="#aaa", width=8).pack(side=tk.LEFT)
            tk.Label(row, text=f"{cemoji}{cname}", bg=self.C["item"], fg=self.C["ac"], width=14).pack(side=tk.LEFT)
            tk.Label(row, text=sx, bg=self.C["item"], fg=self.C["good"], width=8).pack(side=tk.LEFT)
        def batch():
            out = tk.Toplevel(self); out.title("全员运势"); out.geometry("380x300")
            out.config(bg=self.C["bg"])
            txt = tk.Text(out, bg=self.C["item"], fg=self.C["fg"], wrap=tk.WORD)
            txt.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
            for rec in self.birthdays:
                name = rec.get("name","?")
                m,d = map(int, rec.get("date","1-1").split("-"))
                c_info = self._md_to_constellation(m,d)
                if not c_info: continue
                cname = c_info[0].split(" ",1)[1]
                random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(name)%1000)
                score = random.randint(60,100)
                txt.insert(tk.END, f"{c_info[5]} {name}({cname}): {score}/100\n")
        tk.Button(b, text="🔮 全员运势", command=batch, bg=self.C["purple"], fg="white").pack(pady=6)

    # ========== 23. 开机运势 ==========
    def _startup_fortune(self):
        today = datetime.date.today().isoformat()
        if today in self.history: return
        c = random.choice(CONSTELLATIONS)
        cname = c[0].split(" ",1)[1]
        random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(c[0])%1000)
        score = random.randint(60,100)
        messagebox.showinfo("今日运势提醒", f"🔮 {c[5]} {cname}\n综合指数: {score}/100\n\n点击「🔮运势」查看详情！")
        self.history[today] = {"星座":c[0],"分数":score}
        self._save(HISTORY_FILE, self.history)

    # ========== 24. 朋友圈文案 ==========
    def _moment_text(self):
        self._clear(); b=self.body
        tk.Label(b, text="📝 星座朋友圈文案生成器", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=6)
        tk.Label(f, text="星座:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        cv = tk.StringVar(value="狮子座")
        ttk.Combobox(f, textvariable=cv, width=10, state="readonly",
                     values=[c[0].split(" ",1)[1] for c in CONSTELLATIONS]).pack(side=tk.LEFT, padx=4)
        tk.Label(f, text="风格:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        sv = tk.StringVar(value="毒舌")
        ttk.Combobox(f, textvariable=sv, width=8, state="readonly",
                     values=["毒舌","文艺","沙雕"]).pack(side=tk.LEFT, padx=4)
        scv = tk.IntVar(value=85)
        tk.Spinbox(f, from_=1, to=100, textvariable=scv, width=4).pack(side=tk.LEFT, padx=4)
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=6, width=55, font=("Arial",10))
        out.pack(pady=10)
        def gen():
            cname = cv.get(); style = sv.get(); score = scv.get()
            info = next((c for c in CONSTELLATIONS if cname in c[0]), None)
            color = info[4] if info else "未知"
            templates = MOMENT_TEMPLATES.get(style, MOMENT_TEMPLATES["毒舌"])
            tpl = random.choice(templates)
            msg = tpl.replace("{星座}",cname).replace("{颜色}",color).replace("{score}",str(score)).replace("{score2}",str(max(1,score-10)))
            out.delete("1.0",tk.END); out.insert("1.0", msg)
        tk.Button(f, text="生成", command=gen, bg=self.C["ac"], fg="#000").pack(side=tk.LEFT, padx=6)
        tk.Button(b, text="📋复制", command=lambda: (self.m.clipboard_clear(),self.m.clipboard_append(out.get("1.0",tk.END)),messagebox.showinfo("✓","已复制")),
                  bg="#3a3a5a", fg="white").pack(pady=6)
        gen()

    # ========== 25. 多人对比 ==========
    def _multi_compare(self):
        self._clear(); b=self.body
        tk.Label(b, text="📋 多人运势对比", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        lb = tk.Listbox(b, selectmode=tk.MULTIPLE, bg=self.C["item"], fg=self.C["fg"], height=8)
        for c in CONSTELLATIONS: lb.insert(tk.END, f"{c[5]} {c[0].split(' ',1)[1]}")
        lb.pack(pady=6)
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=14, width=60, font=("Consolas",10))
        out.pack(pady=8)
        def compare():
            sel = lb.curselection()
            if len(sel) < 2: messagebox.showwarning("提示","至少选2个"); return
            if len(sel) > 5: messagebox.showwarning("提示","最多选5个"); return
            out.delete("1.0",tk.END)
            out.insert(tk.END, f"{'星座':<10}{'整体':<8}{'爱情':<8}{'事业':<8}{'财运':<8}{'健康':<8}{'综合':<6}\n{'─'*55}\n")
            results = []
            for i in sel:
                rec = CONSTELLATIONS[i]
                cname = rec[0].split(" ",1)[1]
                random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(cname)%1000)
                scores = {dim: random.randint(50,100) for dim in ["整体","爱情","事业","财运","健康"]}
                total = sum(scores.values())//5
                results.append((cname, total))
                out.insert(tk.END, f"{cname:<10}{scores['整体']:<8}{scores['爱情']:<8}{scores['事业']:<8}{scores['财运']:<8}{scores['健康']:<8}{total:<6}\n")
            results.sort(key=lambda x: x[1], reverse=True)
            out.insert(tk.END, f"\n🏆 今日排名:\n")
            for j,(cn,sc) in enumerate(results,1):
                medal = ["🥇","🥈","🥉"][j-1] if j<=3 else f"{j}."
                out.insert(tk.END, f"  {medal} {cn}: {sc}分\n")
        tk.Button(b, text="📊 开始对比", command=compare, bg=self.C["purple"], fg="white").pack(pady=4)

    # ========== 26. 简易星盘 ==========
    def _simple_chart(self):
        self._clear(); b=self.body
        tk.Label(b, text="🌅 简易星盘（日月升）", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=8)
        tk.Label(f, text="日期(MM-DD):", bg=self.C["bg"], fg=self.C["fg"]).grid(row=0,column=0,padx=4)
        dv = tk.StringVar(value="08-15")
        tk.Entry(f, textvariable=dv, width=8, bg=self.C["item"], fg=self.C["fg"]).grid(row=0,column=1,padx=4)
        tk.Label(f, text="时间(HH:MM):", bg=self.C["bg"], fg=self.C["fg"]).grid(row=0,column=2,padx=4)
        tv = tk.StringVar(value="12:00")
        tk.Entry(f, textvariable=tv, width=6, bg=self.C["item"], fg=self.C["fg"]).grid(row=0,column=3,padx=4)
        tk.Label(f, text="城市:", bg=self.C["bg"], fg=self.C["fg"]).grid(row=1,column=0,padx=4,pady=4)
        cv = tk.StringVar(value="北京")
        ttk.Combobox(f, textvariable=cv, width=10,
                     values=["北京","上海","广州","深圳","成都","杭州","武汉","西安","纽约","伦敦","东京","悉尼"]).grid(row=1,column=1,padx=4)
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=12, width=55, font=("Arial",10))
        out.pack(pady=10)
        def calc():
            try:
                m,d = map(int, dv.get().split("-"))
                hh,mm = map(int, tv.get().split(":"))
            except: messagebox.showerror("错误","格式 MM-DD / HH:MM"); return
            sun = self._md_to_constellation(m,d)
            sun_name = sun[0].split(" ",1)[1] if sun else "?"
            moon_idx = (m*31 + d + hh//6) % 12
            moon = CONSTELLATIONS[moon_idx][0].split(" ",1)[1]
            city_offset = hash(cv.get()) % 12
            asc_idx = (moon_idx + hh//2 + city_offset) % 12
            asc = CONSTELLATIONS[asc_idx][0].split(" ",1)[1]
            out.delete("1.0",tk.END)
            out.insert(tk.END, f"🌅 简易星盘\n{'='*30}\n\n☀️ 太阳: {sun_name} (核心人格)\n🌙 月亮: {moon} (情绪模式)\n⬆️ 上升: {asc} (外在表现)\n\n📍 {cv.get()} ⏰ {tv.get()}")
        tk.Button(f, text="🔮 计算", command=calc, bg=self.C["ac"], fg="#000").grid(row=1,column=3,padx=8)
        calc()

    # ========== 27. 运势趋势 ==========
    def _fortune_trend(self):
        self._clear(); b=self.body
        tk.Label(b, text="📈 运势历史趋势", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        if not self.history:
            tk.Label(b, text="暂无历史数据\n每天查看运势后自动记录", bg=self.C["bg"], fg="#888").pack(pady=30); return
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=16, width=60, font=("Consolas",10))
        out.pack(pady=10)
        out.insert(tk.END, f"{'日期':<14}{'星座':<12}{'分数':<6}\n{'─'*35}\n")
        for day,info in sorted(self.history.items(), reverse=True)[:14]:
            cname = info.get("星座","?")
            score = info.get("分数",0)
            bar = "█" * (score//10)
            out.insert(tk.END, f"{day:<14}{cname:<12}{score:<6}{bar}\n")
        scores = [v.get("分数",0) for v in self.history.values()]
        if scores:
            out.insert(tk.END, f"\n📊 平均{sum(scores)//len(scores)} 最高{max(scores)} 最低{min(scores)} 共{len(scores)}天")

    # ========== 28. 星座换肤 ==========
    def _skin_picker(self):
        self._clear(); b=self.body
        tk.Label(b, text="🎨 星座主题皮肤", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        grid = tk.Frame(b, bg=self.C["bg"]); grid.pack(pady=12)
        for i,c in enumerate(CONSTELLATIONS):
            short = c[0].split(" ",1)[1]
            skin = CONSTELLATION_SKINS.get(short, {})
            tk.Button(grid, text=f"{c[5]} {short}", bg=skin.get("bg","#1a1a2e"), fg=skin.get("ac","#FFD700"),
                      command=lambda s=short: self._apply_skin(s)).grid(row=i//4, column=i%4, padx=6, pady=6)
        self._skin_lbl = tk.Label(b, text="当前: 默认", bg=self.C["bg"], fg="#888"); self._skin_lbl.pack(pady=6)

    def _apply_skin(self, cname):
        skin = CONSTELLATION_SKINS.get(cname, {})
        if skin:
            self.C.update(skin)
            self._skin_lbl.config(text=f"已选 {cname}（重启生效）")
            messagebox.showinfo("换肤", f"已选择 {cname} 主题")

    # ========== 29. 星座闹钟 ==========
    def _alarm_ui(self):
        self._clear(); b=self.body
        tk.Label(b, text="⏰ 星座闹钟", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=6)
        tk.Label(f, text="时间(HH:MM):", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        self._atime = tk.StringVar(value="08:00")
        tk.Entry(f, textvariable=self._atime, width=7, bg=self.C["item"], fg=self.C["fg"]).pack(side=tk.LEFT, padx=4)
        tk.Label(f, text="提醒:", bg=self.C["bg"], fg=self.C["fg"]).pack(side=tk.LEFT)
        self._amsg = tk.StringVar(value="该看今日星座运势啦 ✨")
        tk.Entry(f, textvariable=self._amsg, width=22, bg=self.C["item"], fg=self.C["fg"]).pack(side=tk.LEFT, padx=4)
        tk.Button(f, text="➕添加", bg="#4CAF50", fg="white", command=self._add_alarm).pack(side=tk.LEFT, padx=4)
        self._alist = tk.Listbox(b, bg=self.C["item"], fg=self.C["fg"], height=6, width=50)
        self._alist.pack(pady=8)
        for a in self.alarms: self._alist.insert(tk.END, f"{a['time']} - {a['msg']}")
        tk.Button(b, text="🗑删除选中", bg="#FF6B6B", fg="white", command=self._del_alarm).pack(pady=4)

    def _add_alarm(self):
        t = self._atime.get().strip()
        if len(t)!=5 or t[2]!=":": messagebox.showerror("错误","格式 HH:MM"); return
        self.alarms.append({"time":t,"msg":self._amsg.get()})
        self._save(ALARM_FILE, self.alarms)
        self._alist.insert(tk.END, f"{t} - {self._amsg.get()}")
        messagebox.showinfo("✓", f"闹钟 {t} 已添加")

    def _del_alarm(self):
        sel = self._alist.curselection()
        if not sel: return
        self.alarms.pop(sel[0]); self._save(ALARM_FILE, self.alarms)
        self._alist.delete(sel[0])

    def _start_alarm_loop(self):
        def loop():
            while True:
                now = datetime.datetime.now().strftime("%H:%M")
                for a in self.alarms:
                    if a["time"] == now and not a.get("fired"):
                        a["fired"] = True
                        self.m.after(0, lambda m=a["msg"]: messagebox.showinfo("⏰ 闹钟", m))
                if datetime.datetime.now().second == 0:
                    for a in self.alarms: a.pop("fired", None)
                time.sleep(1)
        threading.Thread(target=loop, daemon=True).start()

    # ========== 30. 微信推送文案 ==========
    def _wechat_push(self, cname):
        random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(cname)%1000)
        score = random.randint(62,98)
        return f"【今日星座运势】\n{cname}：{score}/100\n宜：保持好奇，忌：内耗。\n✨ 来自星座小工具 v13"

    # ========== 31. 性格测试 ==========
    def _quiz_ui(self):
        self._clear(); b=self.body
        tk.Label(b, text="🧠 星座性格测试（8题）", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        self._qidx = 0; self._qscores = {"火":0,"土":0,"风":0,"水":0}
        self._qlabel = tk.Label(b, text="", bg=self.C["bg"], fg=self.C["fg"], wraplength=420, font=("Arial",11))
        self._qlabel.pack(pady=12)
        self._qvar = tk.StringVar()
        self._qbtns = []
        for i in range(4):
            rb = tk.Radiobutton(b, text="", variable=self._qvar, value="", bg=self.C["bg"],
                                fg=self.C["fg"], indicatoron=0, width=32, command=self._quiz_next)
            rb.pack(pady=2); self._qbtns.append(rb)
        self._quiz_load()

    def _quiz_load(self):
        q = QUIZ[self._qidx]
        self._qlabel.config(text=f"Q{self._qidx+1}. {q[0]}")
        self._qvar.set(None)
        for i,opt in enumerate(q[1]):
            self._qbtns[i].config(text=opt, value=opt, state=tk.NORMAL)
        for i in range(len(q[1]),4):
            self._qbtns[i].config(text="", state=tk.DISABLED)

    def _quiz_next(self):
        ans = self._qvar.get()
        if not ans: return
        elems = ["火","土","风","水"]
        picked = QUIZ[self._qidx][1].index(ans)
        self._qscores[elems[picked%4]] += 2
        self._qidx += 1
        if self._qidx >= len(QUIZ): self._quiz_result()
        else: self._quiz_load()

    def _quiz_result(self):
        self._clear(); b=self.body
        dom = max(self._qscores, key=self._qscores.get)
        c = {"火":"白羊/狮子/射手","土":"金牛/处女/摩羯","风":"双子/天秤/水瓶","水":"巨蟹/天蝎/双鱼"}[dom]
        tk.Label(b, text="🧠 测试结果", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=12)
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=10, width=55, font=("Arial",10))
        out.pack(pady=8)
        out.insert(tk.END, f"主导元素：{dom}\n适配星座：{c}\n\n细分：\n")
        for k,v in self._qscores.items(): out.insert(tk.END, f"  {k}: {v}\n")
        out.insert(tk.END, "\n" + random.choice([
            "外热内冷，表面洒脱其实很重感情。","逻辑在线，但情绪来了谁都拦不住。",
            "自由至上，讨厌被贴标签。","温柔有边界，熟人面前才疯。"]))
        tk.Button(b, text="📋复制", bg="#3a3a5a", fg="white",
                  command=lambda: (self.m.clipboard_clear(), self.m.clipboard_append(out.get("1.0",tk.END)))).pack(pady=4)

    # ========== 32. 八字 ==========
    def _bazi_ui(self):
        self._clear(); b=self.body
        tk.Label(b, text="☯️ 生辰八字生成", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=6)
        self._bv = {}
        for i,(lab,defv) in enumerate([("年",1999),("月",8),("日",15),("时",14)]):
            tk.Label(f, text=lab, bg=self.C["bg"], fg=self.C["fg"]).grid(row=0,column=i*2,padx=2)
            v = tk.IntVar(value=defv)
            if lab=="年": tk.Spinbox(f, from_=1900, to=2100, textvariable=v, width=5).grid(row=0,column=i*2+1)
            elif lab=="时": tk.Spinbox(f, from_=0, to=23, textvariable=v, width=4).grid(row=0,column=i*2+1)
            else: tk.Spinbox(f, from_=1, to=12 if lab=="月" else 31, textvariable=v, width=4).grid(row=0,column=i*2+1)
            self._bv[lab]=v
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=14, width=60, font=("Consolas",10))
        out.pack(pady=10)
        def calc():
            y=self._bv["年"].get(); mo=self._bv["月"].get(); d=self._bv["日"].get(); h=self._bv["时"].get()
            yp = GAN[(y-4)%10]+ZHI[(y-4)%12]
            dp = GAN[(datetime.date(y,mo,d)-datetime.date(1900,1,1)).days%10] + ZHI[(datetime.date(y,mo,d)-datetime.date(1900,1,1)).days%12]
            mp = GAN[((y-4)%10 * 2+2+mo-1)%10] + ZHI[(mo+1)%12]
            hp = GAN[((GAN.index(dp[0])%10 * 2)%10+h//2)%10] + ZHI[(h+1)//2%12]
            out.delete("1.0",tk.END)
            out.insert(tk.END, f"公历 {y}-{mo:02d}-{d:02d} {h:02d}:00\n{'='*30}\n四柱：\n 年 {yp}\n 月 {mp}\n 日 {dp}（日主）\n 时 {hp}\n\n")
            wx = {"金":0,"木":0,"水":0,"火":0,"土":0}
            for p in [yp,mp,dp,hp]:
                wx[WUXING.get(p[0],"?")] = wx.get(WUXING.get(p[0],"?"),0)+1
                wx[ZHI_WX.get(p[1],"?")] = wx.get(ZHI_WX.get(p[1],"?"),0)+0.5
            out.insert(tk.END, "五行：")
            for k,v in wx.items(): out.insert(tk.END, f" {k}{v}")
            dm = dp[0]
            strong = wx[WUXING[dm]] >= 3
            out.insert(tk.END, f"\n\n日主：{dm}（{WUXING[dm]}）{'偏强' if strong else '偏弱'}")
        tk.Button(f, text="☯️排盘", bg=self.C["ac"], fg="#000", command=calc).grid(row=1,column=0,columnspan=8,pady=6)
        calc()

    # ========== 33. 双人合盘 ==========
    def _synastry(self):
        self._clear(); b=self.body
        tk.Label(b, text="💞 双人合盘（详细版）", bg=self.C["bg"], fg=self.C["ac"], font=("Arial",16,"bold")).pack(pady=10)
        f = tk.Frame(b, bg=self.C["bg"]); f.pack(pady=8)
        tk.Label(f, text="A:", bg=self.C["bg"], fg=self.C["fg"]).grid(row=0,column=0)
        av = tk.StringVar(value="狮子座")
        ttk.Combobox(f, textvariable=av, values=[c[0].split(" ",1)[1] for c in CONSTELLATIONS], width=10).grid(row=0,column=1)
        tk.Label(f, text="×", bg=self.C["bg"], fg="#FF6B6B", font=("Arial",14)).grid(row=0,column=2,padx=6)
        tk.Label(f, text="B:", bg=self.C["bg"], fg=self.C["fg"]).grid(row=0,column=3)
        bv = tk.StringVar(value="水瓶座")
        ttk.Combobox(f, textvariable=bv, values=[c[0].split(" ",1)[1] for c in CONSTELLATIONS], width=10).grid(row=0,column=4)
        out = tk.Text(b, bg=self.C["item"], fg=self.C["fg"], height=16, width=60, font=("Consolas",10))
        out.pack(pady=8)
        def calc():
            A,B = av.get(), bv.get()
            random.seed(int(datetime.date.today().strftime("%Y%m%d")) + hash(A+B)%1000)
            score = random.randint(55,96)
            out.delete("1.0",tk.END)
            out.insert(tk.END, f"A:{A} × B:{B}\n{'='*30}\n综合契合度: {score}/100\n\n")
            for dim in ["沟通","亲密","冲突处理","长期稳定"]:
                out.insert(tk.END, f"  {dim}: {random.randint(50,100)}\n")
            out.insert(tk.END, "\n建议：\n- 别在情绪头上做决定\n- 每周留一段只聊感受的时间\n- 差异不是错，是拼图")
        tk.Button(f, text="💘合盘", bg="#FF6B6B", fg="white", command=calc).grid(row=1,column=0,columnspan=5,pady=6)
        calc()

# ==================== 启动 ====================
def main():
    root = tk.Tk()
    root.title("♈ 星座/生肖/八字 v13.0 — 33功能")
    root.geometry("860x680")
    root.config(bg="#0f0f1a")
    s = ttk.Style(); s.theme_use("clam")
    s.configure("TCombobox", fieldbackground="#16213e", background="#2a2a4a", foreground="white")
    AstroApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()