.ai tambahkan fitur ini #   - 🌐 Network AI firewall
#   - 🧲 Anti-tampering watchdog
#   - 🔐 Advanced password vault
#   - 🧬 Behavior-based scanner
#   - 🧠 AI-based anomaly detection
#   - 🧪 Fake Virus Launcher (test reactions)
#   - ⚙️ Auto-Fix corrupted Windows files
#   - 📡 Server beacon (remote command listener)
#   - 📁 File recovery (undelete from quarantine)
#   - 🧿 Registry defender
#   - 🛡️ Anti-rootkit shield
#   - 🛰️ USB auto-scan
#   - 🦠 Malware emulator (sandbox)
#   - ⛓️ Threat chain visualizer
#   - 📊 Threat report analytics
#   - 💡 Real-time suggestion AI (based on logs)
#   - 📌 App locker (block apps temporarily)
#   - ⏳ Timer-based scan scheduler
#   - ☠️ Fake BlueScreen trigger (test reaction)
#   - 🔭 Deep process analyzer
#   - 🔄 Auto self-update
#   - 🌘 Dark/Light Toggle already included
#   - 💠 Branding & cyberpunk animations
#   - 🎛️ Animated LED-styled logging
#   - 🔋 Battery-aware scan (pause on low batt)
#   - 📲 Phone connect companion (future)
#   - 🔐 VPN checker + block DNS leak
#   - 🔍 Browser checker (extensions + injected JS)
#   - 🧯 Emergency Kill-Switch
#   - 🎯 Live threat mapping (worldmap)
#   - 💬 Voice assistant command (future)
#   - 🧵 Thread manager
#   - 🕵️ Anti-tracking (script-level)
#   - ⚠️ Suspicious user behavior monitor
#   - 📂 System file hash validator (SFC-like)
#   - 🛠️ Admin toolkit (CMD tools)
#   - ⏲️ Boot-time startup scanner
#   - 📉 System slowdown detector
#   - 🔗 DNS changer blocker
#   - 📌 Pinned reports on UI
#   - 🧪 Temp file purger
#   - 🌫️ Stealth mode (UI hidden, log to file)
#   - 🔊 Sound alert FX toggle
#   - 🔁 Monitor reloaded apps (post kill)
#   - 🧊 RAM Cleaner on threat idle
#   - 💣 Exploit detector
#   - 🚨 Panic button (Kill all + disconnect net)
#   - 💾 Save config profiles
#   - 📥 Email log sender
#   - 📋 Clipboard hijack monitor
#   - 📌 Button for threat definitions offline install
#   - 🔒 Ransomware trapper (lock honeypot access) dalam script ini import os
import sys
import hashlib
import shutil
import threading
import psutil
import requests
import json
import socket
import platform
import time
import webbrowser
import ctypes
import re
import importlib
from datetime import datetime
import customtkinter as ctk
import traceback
import tkinter
from tkinter import filedialog, messagebox
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

APP_NAME = "N4tzzDefender v5.5 Cyberpunk AI"
CONFIG_FILE = "config.json"
SIGNATURE_DB = {}
SIGNATURE_INDEX_URL = "https://raw.githubusercontent.com/VISWESWARAN1998/open-threat-database/master/ruleset/rule_set1.json"
LOCAL_SIGNATURE_CACHE = "signature_cache.json"
QUARANTINE_FOLDER = "quarantine"
HONEYPOT_FILE = "readme.txt"
LOG_FILE = "logs.txt"
PLUGIN_FOLDER = "plugins"
SILENT_MODE = False
_seen_connections = set()
MALICIOUS_HOSTS = ["malicious-site.com", "ads.badads.com", "127.0.0.1"]
FIREWALL_BLOCKED = []

def load_config():
    global SILENT_MODE
    default_config = {
        "theme": "dark",
        "silent_mode": False,
        "auto_update": True,
        "last_loaded": str(datetime.now())
    }
    if not os.path.exists(CONFIG_FILE):
        save_config(default_config)
        return default_config
    try:
        with open(CONFIG_FILE, "r", encoding="utf-8") as f:
            config = json.load(f)
        SILENT_MODE = config.get("silent_mode", False)
        return config
    except:
        save_config(default_config)
        return default_config

def save_config(config):
    try:
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(config, f, indent=4)
    except:
        pass

def get_md5(path):
    try:
        with open(path, "rb") as f:
            return hashlib.md5(f.read()).hexdigest()
    except:
        return None

def quarantine(file):
    try:
        os.makedirs(QUARANTINE_FOLDER, exist_ok=True)
        shutil.move(file, os.path.join(QUARANTINE_FOLDER, os.path.basename(file)))
        return True
    except:
        return False

def log_event(msg):
    with open(LOG_FILE, "a", encoding='utf-8') as f:
        f.write(f"[{datetime.now().strftime('%H:%M:%S')}] {msg}\n")

def alert_popup(title, msg):
    if not SILENT_MODE:
        try:
            messagebox.showwarning(title, msg)
        except:
            pass

def scan_file(file, callback):
    md5 = get_md5(file)
    if md5 and md5 in SIGNATURE_DB:
        callback(f"⚠️ Virus Detected: {SIGNATURE_DB[md5]} in {file}")
        if quarantine(file):
            callback(f"✅ Quarantined: {file}")
        else:
            callback(f"❌ Failed to Quarantine: {file}")
    else:
        callback(f"✅ Clean: {file}")

def scan_folder(path, callback):
    for root, _, files in os.walk(path):
        for file in files:
            scan_file(os.path.join(root, file), callback)

def firewall_block(host):
    if host not in FIREWALL_BLOCKED:
        FIREWALL_BLOCKED.append(host)
        log_event(f"Firewall blocked: {host}")

def network_monitor(callback):
    global _seen_connections
    for proc in psutil.process_iter(['pid','name']):
        try:
            for c in proc.net_connections(kind="inet"):
                if c.status == "ESTABLISHED" and c.raddr:
                    host = c.raddr.ip
                    info = f"{proc.info['name']} PID {proc.info['pid']} -> {host}:{c.raddr.port}"
                    if info not in _seen_connections:
                        _seen_connections.add(info)
                    if any(m in host for m in MALICIOUS_HOSTS):
                        firewall_block(host)
                        callback(f"🛑 Detected Malicious: {host} (by {proc.info['name']})")
                    else:
                        callback(f"📶 Network: {info}")
        except:
            continue

def honeypot():
    try:
        with open(HONEYPOT_FILE, "w", encoding='utf-8') as f:
            f.write("Don't touch this file.")
    except:
        pass

def honeypot_check(callback):
    if not os.path.exists(HONEYPOT_FILE):
        callback("⚠️ Honeypot triggered!")
        alert_popup("Honeypot Alert", "Suspicious tampering detected!")
        honeypot()

def load_online_signatures_threaded(callback):
    global SIGNATURE_DB
    if os.path.exists(LOCAL_SIGNATURE_CACHE):
        try:
            with open(LOCAL_SIGNATURE_CACHE, "r", encoding='utf-8') as f:
                SIGNATURE_DB = json.load(f)
            callback(f"[SIGNATURE] Loaded {len(SIGNATURE_DB)} entries from cache.")
            return
        except:
            pass

    try:
        r = requests.get(SIGNATURE_INDEX_URL, timeout=10)
        r.raise_for_status()
        SIGNATURE_DB = r.json()
        callback(f"[SIGNATURE] Downloaded {len(SIGNATURE_DB)} signatures.")
        with open(LOCAL_SIGNATURE_CACHE, "w", encoding='utf-8') as f:
            json.dump(SIGNATURE_DB, f, indent=4)
    except:
        callback("[SIGNATURE] Failed to load online database.")

def load_plugins_threaded(callback):
    if not os.path.exists(PLUGIN_FOLDER):
        os.makedirs(PLUGIN_FOLDER)
    for file in os.listdir(PLUGIN_FOLDER):
        if file.endswith(".py"):
            try:
                name = file[:-3]
                spec = importlib.util.spec_from_file_location(name, os.path.join(PLUGIN_FOLDER, file))
                mod = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(mod)
                callback(f"🧩 Plugin loaded: {name}")
            except:
                callback(f"❌ Plugin {file} failed")

class FileMonitor(FileSystemEventHandler):
    def __init__(self, callback):
        self.callback = callback
    def on_created(self, event):
        if not event.is_directory:
            self.callback(f"[Realtime] New file: {event.src_path}")
            scan_file(event.src_path, self.callback)
    def on_modified(self, event):
        if not event.is_directory and event.src_path == HONEYPOT_FILE:
            self.callback("⚠️ Honeypot file modified!")
            honeypot_check(self.callback)

class N4tzzDefenderApp(ctk.CTk):
    def __init__(self):
        super().__init__()
        self.title(APP_NAME)
        self.geometry("1100x740")
        ctk.set_appearance_mode(load_config().get("theme", "dark"))

        # Sidebar
        self.sidebar = ctk.CTkFrame(self, width=200)
        self.sidebar.pack(side="left", fill="y")

        # Main Frame
        self.main = ctk.CTkFrame(self)
        self.main.pack(side="right", fill="both", expand=True)

        self.build_sidebar()
        self.show_dashboard()

        honeypot()
        threading.Thread(target=self.realtime_watchdog, daemon=True).start()
        threading.Thread(target=self.realtime_checks, daemon=True).start()
        threading.Thread(target=load_online_signatures_threaded, args=(self.log,), daemon=True).start()
        threading.Thread(target=load_plugins_threaded, args=(self.log,), daemon=True).start()

    def build_sidebar(self):
        buttons = [
            ("Dashboard", self.show_dashboard),
            ("Scan Folder", self.show_scan),
            ("Network", self.show_network),
            ("Settings", self.show_settings),
            ("Password Protect", self.show_password_protect),  # New Feature
            ("Virus Tester", self.show_virus_tester),  # New Feature
            ("Remote Editor", self.show_remote_editor),  # New Feature
            ("Diagnostic Tool", self.show_diagnostic_tool),  # New Feature
        ]
        for text, cmd in buttons:
            b = ctk.CTkButton(self.sidebar, text=text, command=cmd)
            b.pack(pady=10, padx=10)

    def clear_main(self):
        for w in self.main.winfo_children():
            w.destroy()

    def show_dashboard(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)

        # Quick Scan Button
        quick_scan_button = ctk.CTkButton(frame, text="⚡ Quick Scan", command=self.quick_scan)
        quick_scan_button.pack(pady=10)

        self.logbox = ctk.CTkTextbox(frame, text_color="#00FF00", bg_color="black")  # Cyberpunk theme color
        self.logbox.pack(fill="both", expand=True)
        self.log("🧠 AI Defense System Activated")

    def quick_scan(self):
        # You can define a default folder to scan, or prompt the user
        default_scan_folder = os.getcwd()  # Current working directory
        self.log(f"⚡ Starting Quick Scan in: {default_scan_folder}")
        threading.Thread(target=scan_folder, args=(default_scan_folder, self.log), daemon=True).start()

    def show_scan(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)
        ctk.CTkButton(frame, text="Select Folder", command=self.scan_trigger).pack(pady=20)

    def scan_trigger(self):
        folder = filedialog.askdirectory()
        if folder:
            self.log(f"🔍 Scanning folder: {folder}")
            threading.Thread(target=scan_folder, args=(folder, self.log), daemon=True).start()

    def show_network(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)
        self.netbox = ctk.CTkTextbox(frame)
        self.netbox.pack(fill="both", expand=True)
        ctk.CTkButton(frame, text="Refresh", command=self.refresh_network).pack(pady=10)

    def refresh_network(self):
        self.netbox.delete("1.0", "end")
        for conn in sorted(list(_seen_connections)):
            self.netbox.insert("end", f"{conn}\n")
        if FIREWALL_BLOCKED:
            self.netbox.insert("end", "\n--- Blocked Hosts ---\n")
            for host in sorted(FIREWALL_BLOCKED):
                self.netbox.insert("end", f"🛑 {host}\n")

    def show_settings(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)

        # Theme Toggle
        theme_label = ctk.CTkLabel(frame, text="Theme:")
        theme_label.pack(pady=(10, 0))
        theme_optionmenu = ctk.CTkOptionMenu(frame, values=["dark", "light"], command=self.change_theme)
        theme_optionmenu.pack(pady=(0, 10))
        theme_optionmenu.set(load_config().get("theme", "dark"))  # Set current theme

        # Silent Mode Toggle
        switch = ctk.CTkSwitch(frame, text="Silent Mode", command=self.toggle_silent)
        switch.pack(pady=10)
        if SILENT_MODE:
            switch.select()

    def change_theme(self, theme):
        ctk.set_appearance_mode(theme)
        config = load_config()
        config["theme"] = theme
        save_config(config)
        self.log(f"Theme changed to: {theme}")

    def toggle_silent(self):
        global SILENT_MODE
        SILENT_MODE = not SILENT_MODE
        config = load_config()
        config["silent_mode"] = SILENT_MODE
        save_config(config)
        self.log(f"Silent mode: {SILENT_MODE}")

    # --- New Features ---
    def show_password_protect(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)
        ctk.CTkLabel(frame, text="Password Protection Settings (Under Development)").pack(pady=20)

    def show_virus_tester(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)
        ctk.CTkLabel(frame, text="Virus Sample Tester (Under Development)").pack(pady=20)

    def show_remote_editor(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)
        ctk.CTkLabel(frame, text="Remote Signature Editor (Under Development)").pack(pady=20)

    def show_diagnostic_tool(self):
        self.clear_main()
        frame = ctk.CTkFrame(self.main)
        frame.pack(fill="both", expand=True, padx=20, pady=20)
        ctk.CTkLabel(frame, text="Diagnostic & Fix Tool (Under Development)").pack(pady=20)

    def realtime_watchdog(self):
        observer = Observer()
        observer.schedule(FileMonitor(self.log), os.getcwd(), recursive=True)
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            observer.stop()
            observer.join()

    def realtime_checks(self):
        while True:
            honeypot_check(self.log)
            network_monitor(self.log)
            time.sleep(10)

    def log(self, msg):
        now = datetime.now().strftime("%H:%M:%S")
        if hasattr(self, 'logbox') and self.logbox:
            self.logbox.insert("end", f"[{now}] {msg}\n")
            self.logbox.see("end")
        log_event(msg)

def save_error_to_file(text):
    i = 1
    while True:
        name = f"error{i}.txt"
        if not os.path.exists(name):
            with open(name, "w", encoding='utf-8') as f:
                f.write(text)
            break
        i += 1

if __name__ == "__main__":
    if os.name == 'nt':
        try:
            os.system('chcp 65001')
        except:
            pass
    if os.name == 'nt' and not ctypes.windll.shell32.IsUserAnAdmin():
        try:
            ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
            sys.exit(0)
        except Exception as e:
            save_error_to_file(str(e))
            sys.exit(1)
    try:
        app = N4tzzDefenderApp()
        app.mainloop()
    except Exception as e:
        save_error_to_file(traceback.format_exc())
        try:
            root = tkinter.Tk()
            root.withdraw()
            messagebox.showerror("N4tzzDefender Crash", "Check error log.")
            root.destroy()
        except:
            pass
        sys.exit(1)