import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import time
import threading
import sys
import os

# ====================== 反检测核心模拟模块 ======================
class AntiDetectionSystem:
    def __init__(self, log_callback):
        self.log = log_callback
        self.is_active = False
        self.detection_status = "未激活"

    def elevate_privileges(self):
        self.log("[反检测] 正在提升系统权限...")
        time.sleep(0.5)
        self.log("[反检测] 权限提升成功 (模拟)")
        return True

    def load_kernel_driver(self):
        self.log("[反检测] 正在加载Ring0内核驱动...")
        time.sleep(0.8)
        self.log("[反检测] 驱动加载成功 (模拟)")
        return True

    def hide_process(self):
        self.log("[反检测] 正在执行DKOM进程隐藏...")
        time.sleep(0.6)
        self.log("[反检测] 进程已从任务管理器隐藏 (模拟)")
        return True

    def hook_system_calls(self):
        self.log("[反检测] 正在挂钩系统调用 NtQuerySystemInformation...")
        time.sleep(0.7)
        self.log("[反检测] 系统调用挂钩成功 (模拟)")
        return True

    def bypass_gameguard(self):
        self.log("[反检测] 正在绕过GameGuard/NGS防护...")
        time.sleep(1)
        self.log("[反检测] 防护绕过成功 (模拟)")
        return True

    def clear_traces(self):
        self.log("[反检测] 正在清除内存特征与日志痕迹...")
        time.sleep(0.5)
        self.log("[反检测] 痕迹清除完成 (模拟)")
        return True

    def full_anti_detection(self):
        if self.is_active:
            self.log("[反检测] 反检测系统已处于激活状态")
            return
        self.is_active = True
        self.detection_status = "已激活"
        self.log("="*50)
        self.log("[反检测] 启动完整反检测防护流程")
        self.elevate_privileges()
        self.load_kernel_driver()
        self.hide_process()
        self.hook_system_calls()
        self.bypass_gameguard()
        self.clear_traces()
        self.log("[反检测] 所有防护模块已全部激活")
        self.log("="*50)

    def brute_force_database(self, progress_callback):
        self.log("[爆破] 启动数据库暴力破解...")
        for i in range(1, 101):
            time.sleep(0.02)
            progress_callback(i)
            if i % 25 == 0:
                self.log(f"[爆破] 进度: {i}%")
        self.log("[爆破] 暴力破解完成 (模拟)")
        return True

    def tamper_logs(self):
        self.log("[日志篡改] 正在修改服务器登录日志...")
        time.sleep(0.5)
        self.log("[日志篡改] 日志篡改完成: LOG_ENTRY: USER_LOGIN_SUCCESS (模拟)")
        return True

    def irreversible_delete(self):
        confirm = messagebox.askyesno("⚠️ 高危操作确认",
            "此操作将不可逆删除服务器数据库!\n\n是否确认执行?")
        if not confirm:
            self.log("[删除] 操作已取消")
            return
        self.log("[删除] 正在执行不可逆数据库删除...")
        time.sleep(1)
        self.log("[删除] 数据库删除完成 (模拟)")
        messagebox.showwarning("⚠️ 模拟完成", "数据库删除操作已执行 (仅演示)")

# ====================== 主程序GUI ======================
class MapleStoryTool:
    def __init__(self, root):
        self.root = root
        self.root.title("MAPLESTORY 079 | 复古辅助工具 v6.1")
        self.root.geometry("1000x700")
        self.root.resizable(False, False)
        self.root.configure(bg='#1a1a2e')

        # 初始化反检测系统
        self.anti_detect = AntiDetectionSystem(self.log)

        # 样式配置
        self.setup_styles()
        # 构建界面
        self.build_ui()
        # 初始化日志
        self.log("系统初始化完成 → 冒险岛079辅助工具 v6.1")
        self.log("反检测模块已加载，等待激活")

    def setup_styles(self):
        style = ttk.Style()
        style.theme_use('clam')
        
        # 主界面样式
        style.configure('Dark.TLabelframe', background='#16213e', foreground='#00ccff', 
                        bordercolor='#0f3460', lightcolor='#0f3460', darkcolor='#0f3460')
        style.configure('Dark.TLabelframe.Label', background='#16213e', foreground='#00ccff', 
                        font=('微软雅黑', 10, 'bold'))
        style.configure('Dark.TButton', background='#0f3460', foreground='white', 
                        font=('微软雅黑', 9), borderwidth=2)
        style.map('Dark.TButton', background=[('active', '#1a4d8c')])
        style.configure('Dark.TCheckbutton', background='#16213e', foreground='white', 
                        font=('微软雅黑', 9))
        style.configure('Dark.TScale', background='#16213e', troughcolor='#0f3460')
        
        # 危险按钮样式
        style.configure('Danger.TButton', background='#8b0000', foreground='white', 
                        font=('微软雅黑', 9, 'bold'), borderwidth=2)
        style.map('Danger.TButton', background=[('active', '#b22222')])
        
        # 成功按钮样式
        style.configure('Success.TButton', background='#228b22', foreground='white', 
                        font=('微软雅黑', 9, 'bold'), borderwidth=2)
        style.map('Success.TButton', background=[('active', '#32cd32')])

    def build_ui(self):
        # 顶部标题栏
        title_frame = tk.Frame(self.root, bg='#8b4513', height=40)
        title_frame.pack(fill='x', side='top')
        tk.Label(title_frame, text="v079", bg='#8b4513', fg='white', 
                 font=('微软雅黑', 12, 'bold')).pack(side='left', padx=10)
        tk.Label(title_frame, text="MAPLESTORY 079 | 复古辅助工具", bg='#8b4513', fg='white', 
                 font=('微软雅黑', 14, 'bold')).pack(side='left', padx=20)
        close_btn = tk.Button(title_frame, text="✕", bg='#8b0000', fg='white', 
                              font=('微软雅黑', 12, 'bold'), width=3, command=self.root.quit)
        close_btn.pack(side='right', padx=5)

        # 主内容区
        main_frame = tk.Frame(self.root, bg='#1a1a2e')
        main_frame.pack(fill='both', expand=True, padx=10, pady=10)

        # 第一行：物品复制 + 强化保护 + GM权限
        row1 = tk.Frame(main_frame, bg='#1a1a2e')
        row1.pack(fill='x', pady=5)

        # 1. 物品复制控制区
        item_frame = ttk.LabelFrame(row1, text="📦 物品复制控制区", style='Dark.TLabelframe', width=300, height=350)
        item_frame.grid(row=0, column=0, padx=5, pady=5)
        item_frame.grid_propagate(False)

        items = [
            ("💰 金币", "gold"),
            ("⚔️ 装备", "equip"),
            ("🧪 药水", "potion"),
            ("📜 卷轴", "scroll"),
            ("🍲 炖物材料", "material"),
            ("💎 现金道具", "cash")
        ]
        self.item_entries = {}
        for i, (label, key) in enumerate(items):
            lbl = tk.Label(item_frame, text=label, bg='#16213e', fg='white', font=('微软雅黑', 10))
            lbl.grid(row=i, column=0, padx=10, pady=8, sticky='w')
            lbl2 = tk.Label(item_frame, text="数量:", bg='#16213e', fg='white', font=('微软雅黑', 10))
            lbl2.grid(row=i, column=1, padx=5, pady=8, sticky='w')
            entry = tk.Entry(item_frame, width=10, bg='#0f3460', fg='#00ccff', insertbackground='#00ccff', 
                             bd=0, font=('微软雅黑', 10))
            entry.grid(row=i, column=2, padx=5, pady=8)
            entry.insert(0, "1")
            btn = ttk.Button(item_frame, text="复制", style='Dark.TButton', width=6,
                             command=lambda k=key, e=entry: self.duplicate_item(k, e))
            btn.grid(row=i, column=3, padx=5, pady=8)
            self.item_entries[key] = entry

        # 2. 装备强化保护
        protect_frame = ttk.LabelFrame(row1, text="⚙️ 装备强化保护", style='Dark.TLabelframe', width=300, height=350)
        protect_frame.grid(row=0, column=1, padx=5, pady=5)
        protect_frame.grid_propagate(False)

        # 卷轴次数保护
        self.scroll_protect = tk.BooleanVar(value=True)
        scroll_frame = tk.Frame(protect_frame, bg='#16213e')
        scroll_frame.pack(pady=20, padx=20, fill='x')
        tk.Label(scroll_frame, text="卷轴次数保护", bg='#16213e', fg='white', font=('微软雅黑', 11)).pack(anchor='w')
        scroll_switch = ttk.Checkbutton(scroll_frame, variable=self.scroll_protect, style='Switch.TCheckbutton')
        scroll_switch.pack(anchor='w', pady=5)
        self.scroll_status = tk.Label(scroll_frame, text="ON", bg='#16213e', fg='#00ff00', font=('微软雅黑', 10, 'bold'))
        self.scroll_status.pack(anchor='w')

        # 失败不损坏
        self.break_protect = tk.BooleanVar(value=True)
        break_frame = tk.Frame(protect_frame, bg='#16213e')
        break_frame.pack(pady=20, padx=20, fill='x')
        tk.Label(break_frame, text="失败不损坏", bg='#16213e', fg='white', font=('微软雅黑', 11)).pack(anchor='w')
        break_switch = ttk.Checkbutton(break_frame, variable=self.break_protect, style='Switch.TCheckbutton')
        break_switch.pack(anchor='w', pady=5)
        self.break_status = tk.Label(break_frame, text="ON", bg='#16213e', fg='#00ff00', font=('微软雅黑', 10, 'bold'))
        self.break_status.pack(anchor='w')

        ttk.Button(protect_frame, text="应用保护设置", style='Success.TButton', 
                   command=self.apply_protection).pack(pady=10)

        # 3. GM权限激活
        gm_frame = ttk.LabelFrame(row1, text="👑 GM权限激活", style='Dark.TLabelframe', width=300, height=350)
        gm_frame.grid(row=0, column=2, padx=5, pady=5)
        gm_frame.grid_propagate(False)

        gm_btn = tk.Button(gm_frame, text="👑\n激活GM权限", bg='#ff8c00', fg='white', 
                           font=('微软雅黑', 16, 'bold'), width=12, height=4, command=self.activate_gm)
        gm_btn.pack(pady=30)

        # 经验倍率
        exp_frame = ttk.LabelFrame(gm_frame, text="📈 经验倍率", style='Dark.TLabelframe')
        exp_frame.pack(fill='x', padx=10, pady=10)
        self.exp_slider = ttk.Scale(exp_frame, from_=1, to=100, orient='horizontal', 
                                    command=self.update_exp_label, style='Dark.TScale')
        self.exp_slider.set(10)
        self.exp_slider.pack(pady=10, padx=20, fill='x')
        self.exp_label = tk.Label(exp_frame, text="×10", bg='#16213e', fg='#00ccff', font=('微软雅黑', 12, 'bold'))
        self.exp_label.pack()
        ttk.Button(exp_frame, text="应用倍率", style='Dark.TButton', command=self.apply_exp_rate).pack(pady=5)

        # 第二行：反检测/高级功能 + 日志
        row2 = tk.Frame(main_frame, bg='#1a1a2e')
        row2.pack(fill='both', expand=True, pady=5)

        # 高级功能拓展
        adv_frame = ttk.LabelFrame(row2, text="🚀 高级功能拓展", style='Dark.TLabelframe', width=600, height=250)
        adv_frame.grid(row=0, column=0, padx=5, pady=5, sticky='nsew')
        adv_frame.grid_propagate(False)

        # 反后台检测
        detect_frame = tk.Frame(adv_frame, bg='#0f192e', bd=2, relief='groove')
        detect_frame.grid(row=0, column=0, padx=10, pady=10, sticky='nsew')
        tk.Label(detect_frame, text="🛡️ 反后台检测", bg='#0f192e', fg='#00ccff', 
                 font=('微软雅黑', 11, 'bold')).pack(anchor='w', padx=10, pady=5)
        self.detect_switch = ttk.Checkbutton(detect_frame, style='Switch.TCheckbutton', 
                                              command=self.toggle_detection)
        self.detect_switch.pack(anchor='w', padx=10, pady=5)
        self.detect_status = tk.Label(detect_frame, text="SECURITY SHIELD: INACTIVE", 
                                       bg='#0f192e', fg='#ff4444', font=('Consolas', 10, 'bold'))
        self.detect_status.pack(anchor='w', padx=10, pady=5)

        # 逆服务端删库
        delete_frame = tk.Frame(adv_frame, bg='#1a0a0a', bd=2, relief='groove')
        delete_frame.grid(row=0, column=1, padx=10, pady=10, sticky='nsew')
        tk.Label(delete_frame, text="☠️ 逆服务端删库", bg='#1a0a0a', fg='#ff4444', 
                 font=('微软雅黑', 11, 'bold')).pack(anchor='w', padx=10, pady=5)
        delete_btn = tk.Button(delete_frame, text="⚠️ 执行删除", bg='#8b0000', fg='white', 
                               font=('微软雅黑', 10, 'bold'), command=self.anti_detect.irreversible_delete)
        delete_btn.pack(pady=10, padx=10)
        tk.Label(delete_frame, text="⚠️ DANGER: IRREVERSIBLE ACTION!", bg='#1a0a0a', fg='#ff4444',
                 font=('Consolas', 9, 'bold')).pack(anchor='w', padx=10, pady=5)

        # 服务器日志篡改
        log_frame = tk.Frame(adv_frame, bg='#0a1a0a', bd=2, relief='groove')
        log_frame.grid(row=1, column=0, padx=10, pady=10, sticky='nsew')
        tk.Label(log_frame, text="📝 服务器日志篡改", bg='#0a1a0a', fg='#00ff00', 
                 font=('微软雅黑', 11, 'bold')).pack(anchor='w', padx=10, pady=5)
        self.log_entry = tk.Text(log_frame, height=2, width=30, bg='#000000', fg='#00ff00', 
                                 font=('Consolas', 10))
        self.log_entry.insert('end', "LOG_ENTRY: USER_LOGIN_SUCCESS")
        self.log_entry.pack(padx=10, pady=5)
        ttk.Button(log_frame, text="篡改日志", style='Success.TButton', 
                   command=self.anti_detect.tamper_logs).pack(pady=5)

        # 爆破
        brute_frame = tk.Frame(adv_frame, bg='#1a0a0a', bd=2, relief='groove')
        brute_frame.grid(row=1, column=1, padx=10, pady=10, sticky='nsew')
        tk.Label(brute_frame, text="💥 爆破", bg='#1a0a0a', fg='#ff4444', 
                 font=('微软雅黑', 11, 'bold')).pack(anchor='w', padx=10, pady=5)
        self.brute_progress = ttk.Progressbar(brute_frame, orient='horizontal', length=200, mode='determinate')
        self.brute_progress.pack(padx=10, pady=5)
        self.brute_label = tk.Label(brute_frame, text="ATTACK TYPE: BRUTE FORCE\nTARGET: DATABASE", 
                                    bg='#1a0a0a', fg='white', font=('Consolas', 9))
        self.brute_label.pack(anchor='w', padx=10)
        brute_btn = ttk.Button(brute_frame, text="开始爆破", style='Danger.TButton', 
                               command=self.start_brute)
        brute_btn.pack(pady=5)

        # 日志区
        log_frame = ttk.LabelFrame(row2, text="📋 操作日志", style='Dark.TLabelframe')
        log_frame.grid(row=0, column=1, padx=5, pady=5, sticky='nsew')
        self.log_text = scrolledtext.ScrolledText(log_frame, bg='#0f3460', fg='#00ffaa', 
                                                  font=('Consolas', 9), wrap='word', height=12)
        self.log_text.pack(padx=5, pady=5, fill='both', expand=True)

        # 配置网格权重
        adv_frame.grid_columnconfigure(0, weight=1)
        adv_frame.grid_columnconfigure(1, weight=1)
        row2.grid_columnconfigure(0, weight=2)
        row2.grid_columnconfigure(1, weight=1)

        # 底部状态栏
        status_frame = tk.Frame(self.root, bg='#0f3460', height=30)
        status_frame.pack(fill='x', side='bottom')
        tk.Label(status_frame, text="⚠️ 本工具仅为学习演示使用，无实际修改功能", 
                 bg='#0f3460', fg='#ffcc00', font=('微软雅黑', 9)).pack(pady=5)

    # ====================== 功能函数 ======================
    def log(self, msg):
        t = time.strftime("%H:%M:%S")
        self.log_text.insert('end', f"[{t}] {msg}\n")
        self.log_text.see('end')

    def duplicate_item(self, key, entry):
        try:
            n = int(entry.get())
            if n < 1: raise ValueError
            names = {'gold':'金币','equip':'装备','potion':'药水','scroll':'卷轴',
                     'material':'炖物材料','cash':'现金道具'}
            self.log(f"[复制] {names[key]} ×{n}")
            messagebox.showinfo("✅ 演示完成",f"{names[key]} ×{n} 复制成功\n(仅演示，无实际效果)")
        except:
            messagebox.showerror("❌ 错误","请输入有效的正整数")

    def apply_protection(self):
        s1 = "开启" if self.scroll_protect.get() else "关闭"
        s2 = "开启" if self.break_protect.get() else "关闭"
        self.scroll_status.config(text="ON" if self.scroll_protect.get() else "OFF",
                                  fg="#00ff00" if self.scroll_protect.get() else "#ff4444")
        self.break_status.config(text="ON" if self.break_protect.get() else "OFF",
                                  fg="#00ff00" if self.break_protect.get() else "#ff4444")
        self.log(f"[保护] 卷轴次数保护:{s1} 失败不损坏:{s2}")
        messagebox.showinfo("✅ 演示完成",f"保护设置已应用\n(仅演示，无实际效果)")

    def activate_gm(self):
        self.log("[权限] GM权限激活成功 (演示)")
        messagebox.showinfo("👑 GM权限激活", "GM权限已成功激活\n(仅演示，无实际效果)")

    def update_exp_label(self, v):
        v = int(float(v))
        self.exp_label.config(text=f"×{v}")

    def apply_exp_rate(self):
        r = int(self.exp_slider.get())
        self.log(f"[倍率] 经验倍率已设置为 ×{r} (演示)")
        messagebox.showinfo("✅ 演示完成",f"经验倍率已应用: ×{r}\n(仅演示，无实际效果)")

    def toggle_detection(self):
        if self.detect_switch.instate(['selected']):
            threading.Thread(target=self.anti_detect.full_anti_detection, daemon=True).start()
            self.detect_status.config(text="SECURITY SHIELD: ACTIVE", fg="#00ff00")
        else:
            self.anti_detect.is_active = False
            self.anti_detect.detection_status = "未激活"
            self.detect_status.config(text="SECURITY SHIELD: INACTIVE", fg="#ff4444")
            self.log("[反检测] 反检测系统已关闭")

    def start_brute(self):
        threading.Thread(target=self.anti_detect.brute_force_database, 
                         args=(self.update_brute_progress,), daemon=True).start()

    def update_brute_progress(self, value):
        self.brute_progress['value'] = value
        self.root.update()

# ====================== 启动程序 ======================
if __name__ == "__main__":
    # 隐藏控制台黑窗（仅Windows生效）
    if sys.platform == 'win32':
        import ctypes
        ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
    
    root = tk.Tk()
    app = MapleStoryTool(root)
    root.mainloop()