#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
NetRadar – Local Network Scanner
Discovers computers, devices and open services on your LAN.
"""

# *************** DEL 01 – IMPORTS & PATH SETUP ***************
# ToDo: Standard library imports + establish base paths that work as EXE too.

import os
import sys
import json
import time
import socket
import threading
import subprocess
import ipaddress
import traceback
import webbrowser
import concurrent.futures
import ctypes
import csv
import base64
import struct
import select
import platform
import re
import shutil
from datetime import datetime
from pathlib import Path

import tkinter as tk
from tkinter import ttk, messagebox

# Base path: always relative to THIS script (works as frozen EXE too)
if getattr(sys, "frozen", False):
    BASE_DIR = Path(sys.executable).parent
else:
    BASE_DIR = Path(__file__).parent

HELPFILES    = BASE_DIR / "Helpfiles"
LOG_DIR      = HELPFILES / "0---Empty"
SETTINGS_DIR = HELPFILES / "0---Settings"

for _d in (LOG_DIR, SETTINGS_DIR):
    _d.mkdir(parents=True, exist_ok=True)

LOG_FILE       = LOG_DIR      / "netradar_log.txt"
SETTINGS_FILE  = SETTINGS_DIR / "netradar_settings.json"
FAVORITES_FILE = SETTINGS_DIR / "netradar_favorites.json"

# Real paths of the Windows tools (never start them by bare name - 01_CORE rule 8).
SYS32      = Path(os.environ.get("SystemRoot", r"C:\Windows")) / "System32"
NET_EXE    = str(SYS32 / "net.exe")
CMDKEY_EXE = str(SYS32 / "cmdkey.exe")


# *************** DEL 02 – COLOUR PALETTE & FONTS ***************
# ToDo: Central colour definitions – change one value here to restyle the whole app.

C_BG        = "#0d1117"   # main window background (very dark)
C_BG2       = "#161b22"   # panel / tab background
C_BG3       = "#1c2128"   # header / dialog background
C_FRAME     = "#21262d"   # widget frame background
C_SEP       = "#30363d"   # separator lines
C_ACCENT    = "#58a6ff"   # blue accent (labels, links)
C_GREEN     = "#3fb950"   # online / success
C_YELLOW    = "#d29922"   # warning
C_RED       = "#f85149"   # error / offline
C_FG        = "#c9d1d9"   # main foreground text
C_FG_DIM    = "#6e7681"   # dimmed / secondary text
C_FG_BRIGHT = "#e6edf3"   # bright / highlighted text
C_TREE_SEL  = "#2d4a6e"   # treeview row selection

# Button colours – each named so they are trivial to change
C_BTN_SCAN  = "#238636"   # green  – scan / start buttons
C_BTN_STOP  = "#8b1a1a"   # red    – stop button
C_BTN_FIX   = "#1f4e79"   # dark blue – fix buttons
C_BTN_COPY  = "#21262d"   # dark   – copy / export / utility buttons
C_BTN_NORM  = "#21262d"   # dark   – neutral buttons

FONT_MAIN   = ("Consolas", 10)
FONT_BOLD   = ("Consolas", 10, "bold")
FONT_SMALL  = ("Consolas", 9)
FONT_TITLE  = ("Consolas", 13, "bold")
FONT_HEADER = ("Consolas", 11, "bold")
FONT_MONO   = ("Courier New", 9)


# *************** DEL 03 – SETTINGS MANAGER ***************
# ToDo: Load/save all user preferences to JSON; always remember previous session.

DEFAULT_SETTINGS = {
    "geometry":     "1150x740",
    "subnet":       "",
    "timeout":      0.8,
    "max_threads":  128,
    "ports":        "22,80,135,139,443,445,3389,5985",
    "do_ports":     True,
    "do_nbtstat":   True,
    "do_dns":       True,
    "last_tab":     0,
    "log_max_lines":2000,
    # Printer tab
    "p_mdns":       True,
    "p_sweep":      True,
    "p_snmp":       True,
    # Favorites: reconnect all saved drives every time NetRadar starts
    "auto_connect": True,
}


def load_settings() -> dict:
    try:
        if SETTINGS_FILE.exists():
            data = json.loads(SETTINGS_FILE.read_text(encoding="utf-8"))
            merged = DEFAULT_SETTINGS.copy()
            merged.update(data)
            return merged
    except Exception:
        pass
    return DEFAULT_SETTINGS.copy()


def save_settings(cfg: dict):
    try:
        SETTINGS_FILE.write_text(json.dumps(cfg, indent=2), encoding="utf-8")
    except Exception:
        pass


# ─── Favorites helpers ──────────────────────────────────────────────────────
# Each favorite is a dict:
#   { "name": str, "letter": "Z:", "path": "\\\\server\\share",
#     "user": str, "_pw": base64-encoded str }

def _fav_encode_pw(pw: str) -> str:
    """Trivial obfuscation – keeps password out of plain text in JSON."""
    return base64.b64encode(pw.encode("utf-8")).decode("ascii") if pw else ""


def _fav_decode_pw(enc: str) -> str:
    try:
        return base64.b64decode(enc.encode("ascii")).decode("utf-8") if enc else ""
    except Exception:
        return ""


def load_favorites() -> list:
    try:
        if FAVORITES_FILE.exists():
            return json.loads(FAVORITES_FILE.read_text(encoding="utf-8"))
    except Exception:
        pass
    return []


def save_favorites(favs: list):
    try:
        FAVORITES_FILE.write_text(json.dumps(favs, indent=2), encoding="utf-8")
    except Exception:
        pass


# *************** DEL 04 – LOGGER ***************
# ToDo: Thread-safe file logger that also feeds registered GUI callbacks.

class Logger:
    _lock      = threading.Lock()
    _callbacks: list = []

    @classmethod
    def register(cls, cb):
        cls._callbacks.append(cb)

    @classmethod
    def log(cls, msg: str, level: str = "INFO"):
        ts   = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        line = f"[{ts}] [{level:5s}] {msg}\n"
        with cls._lock:
            try:
                with open(LOG_FILE, "a", encoding="utf-8") as f:
                    f.write(line)
            except Exception:
                pass
            for cb in cls._callbacks:
                try:
                    cb(line, level)
                except Exception:
                    pass


# *************** DEL 05 – NETWORK UTILITY FUNCTIONS ***************
# ToDo: Low-level helpers: adapter detection, ping, ARP, hostname, NetBIOS, ports.

def get_local_interfaces() -> list:
    """Return list of {name, ip, mask, cidr} for active IPv4 interfaces."""
    interfaces = []
    try:
        out = subprocess.check_output(
            ["ipconfig", "/all"],
            text=True, errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW,
        )
        current_name = "Unknown"
        ip = mask = ""
        for raw_line in out.splitlines():
            line = raw_line.rstrip()
            if line and line[0] not in (" ", "\t"):
                # Flush previous adapter
                if ip and mask and not ip.startswith("169.254"):
                    try:
                        net = ipaddress.IPv4Network(f"{ip}/{mask}", strict=False)
                        interfaces.append(
                            {"name": current_name.strip(": "),
                             "ip": ip, "mask": mask, "cidr": str(net)}
                        )
                    except Exception:
                        pass
                ip = mask = ""
                current_name = line.strip(": \t")
            else:
                s = line.strip()
                if s.lower().startswith("ipv4 address") and ":" in s:
                    ip = s.split(":")[-1].strip().split("(")[0].strip()
                elif s.lower().startswith("subnet mask") and ":" in s:
                    mask = s.split(":")[-1].strip()
        # Last block
        if ip and mask and not ip.startswith("169.254"):
            try:
                net = ipaddress.IPv4Network(f"{ip}/{mask}", strict=False)
                interfaces.append(
                    {"name": current_name.strip(": "),
                     "ip": ip, "mask": mask, "cidr": str(net)}
                )
            except Exception:
                pass
    except Exception as e:
        Logger.log(f"get_local_interfaces: {e}", "ERROR")

    # Fallback via socket
    if not interfaces:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            interfaces.append(
                {"name": "Default",
                 "ip": ip, "mask": "255.255.255.0",
                 "cidr": f"{ip.rsplit('.',1)[0]}.0/24"}
            )
        except Exception:
            pass
    return interfaces


def ping_host(ip: str, timeout: float = 0.8) -> bool:
    """Return True if the host responds to a single ICMP echo."""
    try:
        ms = max(200, int(timeout * 1000))
        r  = subprocess.run(
            ["ping", "-n", "1", "-w", str(ms), ip],
            capture_output=True, text=True,
            creationflags=subprocess.CREATE_NO_WINDOW,
            timeout=timeout + 2.0,
        )
        return r.returncode == 0
    except Exception:
        return False


def get_arp_table() -> dict:
    """Return {ip: mac_str} from the system ARP cache."""
    arp = {}
    try:
        out = subprocess.check_output(
            ["arp", "-a"],
            text=True, errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW,
        )
        for line in out.splitlines():
            parts = line.split()
            if len(parts) >= 3:
                ip_s  = parts[0].strip()
                mac_s = parts[1].strip()
                if ("-" in mac_s or ":" in mac_s) and len(mac_s) >= 11:
                    try:
                        ipaddress.ip_address(ip_s)
                        arp[ip_s] = mac_s.upper()
                    except Exception:
                        pass
    except Exception as e:
        Logger.log(f"get_arp_table: {e}", "ERROR")
    return arp


def resolve_hostname(ip: str, timeout: float = 1.5) -> str:
    """Reverse-DNS lookup; returns empty string on failure."""
    old = socket.getdefaulttimeout()
    try:
        socket.setdefaulttimeout(timeout)
        host, _, _ = socket.gethostbyaddr(ip)
        return host
    except Exception:
        return ""
    finally:
        socket.setdefaulttimeout(old)


def get_netbios_name(ip: str) -> str:
    """Query NetBIOS name via nbtstat -A; returns empty string on failure."""
    try:
        out = subprocess.check_output(
            ["nbtstat", "-A", ip],
            text=True, errors="ignore",
            creationflags=subprocess.CREATE_NO_WINDOW,
            timeout=5,
        )
        for line in out.splitlines():
            s = line.strip()
            if "<00>" in s and "UNIQUE" in s.upper():
                return s.split()[0].strip()
    except Exception:
        pass
    return ""


def check_ports(ip: str, ports: list, timeout: float = 0.5) -> list:
    """Return list of open TCP ports from the given list."""
    open_ports = []
    for port in ports:
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.settimeout(timeout)
                if s.connect_ex((ip, port)) == 0:
                    open_ports.append(port)
        except Exception:
            pass
    return open_ports


PORT_LABELS = {
    21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP",
    53: "DNS", 80: "HTTP", 110: "POP3", 135: "RPC",
    139: "NetBIOS", 143: "IMAP", 443: "HTTPS", 445: "SMB",
    993: "IMAPS", 995: "POP3S", 1433: "MSSQL", 3306: "MySQL",
    3389: "RDP", 5900: "VNC", 5985: "WinRM", 8080: "HTTP-Alt",
    8443: "HTTPS-Alt",
    # Printer / scanner services
    161: "SNMP", 515: "LPD-Printer", 631: "IPP-Printer",
    9100: "RAW-Printer", 9101: "RAW-Printer2", 9102: "RAW-Printer3",
    5357: "WSD", 8610: "Canon-BJNP", 8612: "Canon-BJNP",
}


def format_ports(open_ports: list) -> str:
    parts = []
    for p in sorted(open_ports):
        lbl = PORT_LABELS.get(p, "")
        parts.append(f"{p}/{lbl}" if lbl else str(p))
    return "  ".join(parts)


def get_drive_info() -> tuple:
    """Return (available_letters, mapped_drives).
    available_letters : list of free drive letters, e.g. ['E:', 'F:', 'Y:', 'Z:']
    mapped_drives     : list of (letter, unc_path) for existing net-use mappings.
    """
    import string
    used = set()

    # Drives that already exist on the system
    for letter in string.ascii_uppercase:
        if os.path.exists(f"{letter}:\\"):
            used.add(letter.upper())

    # Collect existing net-use mappings
    mapped = []
    try:
        _rc, out = run_tool(NET_EXE, ["use"], timeout=15)
        for line in out.splitlines():
            parts = line.split()
            # Lines look like: OK  Y:  \\server\share  ...
            for i, p in enumerate(parts):
                if len(p) == 2 and p[1] == ":" and p[0].isalpha():
                    letter = p[0].upper()
                    used.add(letter)
                    unc = parts[i + 1] if i + 1 < len(parts) else ""
                    if unc.startswith("\\\\"):
                        mapped.append((f"{letter}:", unc))
                    break
    except Exception:
        pass

    available = [f"{l}:" for l in string.ascii_uppercase[3:]   # D..Z
                 if l not in used]
    return available, mapped


def is_admin() -> bool:
    try:
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except Exception:
        return False


# *************** DEL 05A – EASY DRIVE MAPPING (login once, map everything) ***************
# ToDo: Whole-PC mapping.  One login per PC -> every drive found (C$, D$ ... or real
#       shares) is mapped, saved as a favorite and remembered in Windows' credential
#       store (cmdkey) so File Explorer's "Network locations" stops asking too.
#       Everything is stored under Helpfiles\0---Settings, so a Windows reinstall only
#       needs NetRadar started once (auto-connect) - nothing is typed again.

def run_tool(exe: str, args: list, timeout: int = 45) -> tuple:
    """Run net.exe / cmdkey.exe by full path. stdin is closed on purpose: without it
    'net use' waits for a typed user name on a hidden console and hangs.
    Returns (returncode, output_text)."""
    try:
        r = subprocess.run(
            [exe] + list(args), capture_output=True, text=True, errors="ignore",
            stdin=subprocess.DEVNULL, timeout=timeout,
            creationflags=subprocess.CREATE_NO_WINDOW,
        )
        return r.returncode, (r.stdout + r.stderr).strip()
    except Exception as exc:
        return 1, str(exc)


def net_error_code(out: str) -> int:
    """Pull the Windows system error number out of net.exe output (any language:
    'System error 5 has occurred' / 'Systemfel 5 har uppstatt')."""
    m = re.search(r"(?:error|fel)\s+(\d+)", out or "", re.IGNORECASE)
    return int(m.group(1)) if m else 0


def net_error_hint(code: int) -> str:
    """Plain-English reason for the usual net use errors."""
    return {
        5:    "Access denied. The account is right, but it may not be an Administrator "
              "on that PC (C$, D$ ... are administrator shares).",
        53:   "The PC or share was not found - is it switched on and on this network?",
        67:   "The share name was not found on that PC.",
        85:   "That drive letter is already in use here.",
        86:   "Wrong password.",
        1219: "Windows already has a connection to this PC with another login. "
              "NetRadar clears it and retries.",
        1326: "Wrong user name or password for that PC. Use the Windows login of that PC "
              "(for a Microsoft account: the e-mail address and its password).",
        1311: "That PC could not log you in.",
        1272: "That PC does not know this user name (it falls back to 'guest', which "
              "Windows blocks). Check the user name - a wrong login is answered after ~20 s.",
    }.get(code, "")


def smb_reachable(host: str, timeout: float = 1.5) -> bool:
    """True when the PC answers on the Windows file-sharing port 445."""
    try:
        with socket.create_connection((host, 445), timeout=timeout):
            return True
    except Exception:
        return False


def unc_host(path: str) -> str:
    """'\\\\192.168.50.47\\D$' -> '192.168.50.47' ('' when not a UNC path)."""
    if not path.startswith("\\\\"):
        return ""
    parts = path.split("\\")
    return parts[2] if len(parts) > 2 else ""


def qualify_user(user: str, cname: str) -> str:
    """'issu' -> 'FILM\\issu' (log in on THAT PC, not as a name of this one).
    Names that already hold a backslash or an @ are left alone."""
    user = (user or "").strip()
    if not user or "\\" in user or "@" in user or not cname:
        return user
    return f"{cname}\\{user}"


def smb_login(host: str, user: str, pw: str) -> tuple:
    """Open (or re-open) a session on the PC with this login. Returns (ok, code, out).
    Error 1219 (another login already open to the same PC) is cleared and retried."""
    target = f"\\\\{host}\\IPC$"
    for attempt in (1, 2):
        rc, out = run_tool(NET_EXE, ["use", target, f"/user:{user}", pw,
                                     "/persistent:no"])
        if rc == 0:
            return True, 0, out
        code = net_error_code(out)
        if code == 1219 and attempt == 1:
            run_tool(NET_EXE, ["use", f"\\\\{host}", "/delete", "/y"])
            run_tool(NET_EXE, ["use", target, "/delete", "/y"])
            continue
        return False, code, out
    return False, 0, ""


def find_remote_drives(host: str) -> list:
    """After smb_login: list the drives of the PC as [(share_name, text)].
    Tries the administrator shares C$ .. Z$ and every disk share that 'net view /all'
    lists.  The text carries free/total space so the user sees which is which."""
    import string
    names = [f"{c}$" for c in string.ascii_uppercase[2:]]

    # Real (non-admin) disk shares, e.g. 'Film' - parse "Name   Disk" lines.
    rc, out = run_tool(NET_EXE, ["view", f"\\\\{host}", "/all"])
    for line in out.splitlines():
        m = re.match(r"^(\S.*?)\s{2,}Disk\b", line)
        if m:
            nm = m.group(1).strip()
            if nm and nm not in names:
                names.append(nm)

    def probe(nm):
        unc = f"\\\\{host}\\{nm}\\"
        try:
            if not os.path.isdir(unc):
                return None
            try:
                u = shutil.disk_usage(unc)
                txt = (f"{u.free / 1e9:,.0f} GB free of {u.total / 1e9:,.0f} GB"
                       .replace(",", " "))
            except Exception:
                txt = "available"
            return (nm, txt)
        except Exception:
            return None

    found = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
        for res in ex.map(probe, names):
            if res:
                found.append(res)
    return found


def pick_letters(shares: list, host: str, favorites: list) -> dict:
    """Choose a free drive letter per share.  A share that is already a favorite keeps
    its letter; new ones get free letters counted DOWN from Z (D..M stay free for
    local disks).  Returns {share_name: 'Z:'}."""
    available, mapped = get_drive_info()
    free = [l for l in reversed(available)]              # Z: first
    chosen = {}
    for nm in shares:
        path = f"\\\\{host}\\{nm}".lower()
        keep = ""
        for f in favorites:
            if f.get("path", "").lower() == path:
                keep = f.get("letter", "")
                break
        if not keep:
            for l, unc in mapped:
                if unc.lower() == path:
                    keep = l
                    break
        if keep and keep not in chosen.values():
            chosen[nm] = keep
            if keep in free:
                free.remove(keep)
    for nm in shares:
        if nm not in chosen:
            if not free:
                break
            chosen[nm] = free.pop(0)
    return chosen


def remember_login(host: str, cname: str, user: str, pw: str):
    """Store the login in Windows' own credential store for the IP and the PC name, so
    Explorer / 'Network locations' / reconnect-at-logon never ask again."""
    for target in {host, cname}:
        if target:
            run_tool(CMDKEY_EXE, [f"/add:{target}", f"/user:{user}", f"/pass:{pw}"])


def host_login(favorites: list, host: str) -> tuple:
    """(user, plain password) saved on ANY favorite of this host - one login serves
    all of its drives."""
    for f in favorites:
        if unc_host(f.get("path", "")) == host and f.get("user"):
            return f["user"], _fav_decode_pw(f.get("_pw", ""))
    return "", ""


# *************** DEL 05B – PRINTER DISCOVERY ***************
# ToDo: Find network printers even when they ignore ping (sleeping printers).
#       Four independent methods, results merged per IP address:
#         1. mDNS / Bonjour multicast query  (_ipp, _printer, _pdl-datastream)
#         2. Direct TCP sweep of printer ports 9100 / 515 / 631
#         3. SNMP v1 GET of sysDescr / sysName  -> real model name
#         4. Windows' own printer list (Get-Printer / Get-PrinterPort)

PRINTER_PORTS = {
    9100: "RAW / JetDirect",
    515:  "LPD",
    631:  "IPP",
    80:   "Web UI",
    443:  "Web UI (TLS)",
}

# Ports actually swept across the subnet (fast: 3 per host)
PRINTER_SWEEP_PORTS = [9100, 515, 631]

# MAC prefix -> vendor. Only a hint; a match strongly suggests a printer maker.
PRINTER_OUI = {
    # Hewlett-Packard
    "00:1B:78": "HP", "00:1E:0B": "HP", "00:23:7D": "HP", "00:25:B3": "HP",
    "3C:D9:2B": "HP", "6C:3B:E5": "HP", "70:5A:0F": "HP", "9C:8E:99": "HP",
    "A0:D3:C1": "HP", "B4:B5:2F": "HP", "C4:34:6B": "HP", "D4:C9:EF": "HP",
    "EC:B1:D7": "HP", "00:17:A4": "HP", "00:30:C1": "HP", "00:0F:20": "HP",
    "00:21:5A": "HP", "00:24:81": "HP", "2C:41:38": "HP", "30:E1:71": "HP",
    "40:B0:34": "HP", "5C:B9:01": "HP", "84:34:97": "HP", "94:57:A5": "HP",
    "00:60:B0": "HP", "08:00:09": "HP",
    # Canon
    "00:00:85": "Canon", "00:1E:8F": "Canon", "00:BB:C1": "Canon",
    "2C:9E:FC": "Canon", "88:87:17": "Canon", "F4:81:39": "Canon",
    # Brother
    "00:80:77": "Brother", "00:1B:A9": "Brother", "30:05:5C": "Brother",
    # Seiko Epson
    "00:00:48": "Epson", "00:26:AB": "Epson", "38:1A:52": "Epson",
    "44:D2:44": "Epson", "64:EB:8C": "Epson", "A4:EE:57": "Epson",
    "AC:18:26": "Epson", "D8:49:2F": "Epson",
    # Xerox
    "00:00:AA": "Xerox", "00:20:85": "Xerox", "08:00:37": "Xerox",
    "9C:93:4E": "Xerox",
    # Lexmark
    "00:04:00": "Lexmark", "00:20:00": "Lexmark", "00:21:B7": "Lexmark",
    # Ricoh
    "00:00:74": "Ricoh", "00:26:73": "Ricoh", "58:38:79": "Ricoh",
    # Kyocera
    "00:C0:EE": "Kyocera", "00:17:C8": "Kyocera",
    # Samsung
    "00:15:99": "Samsung", "00:00:F0": "Samsung", "30:CD:A7": "Samsung",
    "8C:71:F8": "Samsung",
    # Konica Minolta
    "00:20:6B": "Konica Minolta",
    # Dell
    "00:14:22": "Dell", "00:1E:C9": "Dell", "B8:2A:72": "Dell",
    # Others
    "00:07:4D": "Zebra", "00:80:87": "OKI Data",
}


def oui_vendor(mac: str) -> str:
    """Return vendor name for a MAC address prefix, or '' if unknown."""
    if not mac or len(mac) < 8:
        return ""
    return PRINTER_OUI.get(mac[:8].upper().replace("-", ":"), "")


# ─── Minimal BER / ASN.1 helpers (for SNMP – no external modules) ────────────

def _ber_len(n: int) -> bytes:
    if n < 0x80:
        return bytes([n])
    raw = b""
    while n:
        raw = bytes([n & 0xFF]) + raw
        n >>= 8
    return bytes([0x80 | len(raw)]) + raw


def _ber_tlv(tag: int, payload: bytes) -> bytes:
    return bytes([tag]) + _ber_len(len(payload)) + payload


def _ber_int(value: int) -> bytes:
    raw = b""
    v = value
    if v == 0:
        raw = b"\x00"
    while v:
        raw = bytes([v & 0xFF]) + raw
        v >>= 8
    if raw and raw[0] & 0x80:
        raw = b"\x00" + raw
    return _ber_tlv(0x02, raw)


def _ber_oid(oid: str) -> bytes:
    parts = [int(p) for p in oid.split(".")]
    raw = bytes([parts[0] * 40 + parts[1]])
    for p in parts[2:]:
        if p < 0x80:
            raw += bytes([p])
        else:
            chunk = [p & 0x7F]
            p >>= 7
            while p:
                chunk.insert(0, (p & 0x7F) | 0x80)
                p >>= 7
            raw += bytes(chunk)
    return _ber_tlv(0x06, raw)


def _ber_read(data: bytes, i: int):
    """Read one TLV. Returns (tag, value_bytes, index_after)."""
    tag = data[i]
    i += 1
    ln = data[i]
    i += 1
    if ln & 0x80:
        cnt = ln & 0x7F
        ln = int.from_bytes(data[i:i + cnt], "big")
        i += cnt
    return tag, data[i:i + ln], i + ln


def snmp_get(ip: str, oid: str, community: str = "public",
             timeout: float = 1.0) -> str:
    """
    Send a plain SNMPv1 GET and return the answer as text.
    Pure sockets – no pysnmp needed. Returns '' on any failure.
    """
    try:
        req_id = int(time.time() * 1000) & 0x7FFFFFFF
        varbind = _ber_tlv(0x30, _ber_oid(oid) + _ber_tlv(0x05, b""))
        pdu = _ber_tlv(
            0xA0,                                   # GetRequest
            _ber_int(req_id) + _ber_int(0) + _ber_int(0) +
            _ber_tlv(0x30, varbind)
        )
        msg = _ber_tlv(
            0x30,
            _ber_int(0) +                            # version 1 (=0)
            _ber_tlv(0x04, community.encode()) +
            pdu
        )

        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.settimeout(timeout)
            s.sendto(msg, (ip, 161))
            data, _ = s.recvfrom(4096)

        # Unwrap: SEQUENCE > version, community, PDU > id, err, idx, varbinds
        _, body, _ = _ber_read(data, 0)
        i = 0
        _, _, i = _ber_read(body, i)          # version
        _, _, i = _ber_read(body, i)          # community
        _, pdu_body, _ = _ber_read(body, i)   # response PDU
        j = 0
        for _ in range(3):                    # req-id, error-status, error-index
            _, _, j = _ber_read(pdu_body, j)
        _, vb_list, _ = _ber_read(pdu_body, j)
        _, vb, _ = _ber_read(vb_list, 0)      # first varbind
        k = 0
        _, _, k = _ber_read(vb, k)            # the OID
        tag, val, _ = _ber_read(vb, k)        # the value
        if tag in (0x05, 0x80, 0x81, 0x82):   # NULL / noSuchObject etc.
            return ""
        if tag == 0x02:
            return str(int.from_bytes(val, "big"))
        return val.decode("utf-8", "replace").strip()
    except Exception:
        return ""


# Useful printer OIDs
OID_SYS_DESCR = "1.3.6.1.2.1.1.1.0"     # e.g. "HP ETHERNET MULTI-ENVIRONMENT..."
OID_SYS_NAME  = "1.3.6.1.2.1.1.5.0"     # device name
OID_PRT_MODEL = "1.3.6.1.2.1.25.3.2.1.3.1"   # hrDeviceDescr – often the model


def snmp_identify(ip: str) -> tuple:
    """Return (model, sysname) from SNMP, best effort."""
    model = snmp_get(ip, OID_PRT_MODEL, timeout=1.0)
    if not model:
        model = snmp_get(ip, OID_SYS_DESCR, timeout=1.0)
    name = snmp_get(ip, OID_SYS_NAME, timeout=1.0)
    # Trim the very chatty HP/Ricoh descriptions to one readable line
    if model:
        model = model.replace("\r", " ").replace("\n", " ")
        model = " ".join(model.split())[:90]
    return model, name


# ─── mDNS / Bonjour discovery ────────────────────────────────────────────────

MDNS_SERVICES = [
    "_pdl-datastream._tcp.local",   # RAW 9100 printing
    "_ipp._tcp.local",              # IPP (most modern printers)
    "_ipps._tcp.local",             # IPP over TLS
    "_printer._tcp.local",          # LPD
    "_scanner._tcp.local",          # MFP scan unit
    "_uscan._tcp.local",            # eSCL / AirScan
]


def _dns_encode_name(name: str) -> bytes:
    out = b""
    for label in name.split("."):
        if label:
            out += bytes([len(label)]) + label.encode()
    return out + b"\x00"


def _dns_decode_name(data: bytes, i: int) -> tuple:
    """Decode a (possibly compressed) DNS name. Returns (name, next_index)."""
    labels, jumped, next_i, guard = [], False, i, 0
    while guard < 128:
        guard += 1
        if i >= len(data):
            break
        ln = data[i]
        if ln == 0:
            i += 1
            if not jumped:
                next_i = i
            break
        if ln & 0xC0 == 0xC0:                       # compression pointer
            ptr = ((ln & 0x3F) << 8) | data[i + 1]
            if not jumped:
                next_i = i + 2
            jumped = True
            i = ptr
            continue
        labels.append(data[i + 1:i + 1 + ln].decode("utf-8", "replace"))
        i += 1 + ln
    return ".".join(labels), next_i


def mdns_discover(timeout: float = 3.0, log_cb=None) -> dict:
    """
    Multicast an mDNS query for the common printer services and collect
    every answer. Returns { ip: {"name": str, "services": set()} }.
    Works without any Bonjour service installed.
    """
    found = {}
    try:
        # One query packet holding all service questions, unicast-response bit set
        header = struct.pack(">HHHHHH", 0x4E52, 0, len(MDNS_SERVICES), 0, 0, 0)
        body = b""
        for svc in MDNS_SERVICES:
            body += _dns_encode_name(svc) + struct.pack(">HH", 12, 0x8001)
        packet = header + body

        socks = []

        # Socket A – ephemeral port, relies on the unicast-response (QU) bit.
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
        sock.setblocking(False)
        sock.bind(("", 0))
        socks.append(sock)

        # Socket B – real mDNS port 5353, joined to the multicast group, so we
        # also catch printers that reply the normal (multicast) way.
        try:
            msock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            msock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                msock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
            except Exception:
                pass
            msock.bind(("", 5353))
            mreq = socket.inet_aton("224.0.0.251") + socket.inet_aton("0.0.0.0")
            msock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
            msock.setblocking(False)
            socks.append(msock)
        except Exception:
            pass    # port already held by Bonjour/mDNSResponder – socket A is enough

        try:
            sock.sendto(packet, ("224.0.0.251", 5353))
        except Exception as e:
            if log_cb:
                log_cb(f"mDNS send failed: {e}", "WARN")

        deadline = time.time() + timeout
        resent = False
        while time.time() < deadline:
            # A second query halfway through – some printers miss the first one
            if not resent and time.time() > deadline - timeout / 2:
                resent = True
                try:
                    sock.sendto(packet, ("224.0.0.251", 5353))
                except Exception:
                    pass
            ready, _, _ = select.select(socks, [], [], 0.3)
            if not ready:
                continue
            try:
                data, addr = ready[0].recvfrom(9000)
            except Exception:
                continue
            # Only look at responses (QR bit set) – skip queries, including
            # our own packet echoed back to us on the multicast socket.
            if len(data) < 12 or not (data[2] & 0x80):
                continue
            ip = addr[0]
            entry = found.setdefault(ip, {"name": "", "services": set()})
            try:
                qd, an, ns, ar = struct.unpack(">HHHH", data[4:12])
                i = 12
                for _ in range(qd):                 # skip questions
                    _, i = _dns_decode_name(data, i)
                    i += 4
                for _ in range(an + ns + ar):
                    rname, i = _dns_decode_name(data, i)
                    if i + 10 > len(data):
                        break
                    rtype, _rclass, _ttl, rdlen = struct.unpack(
                        ">HHIH", data[i:i + 10])
                    i += 10
                    rdata = data[i:i + rdlen]
                    rd_start = i
                    i += rdlen
                    for svc in MDNS_SERVICES:
                        if svc in rname:
                            entry["services"].add(
                                svc.split(".")[0].lstrip("_"))
                    if rtype == 12:                 # PTR -> instance name
                        inst, _ = _dns_decode_name(data, rd_start)
                        pretty = inst.split("._")[0]
                        if pretty and not entry["name"]:
                            entry["name"] = pretty
                    elif rtype == 1 and rdlen == 4:  # A record
                        a_ip = ".".join(str(b) for b in rdata)
                        if a_ip != ip:
                            found.setdefault(
                                a_ip, {"name": entry["name"],
                                       "services": set(entry["services"])})
            except Exception:
                pass
        for s in socks:
            try:
                s.close()
            except Exception:
                pass
    except Exception as e:
        if log_cb:
            log_cb(f"mDNS discovery error: {e}", "WARN")
    return found


# ─── HTTP title (many printers show the model in the web UI title) ───────────

def http_title(ip: str, port: int = 80, timeout: float = 1.2) -> str:
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            if s.connect_ex((ip, port)) != 0:
                return ""
            s.sendall(
                f"GET / HTTP/1.1\r\nHost: {ip}\r\n"
                f"User-Agent: NetRadar\r\nConnection: close\r\n\r\n".encode()
            )
            buf = b""
            while len(buf) < 16384:
                try:
                    chunk = s.recv(4096)
                except socket.timeout:
                    break
                if not chunk:
                    break
                buf += chunk
                if b"</title>" in buf.lower():
                    break
        text = buf.decode("utf-8", "replace")
        low = text.lower()
        a = low.find("<title")
        if a < 0:
            return ""
        a = low.find(">", a)
        b = low.find("</title>", a)
        if a < 0 or b < 0:
            return ""
        return " ".join(text[a + 1:b].split())[:70]
    except Exception:
        return ""


# ─── Windows' own printer list ───────────────────────────────────────────────

def get_windows_printers() -> list:
    """
    Ask Windows what printers it already knows about, and which IP each
    TCP/IP port points at. Returns a list of dicts.
    """
    out = []
    if platform.system() != "Windows":
        return out
    ps = (
        "$ErrorActionPreference='SilentlyContinue';"
        "$ports=@{};"
        "Get-PrinterPort | ForEach-Object { "
        "  if ($_.PrinterHostAddress) { $ports[$_.Name]=$_.PrinterHostAddress } };"
        "Get-Printer | ForEach-Object { "
        "  [pscustomobject]@{ Name=$_.Name; Port=$_.PortName; "
        "  Driver=$_.DriverName; Status=[string]$_.PrinterStatus; "
        "  Address=$ports[$_.PortName]; Shared=[string]$_.Shared } } | "
        "ConvertTo-Json -Compress"
    )
    try:
        res = subprocess.run(
            ["powershell", "-NoProfile", "-NonInteractive", "-Command", ps],
            capture_output=True, text=True, timeout=45,
            creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
        )
        raw = (res.stdout or "").strip()
        if not raw:
            return out
        data = json.loads(raw)
        if isinstance(data, dict):
            data = [data]
        for d in data:
            out.append({
                "name":    d.get("Name")    or "",
                "port":    d.get("Port")    or "",
                "driver":  d.get("Driver")  or "",
                "status":  d.get("Status")  or "",
                "address": d.get("Address") or "",
                "shared":  d.get("Shared")  or "",
            })
    except Exception:
        pass
    return out


# ─── The printer scan engine ─────────────────────────────────────────────────

class PrinterScanEngine:
    """
    Finds printers that a normal ping sweep misses: many printers sleep and
    drop ICMP, but still answer on TCP 9100 / 515 / 631.
    """

    def __init__(self, result_cb, progress_cb, done_cb, log_cb):
        self.result_cb   = result_cb
        self.progress_cb = progress_cb
        self.done_cb     = done_cb
        self.log_cb      = log_cb
        self._stop       = threading.Event()
        self._thread     = None

    def start(self, subnet: str, use_mdns: bool, use_sweep: bool,
              use_snmp: bool, max_threads: int = 128):
        self._stop.clear()
        self._thread = threading.Thread(
            target=self._run,
            args=(subnet, use_mdns, use_sweep, use_snmp, max_threads),
            daemon=True)
        self._thread.start()

    def stop(self):
        self._stop.set()

    def _run(self, subnet, use_mdns, use_sweep, use_snmp, max_threads):
        try:
            candidates = {}     # ip -> dict

            def _cand(ip):
                return candidates.setdefault(ip, {
                    "ip": ip, "name": "", "model": "", "vendor": "",
                    "ports": [], "sources": set(), "mac": "",
                })

            # ── Phase 1: mDNS / Bonjour ──────────────────────────────────
            if use_mdns and not self._stop.is_set():
                self.log_cb("Phase 1 – mDNS / Bonjour query …", "INFO")
                res = mdns_discover(3.0, self.log_cb)
                for ip, info in res.items():
                    c = _cand(ip)
                    c["sources"].add("mDNS")
                    if info["name"] and not c["name"]:
                        c["name"] = info["name"]
                    c["mdns_services"] = sorted(info["services"])
                self.log_cb(
                    f"Phase 1 done – {len(res)} device(s) answered mDNS.", "INFO")

            # ── Phase 2: TCP sweep of printer ports ──────────────────────
            if use_sweep and not self._stop.is_set():
                net   = ipaddress.IPv4Network(subnet, strict=False)
                hosts = [str(h) for h in net.hosts()]
                total = len(hosts)
                self.log_cb(
                    f"Phase 2 – Probing ports "
                    f"{', '.join(str(p) for p in PRINTER_SWEEP_PORTS)} "
                    f"on {total} addresses …", "INFO")
                done = 0

                def _probe(ip):
                    return ip, check_ports(ip, PRINTER_SWEEP_PORTS, timeout=0.6)

                with concurrent.futures.ThreadPoolExecutor(
                        max_workers=max_threads) as ex:
                    futs = {ex.submit(_probe, ip): ip for ip in hosts}
                    for fut in concurrent.futures.as_completed(futs):
                        if self._stop.is_set():
                            break
                        done += 1
                        self.progress_cb(done, total)
                        try:
                            ip, open_ports = fut.result()
                        except Exception:
                            continue
                        if open_ports:
                            c = _cand(ip)
                            c["sources"].add("Port")
                            for p in open_ports:
                                if p not in c["ports"]:
                                    c["ports"].append(p)
                self.log_cb("Phase 2 done.", "INFO")

            if self._stop.is_set():
                self.log_cb("Printer scan cancelled.", "WARN")
                return

            if not candidates:
                self.log_cb("No printer candidates found.", "WARN")
                return

            # ── Phase 3: identify each candidate ─────────────────────────
            self.log_cb(
                f"Phase 3 – Identifying {len(candidates)} candidate(s) …", "INFO")
            arp = get_arp_table()

            def _identify(c):
                ip = c["ip"]
                if not c["ports"]:
                    c["ports"] = check_ports(
                        ip, [9100, 515, 631, 80, 443], timeout=0.8)
                else:
                    for p in (80, 443):
                        if p not in c["ports"] and check_ports(ip, [p], 0.6):
                            c["ports"].append(p)
                c["mac"] = arp.get(ip, "")
                c["vendor"] = oui_vendor(c["mac"])
                if use_snmp:
                    model, sysname = snmp_identify(ip)
                    if model:
                        c["model"] = model
                        c["sources"].add("SNMP")
                    if sysname and not c["name"]:
                        c["name"] = sysname
                if not c["model"] and 80 in c["ports"]:
                    t = http_title(ip, 80)
                    if t:
                        c["model"] = t
                        c["sources"].add("HTTP")
                if not c["name"]:
                    c["name"] = resolve_hostname(ip)
                return c

            done = 0
            total = len(candidates)
            with concurrent.futures.ThreadPoolExecutor(max_workers=24) as ex:
                futs = {ex.submit(_identify, c): c for c in candidates.values()}
                for fut in concurrent.futures.as_completed(futs):
                    if self._stop.is_set():
                        break
                    done += 1
                    self.progress_cb(done, total)
                    try:
                        c = fut.result()
                    except Exception:
                        continue
                    c["confidence"] = printer_confidence(c)
                    self.result_cb(c)
                    self.log_cb(
                        f"  {c['ip']:<16} {c['confidence']:<8} "
                        f"{(c['model'] or c['name'] or '')[:50]}", "INFO")

            self.log_cb(f"Printer scan complete – {total} candidate(s).", "INFO")
        except Exception as e:
            self.log_cb(
                f"Printer scan error: {e}\n{traceback.format_exc()}", "ERROR")
        finally:
            self.done_cb()


def printer_confidence(c: dict) -> str:
    """Rate how sure we are that this device really is a printer."""
    score = 0
    if 9100 in c["ports"]:
        score += 3
    if 515 in c["ports"]:
        score += 3
    if 631 in c["ports"]:
        score += 3
    if c.get("mdns_services"):
        score += 3
    if c.get("vendor"):
        score += 2
    text = f"{c.get('model','')} {c.get('name','')}".lower()
    for kw in ("print", "laser", "deskjet", "officejet", "envy", "pixma",
               "imageclass", "workforce", "ecotank", "stylus", "mfc", "dcp",
               "hl-", "phaser", "versalink", "altalink", "aficio", "bizhub"):
        if kw in text:
            score += 3
            break
    return "Certain" if score >= 6 else ("Likely" if score >= 3 else "Maybe")


# *************** DEL 06 – SCAN ENGINE ***************
# ToDo: Three-phase scan: ping sweep → ARP enrichment → DNS/NetBIOS/port probing.

class ScanEngine:
    def __init__(self, cfg: dict, result_cb, progress_cb, done_cb, log_cb):
        self.cfg         = cfg
        self.result_cb   = result_cb    # called with host dict (from worker thread)
        self.progress_cb = progress_cb  # called with (done, total)
        self.done_cb     = done_cb      # called when scan finishes
        self.log_cb      = log_cb
        self._stop       = threading.Event()
        self._thread     = None

    def start(self, subnet: str):
        self._stop.clear()
        self._thread = threading.Thread(
            target=self._run, args=(subnet,), daemon=True
        )
        self._thread.start()

    def stop(self):
        self._stop.set()

    def _run(self, subnet: str):
        try:
            net     = ipaddress.IPv4Network(subnet, strict=False)
            hosts   = list(net.hosts())
            total   = len(hosts)
            timeout = float(self.cfg.get("timeout", 0.8))
            max_t   = int(self.cfg.get("max_threads", 128))
            do_ports= self.cfg.get("do_ports", True)
            do_nbt  = self.cfg.get("do_nbtstat", True)
            do_dns  = self.cfg.get("do_dns", True)
            p_str   = self.cfg.get("ports", "80,135,445,3389")
            port_list = [int(p.strip()) for p in p_str.split(",")
                         if p.strip().isdigit()]

            self.log_cb(f"Scan started: {subnet}  ({total} addresses)", "INFO")

            # ── Phase 1: Ping sweep ──────────────────────────────────────
            self.log_cb("Phase 1/3 – Ping sweep …", "INFO")
            alive = []
            done  = 0
            with concurrent.futures.ThreadPoolExecutor(max_workers=max_t) as ex:
                futs = {
                    ex.submit(ping_host, str(ip), timeout): str(ip)
                    for ip in hosts
                }
                for fut in concurrent.futures.as_completed(futs):
                    if self._stop.is_set():
                        break
                    ip = futs[fut]
                    done += 1
                    self.progress_cb(done, total)
                    try:
                        if fut.result():
                            alive.append(ip)
                    except Exception:
                        pass

            if self._stop.is_set():
                self.log_cb("Scan cancelled.", "WARN")
                self.done_cb()
                return

            self.log_cb(
                f"Phase 1 done – {len(alive)} host(s) responded to ping.", "INFO"
            )

            # ── Phase 2: Read ARP cache (MACs) ───────────────────────────
            self.log_cb("Phase 2/3 – Reading ARP cache …", "INFO")
            arp_table = get_arp_table()

            # ── Phase 3: Enrich each alive host ──────────────────────────
            self.log_cb(
                f"Phase 3/3 – Enriching {len(alive)} host(s) …", "INFO"
            )
            done3   = 0
            total3  = len(alive)

            def _enrich(ip):
                h = {
                    "ip":       ip,
                    "hostname": "",
                    "netbios":  "",
                    "mac":      arp_table.get(ip, ""),
                    "ports":    [],
                    "ports_str":"",
                    "status":   "Online",
                }
                if do_dns:
                    h["hostname"] = resolve_hostname(ip)
                if do_nbt:
                    h["netbios"]  = get_netbios_name(ip)
                if do_ports and port_list:
                    h["ports"]     = check_ports(ip, port_list, timeout=0.5)
                    h["ports_str"] = format_ports(h["ports"])
                return h

            with concurrent.futures.ThreadPoolExecutor(
                max_workers=min(32, max_t)
            ) as ex:
                futs3 = {ex.submit(_enrich, ip): ip for ip in alive}
                for fut in concurrent.futures.as_completed(futs3):
                    if self._stop.is_set():
                        break
                    done3 += 1
                    self.progress_cb(
                        max(done3, total - total3 + done3), total
                    )
                    try:
                        result = fut.result()
                        self.result_cb(result)
                        name = (result["hostname"] or
                                result["netbios"]  or
                                result["ip"])
                        self.log_cb(
                            f"  Found: {result['ip']:<16}  {name}", "INFO"
                        )
                    except Exception as e:
                        self.log_cb(f"  Enrich error: {e}", "ERROR")

            self.log_cb(
                f"Scan complete. {len(alive)} host(s) found.", "INFO"
            )
        except Exception as e:
            self.log_cb(
                f"Scan engine error: {e}\n{traceback.format_exc()}", "ERROR"
            )
        finally:
            self.done_cb()


# *************** DEL 07 – WINDOWS NETWORK FIX DEFINITIONS ***************
# ToDo: Define all fix commands for enabling network discovery on Windows 11.

FIXES = [
    {
        "id":    "ping_in",
        "label": "Allow inbound Ping (ICMPv4)  ← most important",
        "cmd":   ('netsh advfirewall firewall add rule '
                  'name="Allow ICMPv4 In" protocol=icmpv4:8,any dir=in action=allow'),
        "desc":  "Your PC won't respond to pings until this is enabled. NetRadar needs this.",
    },
    {
        "id":    "netdisc_private",
        "label": "Enable Network Discovery – Private network",
        "cmd":   ('netsh advfirewall firewall set rule '
                  'group="Network Discovery" new enable=Yes profile=private'),
        "desc":  "Allows this PC to see and be seen by other machines on private networks.",
    },
    {
        "id":    "netdisc_domain",
        "label": "Enable Network Discovery – Domain network",
        "cmd":   ('netsh advfirewall firewall set rule '
                  'group="Network Discovery" new enable=Yes profile=domain'),
        "desc":  "Same as above, for domain-joined networks.",
    },
    {
        "id":    "fileshare",
        "label": "Enable File & Printer Sharing",
        "cmd":   ('netsh advfirewall firewall set rule '
                  'group="File and Printer Sharing" new enable=Yes'),
        "desc":  "Needed for SMB shares and Windows network browsing.",
    },
    {
        "id":    "set_private",
        "label": "Set current network profile to Private",
        "cmd":   ('powershell -Command "'
                  'Get-NetConnectionProfile | '
                  'Set-NetConnectionProfile -NetworkCategory Private"'),
        "desc":  "Windows hides machines on Public profile networks. This switches to Private.",
    },
    {
        "id":    "netbios",
        "label": "Enable NetBIOS over TCP/IP (all adapters)",
        "cmd":   ('powershell -Command "'
                  'Get-WmiObject Win32_NetworkAdapterConfiguration | '
                  'Where-Object { $_.IPEnabled } | '
                  'ForEach-Object { $_.SetTcpipNetbios(1) }"'),
        "desc":  "Enables legacy computer name broadcasting used by Windows network browser.",
    },
    {
        "id":    "fdphost",
        "label": "Start Function Discovery services",
        "cmd":   ('powershell -Command "'
                  'Set-Service fdphost  -StartupType Automatic; Start-Service fdphost; '
                  'Set-Service FDResPub -StartupType Automatic; Start-Service FDResPub; '
                  'Set-Service SSDPSRV  -StartupType Automatic; Start-Service SSDPSRV; '
                  'Set-Service upnphost -StartupType Automatic; Start-Service upnphost"'),
        "desc":  "These services power the Windows network browser. Often disabled on fresh Win11.",
    },
    {
        "id":    "llmnr",
        "label": "Enable LLMNR (Link-Local Multicast Name Resolution)",
        "cmd":   ('powershell -Command "'
                  "Set-ItemProperty -Path "
                  "'HKLM:\\SOFTWARE\\Policies\\Microsoft\\Windows NT\\DNSClient' "
                  '-Name EnableMulticast -Value 1 -Type DWord -Force"'),
        "desc":  "Resolves hostnames on local segment without DNS.",
    },
    {
        "id":    "smb2",
        "label": "Ensure SMBv2 is enabled",
        "cmd":   ('powershell -Command "'
                  'Set-SmbServerConfiguration -EnableSMB2Protocol $true -Force"'),
        "desc":  "SMBv2 must be enabled for modern Windows file sharing.",
    },
    {
        "id":    "winrm",
        "label": "Enable WinRM (remote PowerShell management)",
        "cmd":   ('powershell -Command "'
                  'Enable-PSRemoting -Force -SkipNetworkProfileCheck"'),
        "desc":  "Enables remote management. Useful for administration scripts.",
    },
    {
        "id":    "flush_dns",
        "label": "Flush DNS & NetBIOS caches",
        "cmd":   "ipconfig /flushdns && nbtstat -R && nbtstat -RR",
        "desc":  "Clears stale name resolution entries that can cause connection failures.",
    },
    {
        "id":    "smb1",
        "label": "Enable SMBv1  (LEGACY – only if needed for old NAS/devices)",
        "cmd":   ('powershell -Command "'
                  'Enable-WindowsOptionalFeature -Online -FeatureName '
                  'SMB1Protocol -NoRestart"'),
        "desc":  "Not needed for Win11 ↔ Win11. Only for very old NAS boxes or XP machines.",
    },
]

RECOMMENDED_FIXES = {
    "ping_in", "netdisc_private", "fileshare",
    "set_private", "netbios", "fdphost",
}


def run_fix_command(cmd: str):
    """Run a fix command; returns (success: bool, output: str)."""
    try:
        if is_admin():
            r = subprocess.run(
                cmd, shell=True,
                capture_output=True, text=True, errors="ignore",
                creationflags=subprocess.CREATE_NO_WINDOW,
                timeout=30,
            )
            out = (r.stdout + r.stderr).strip()
            return r.returncode == 0, out
        else:
            # Request UAC elevation via ShellExecute
            rc = ctypes.windll.shell32.ShellExecuteW(
                None, "runas", "cmd.exe", f'/c "{cmd}"', None, 1
            )
            if rc > 32:
                return True, "Sent for admin execution (UAC prompt may have appeared)."
            return False, f"UAC elevation failed (code {rc})."
    except Exception as e:
        return False, str(e)


# *************** DEL 08 – MAIN APPLICATION CLASS ***************
# ToDo: Build the Tkinter window: title bar, notebook with Scanner / ARP / Fix / Log tabs.

class NetRadarApp:

    def __init__(self, root: tk.Tk):
        self.root         = root
        self.cfg          = load_settings()
        self._scan_engine = None
        self._scanning    = False
        self._p_engine    = None
        self._p_scanning  = False
        self._hosts: list = []
        self._fix_btns    = {}
        self._fix_status  = {}
        self._asking_login = set()   # hosts whose login dialog is open right now
        self._cmdkey_done  = set()   # hosts whose login is already in Windows' store

        self._setup_window()
        self._style_ttk()
        self._favorites: list = load_favorites()
        self.var_auto = tk.BooleanVar(value=bool(self.cfg.get("auto_connect", True)))
        self._build_ui()
        self._apply_geometry()
        self._detect_subnet()
        Logger.register(self._on_log_cb)
        Logger.log("NetRadar started.", "INFO")
        # Saved drives come back by themselves (also after a Windows reinstall).
        if self.var_auto.get() and self._favorites:
            self.root.after(900, self._auto_connect_favorites)

    # ------------------------------------------------------------------ #
    #  Window / style                                                      #
    # ------------------------------------------------------------------ #

    def _setup_window(self):
        self.root.title("NetRadar – Network Scanner")
        self.root.configure(bg=C_BG)
        self.root.protocol("WM_DELETE_WINDOW", self._on_close)
        self.root.minsize(820, 580)

    def _apply_geometry(self):
        try:
            self.root.geometry(self.cfg.get("geometry", "1150x740"))
        except Exception:
            self.root.geometry("1150x740")

    def _style_ttk(self):
        s = ttk.Style()
        s.theme_use("clam")
        s.configure(".", background=C_BG2, foreground=C_FG,
                    fieldbackground=C_FRAME, bordercolor=C_SEP,
                    troughcolor=C_BG, font=FONT_MAIN)
        s.configure("TNotebook", background=C_BG, tabmargins=[2, 2, 2, 0])
        s.configure("TNotebook.Tab", background=C_BG2, foreground=C_FG_DIM,
                    padding=[14, 5], font=FONT_BOLD)
        s.map("TNotebook.Tab",
              background=[("selected", C_FRAME)],
              foreground=[("selected", C_FG_BRIGHT)])
        s.configure("Treeview", background=C_FRAME, foreground=C_FG,
                    fieldbackground=C_FRAME, rowheight=22, font=FONT_SMALL)
        s.configure("Treeview.Heading", background=C_BG2, foreground=C_ACCENT,
                    font=FONT_BOLD, relief="flat")
        s.map("Treeview",
              background=[("selected", C_TREE_SEL)],
              foreground=[("selected", C_FG_BRIGHT)])
        s.configure("TProgressbar", troughcolor=C_BG2,
                    background=C_ACCENT, thickness=6)
        s.configure("TScrollbar", background=C_BG2, troughcolor=C_BG,
                    arrowcolor=C_FG_DIM, bordercolor=C_SEP)
        s.configure("TCheckbutton", background=C_BG2,
                    foreground=C_FG, font=FONT_SMALL)
        s.map("TCheckbutton", background=[("active", C_BG2)])

    # ------------------------------------------------------------------ #
    #  Helper: create a flat button                                        #
    # ------------------------------------------------------------------ #

    def _btn(self, parent, text, cmd,
             bg=C_BTN_NORM, fg=C_FG, font=FONT_BOLD,
             width=None, pady=4, padx=10):
        kw = dict(text=text, command=cmd, bg=bg, fg=fg, font=font,
                  relief="flat", cursor="hand2",
                  activebackground=C_SEP, activeforeground=C_FG_BRIGHT,
                  pady=pady, padx=padx, bd=0)
        if width:
            kw["width"] = width
        return tk.Button(parent, **kw)

    # Helper: no-blink entry
    def _entry(self, parent, textvariable=None, width=20, **kw):
        defaults = dict(bg=C_FRAME, fg=C_FG_BRIGHT, font=FONT_MAIN,
                        insertbackground=C_ACCENT, relief="flat",
                        insertofftime=0, insertontime=9999999)
        defaults.update(kw)
        if textvariable:
            defaults["textvariable"] = textvariable
        defaults["width"] = width
        return tk.Entry(parent, **defaults)

    # ------------------------------------------------------------------ #
    #  Build UI                                                            #
    # ------------------------------------------------------------------ #

    def _build_ui(self):
        # ── Title bar ─────────────────────────────────────────────────
        tbar = tk.Frame(self.root, bg=C_BG3, height=46)
        tbar.pack(fill="x")
        tbar.pack_propagate(False)

        tk.Label(tbar, text="◉  NetRadar", bg=C_BG3, fg=C_ACCENT,
                 font=("Consolas", 14, "bold")).pack(side="left", padx=14, pady=8)
        tk.Label(tbar, text="Local Network Scanner", bg=C_BG3, fg=C_FG_DIM,
                 font=("Consolas", 9, "italic")).pack(side="left", pady=8)

        right_bar = tk.Frame(tbar, bg=C_BG3)
        right_bar.pack(side="right", padx=8, pady=6)
        self._btn(right_bar, "Help",  self._show_help,  bg="grey30").pack(side="right", padx=3)
        self._btn(right_bar, "About", self._show_about, bg="grey30").pack(side="right", padx=3)

        # ── Notebook ──────────────────────────────────────────────────
        self.nb = ttk.Notebook(self.root)
        self.nb.pack(fill="both", expand=True, padx=6, pady=6)
        self.nb.bind("<<NotebookTabChanged>>", self._on_tab_change)

        self._tab_scanner  = tk.Frame(self.nb, bg=C_BG2)
        self._tab_printer  = tk.Frame(self.nb, bg=C_BG2)
        self._tab_arp      = tk.Frame(self.nb, bg=C_BG2)
        self._tab_fix      = tk.Frame(self.nb, bg=C_BG2)
        self._tab_fav      = tk.Frame(self.nb, bg=C_BG2)
        self._tab_log      = tk.Frame(self.nb, bg=C_BG2)

        self.nb.add(self._tab_scanner, text="  Scanner  ")
        self.nb.add(self._tab_printer, text="  🖨 Printers  ")
        self.nb.add(self._tab_arp,     text="  ARP Cache  ")
        self.nb.add(self._tab_fix,     text="  Windows Fix  ")
        self.nb.add(self._tab_fav,     text="  ★ Favorites  ")
        self.nb.add(self._tab_log,     text="  Log  ")

        self._build_scanner_tab()
        self._build_printer_tab()
        self._build_arp_tab()
        self._build_fix_tab()
        self._build_favorites_tab()
        self._build_log_tab()

        try:
            self.nb.select(int(self.cfg.get("last_tab", 0)))
        except Exception:
            pass

    # ------------------------------------------------------------------ #
    #  SCANNER TAB                                                         #
    # ------------------------------------------------------------------ #

    def _build_scanner_tab(self):
        tab = self._tab_scanner

        # Row 1 – subnet, timeout, threads, checkboxes
        r1 = tk.Frame(tab, bg=C_BG2)
        r1.pack(fill="x", padx=8, pady=(8, 2))

        tk.Label(r1, text="Subnet:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left")
        self.var_subnet = tk.StringVar(value=self.cfg.get("subnet", ""))
        e_sub = self._entry(r1, textvariable=self.var_subnet, width=20)
        e_sub.pack(side="left", padx=(4, 12))
        e_sub.bind("<Return>", lambda _e: self._start_scan())

        tk.Label(r1, text="Timeout s:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left")
        self.var_timeout = tk.StringVar(value=str(self.cfg.get("timeout", 0.8)))
        self._entry(r1, textvariable=self.var_timeout, width=5).pack(
            side="left", padx=(4, 12))

        tk.Label(r1, text="Threads:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left")
        self.var_threads = tk.StringVar(value=str(self.cfg.get("max_threads", 128)))
        self._entry(r1, textvariable=self.var_threads, width=5).pack(
            side="left", padx=(4, 12))

        self.var_do_dns   = tk.BooleanVar(value=self.cfg.get("do_dns",     True))
        self.var_do_nbt   = tk.BooleanVar(value=self.cfg.get("do_nbtstat", True))
        self.var_do_ports = tk.BooleanVar(value=self.cfg.get("do_ports",   True))
        for var, txt in [(self.var_do_dns,   "Resolve DNS"),
                         (self.var_do_nbt,   "NetBIOS names"),
                         (self.var_do_ports, "Check ports")]:
            ttk.Checkbutton(r1, text=txt, variable=var).pack(side="left", padx=4)

        # Row 2 – ports + action buttons
        r2 = tk.Frame(tab, bg=C_BG2)
        r2.pack(fill="x", padx=8, pady=(0, 4))

        tk.Label(r2, text="Ports:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left")
        self.var_ports = tk.StringVar(
            value=self.cfg.get("ports", "22,80,135,139,443,445,3389,5985"))
        self._entry(r2, textvariable=self.var_ports, width=38).pack(
            side="left", padx=(4, 14))

        self._btn_scan = self._btn(r2, "▶  Scan",          self._start_scan,
                                   bg=C_BTN_SCAN, fg="white", width=12)
        self._btn_scan.pack(side="left", padx=2)

        self._btn_stop = self._btn(r2, "■  Stop",          self._stop_scan,
                                   bg=C_BTN_STOP, fg="white", width=10)
        self._btn_stop.pack(side="left", padx=2)
        self._btn_stop.configure(state="disabled")

        self._btn(r2, "ARP quick-scan", self._arp_quick_scan,
                  bg=C_BTN_COPY, fg=C_FG, width=16).pack(side="left", padx=8)

        self._btn(r2, "Export CSV", self._export_csv,
                  bg=C_BTN_COPY, fg=C_FG, width=12).pack(side="right", padx=2)
        self._btn(r2, "Clear",      self._clear_results,
                  bg=C_BTN_COPY, fg=C_FG, width=8 ).pack(side="right", padx=2)

        # Progress bar
        pr = tk.Frame(tab, bg=C_BG2)
        pr.pack(fill="x", padx=8, pady=(0, 3))
        self._progress_var = tk.DoubleVar(value=0)
        ttk.Progressbar(pr, variable=self._progress_var,
                        maximum=100).pack(side="left", fill="x", expand=True)
        self._lbl_progress = tk.Label(pr, text="Ready", bg=C_BG2, fg=C_FG_DIM,
                                      font=FONT_SMALL, width=30, anchor="w")
        self._lbl_progress.pack(side="left", padx=8)

        # Adapter info row
        ir = tk.Frame(tab, bg=C_BG2)
        ir.pack(fill="x", padx=8, pady=(0, 2))
        tk.Label(ir, text="Adapters:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left")
        self._lbl_ifaces = tk.Label(ir, text="…", bg=C_BG2, fg=C_GREEN,
                                    font=FONT_SMALL, anchor="w")
        self._lbl_ifaces.pack(side="left", padx=4)
        self._btn(ir, "Refresh", self._detect_subnet,
                  bg=C_BTN_COPY, fg=C_FG, padx=6).pack(side="left", padx=6)

        # Results treeview
        tf = tk.Frame(tab, bg=C_BG2)
        tf.pack(fill="both", expand=True, padx=8, pady=(2, 4))

        cols = ("ip", "hostname", "netbios", "mac", "ports", "status")
        self._tree = ttk.Treeview(tf, columns=cols, show="headings",
                                  selectmode="browse")
        hdrs = {
            "ip":       ("IP Address",          130),
            "hostname": ("Hostname (DNS)",       200),
            "netbios":  ("NetBIOS Name",         155),
            "mac":      ("MAC Address",          155),
            "ports":    ("Open Ports / Services",330),
            "status":   ("Status",               70),
        }
        for c, (h, w) in hdrs.items():
            self._tree.heading(c, text=h, anchor="w")
            self._tree.column(c, width=w, minwidth=60, anchor="w")

        vsb = ttk.Scrollbar(tf, orient="vertical",   command=self._tree.yview)
        hsb = ttk.Scrollbar(tf, orient="horizontal", command=self._tree.xview)
        self._tree.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self._tree.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
        tf.rowconfigure(0, weight=1)
        tf.columnconfigure(0, weight=1)

        self._tree.bind("<MouseWheel>",
            lambda e: self._tree.yview_scroll(-1*(e.delta//120), "units"))
        self._tree.bind("<Button-3>", self._tree_rclick)
        self._tree.tag_configure("online",  foreground=C_GREEN)
        self._tree.tag_configure("arp_row", foreground=C_YELLOW)

    # ------------------------------------------------------------------ #
    #  PRINTER TAB                                                         #
    # ------------------------------------------------------------------ #
    # ToDo: Dedicated printer hunt – finds printers a ping sweep misses.

    def _build_printer_tab(self):
        tab = self._tab_printer

        # Row 1 – explanation
        tk.Label(tab,
                 text="Finds network printers even when they ignore ping "
                      "(sleeping printers answer on port 9100 / 515 / 631).",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
                 anchor="w").pack(fill="x", padx=10, pady=(8, 2))

        # Row 2 – options + buttons
        r1 = tk.Frame(tab, bg=C_BG2)
        r1.pack(fill="x", padx=8, pady=(0, 4))

        tk.Label(r1, text="Subnet:", bg=C_BG2, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left")
        self.var_p_subnet = tk.StringVar(value=self.cfg.get("subnet", ""))
        e_ps = self._entry(r1, textvariable=self.var_p_subnet, width=20)
        e_ps.pack(side="left", padx=(4, 12))
        e_ps.bind("<Return>", lambda _e: self._start_printer_scan())

        self.var_p_mdns  = tk.BooleanVar(value=self.cfg.get("p_mdns",  True))
        self.var_p_sweep = tk.BooleanVar(value=self.cfg.get("p_sweep", True))
        self.var_p_snmp  = tk.BooleanVar(value=self.cfg.get("p_snmp",  True))
        for var, txt in [(self.var_p_mdns,  "mDNS / Bonjour"),
                         (self.var_p_sweep, "Port sweep"),
                         (self.var_p_snmp,  "SNMP model lookup")]:
            ttk.Checkbutton(r1, text=txt, variable=var).pack(side="left", padx=4)

        r2 = tk.Frame(tab, bg=C_BG2)
        r2.pack(fill="x", padx=8, pady=(0, 4))

        self._btn_pscan = self._btn(r2, "🖨  Find printers",
                                    self._start_printer_scan,
                                    bg=C_BTN_SCAN, fg="white", width=18)
        self._btn_pscan.pack(side="left", padx=2)

        self._btn_pstop = self._btn(r2, "■  Stop", self._stop_printer_scan,
                                    bg=C_BTN_STOP, fg="white", width=10)
        self._btn_pstop.pack(side="left", padx=2)
        self._btn_pstop.configure(state="disabled")

        self._btn(r2, "Installed printers", self._refresh_win_printers,
                  bg=C_BTN_FIX, fg="white", width=18).pack(side="left", padx=8)
        self._btn(r2, "Add printer wizard", self._open_add_printer,
                  bg=C_BTN_NORM, fg=C_FG, width=18).pack(side="left", padx=2)
        self._btn(r2, "Windows printer folder", self._open_printer_folder,
                  bg=C_BTN_NORM, fg=C_FG, width=22).pack(side="left", padx=2)

        self._btn(r2, "Export CSV", self._export_printers_csv,
                  bg=C_BTN_COPY, fg=C_FG, width=12).pack(side="right", padx=2)
        self._btn(r2, "Clear", self._clear_printers,
                  bg=C_BTN_COPY, fg=C_FG, width=8).pack(side="right", padx=2)

        # Progress
        pr = tk.Frame(tab, bg=C_BG2)
        pr.pack(fill="x", padx=8, pady=(0, 3))
        self._p_progress_var = tk.DoubleVar(value=0)
        ttk.Progressbar(pr, variable=self._p_progress_var,
                        maximum=100).pack(side="left", fill="x", expand=True)
        self._lbl_p_progress = tk.Label(pr, text="Ready", bg=C_BG2, fg=C_FG_DIM,
                                        font=FONT_SMALL, width=30, anchor="w")
        self._lbl_p_progress.pack(side="left", padx=8)

        # ── Found-on-network tree ────────────────────────────────────────
        tk.Label(tab, text="Printers found on the network",
                 bg=C_BG2, fg=C_ACCENT, font=FONT_HEADER,
                 anchor="w").pack(fill="x", padx=10, pady=(4, 0))

        tf = tk.Frame(tab, bg=C_BG2)
        tf.pack(fill="both", expand=True, padx=8, pady=(2, 4))

        pcols = ("ip", "conf", "model", "name", "vendor", "ports", "via")
        self._ptree = ttk.Treeview(tf, columns=pcols, show="headings",
                                   selectmode="browse", height=8)
        phdrs = {
            "ip":     ("IP Address",       125),
            "conf":   ("Confidence",        85),
            "model":  ("Model / Web title",300),
            "name":   ("Name",             180),
            "vendor": ("Vendor (MAC)",     110),
            "ports":  ("Printer ports",    190),
            "via":    ("Found via",        140),
        }
        for c, (h, w) in phdrs.items():
            self._ptree.heading(c, text=h, anchor="w")
            self._ptree.column(c, width=w, minwidth=60, anchor="w")

        pv = ttk.Scrollbar(tf, orient="vertical",   command=self._ptree.yview)
        ph = ttk.Scrollbar(tf, orient="horizontal", command=self._ptree.xview)
        self._ptree.configure(yscrollcommand=pv.set, xscrollcommand=ph.set)
        self._ptree.grid(row=0, column=0, sticky="nsew")
        pv.grid(row=0, column=1, sticky="ns")
        ph.grid(row=1, column=0, sticky="ew")
        tf.rowconfigure(0, weight=1)
        tf.columnconfigure(0, weight=1)

        self._ptree.bind("<MouseWheel>",
            lambda e: self._ptree.yview_scroll(-1 * (e.delta // 120), "units"))
        self._ptree.bind("<Button-3>", self._ptree_rclick)
        self._ptree.bind("<Double-1>", self._ptree_dclick)
        self._ptree.tag_configure("certain", foreground=C_GREEN)
        self._ptree.tag_configure("likely",  foreground=C_YELLOW)
        self._ptree.tag_configure("maybe",   foreground=C_FG_DIM)

        # ── Windows installed printers tree ──────────────────────────────
        tk.Label(tab, text="Printers Windows already has installed",
                 bg=C_BG2, fg=C_ACCENT, font=FONT_HEADER,
                 anchor="w").pack(fill="x", padx=10, pady=(4, 0))

        wf = tk.Frame(tab, bg=C_BG2)
        wf.pack(fill="both", expand=True, padx=8, pady=(2, 8))

        wcols = ("name", "address", "port", "driver", "status", "shared")
        self._wtree = ttk.Treeview(wf, columns=wcols, show="headings",
                                   selectmode="browse", height=6)
        whdrs = {
            "name":    ("Printer name",   260),
            "address": ("IP / Host",      140),
            "port":    ("Port",           170),
            "driver":  ("Driver",         260),
            "status":  ("Status",         110),
            "shared":  ("Shared",          70),
        }
        for c, (h, w) in whdrs.items():
            self._wtree.heading(c, text=h, anchor="w")
            self._wtree.column(c, width=w, minwidth=60, anchor="w")

        wv = ttk.Scrollbar(wf, orient="vertical",   command=self._wtree.yview)
        wh = ttk.Scrollbar(wf, orient="horizontal", command=self._wtree.xview)
        self._wtree.configure(yscrollcommand=wv.set, xscrollcommand=wh.set)
        self._wtree.grid(row=0, column=0, sticky="nsew")
        wv.grid(row=0, column=1, sticky="ns")
        wh.grid(row=1, column=0, sticky="ew")
        wf.rowconfigure(0, weight=1)
        wf.columnconfigure(0, weight=1)

        self._wtree.bind("<MouseWheel>",
            lambda e: self._wtree.yview_scroll(-1 * (e.delta // 120), "units"))
        self._wtree.bind("<Button-3>", self._wtree_rclick)
        self._wtree.tag_configure("offline", foreground=C_RED)
        self._wtree.tag_configure("ok",      foreground=C_GREEN)

        self._printer_rows = []      # list of candidate dicts
        self._win_printers = []      # list of Windows printer dicts

    # ---- printer scan control ----

    def _start_printer_scan(self):
        if self._p_scanning:
            return
        subnet = self.var_p_subnet.get().strip()
        if not subnet and self.var_p_sweep.get():
            self._detect_subnet()
            subnet = self.var_subnet.get().strip()
            self.var_p_subnet.set(subnet)
        if self.var_p_sweep.get():
            try:
                ipaddress.IPv4Network(subnet, strict=False)
            except Exception:
                messagebox.showerror(
                    "Invalid subnet",
                    f"'{subnet}' is not a valid subnet.\n"
                    f"Example: 192.168.1.0/24")
                return
        if not (self.var_p_mdns.get() or self.var_p_sweep.get()):
            messagebox.showwarning(
                "Nothing to do",
                "Enable at least one of 'mDNS / Bonjour' or 'Port sweep'.")
            return

        self._clear_printers()
        self._p_scanning = True
        self._btn_pscan.configure(state="disabled")
        self._btn_pstop.configure(state="normal")
        self._lbl_p_progress.configure(text="Searching …")

        self._p_engine = PrinterScanEngine(
            result_cb   = lambda c: self.root.after(0, self._on_printer_found, c),
            progress_cb = lambda d, t: self.root.after(
                              0, self._on_p_progress, d, t),
            done_cb     = lambda: self.root.after(0, self._on_printer_done),
            log_cb      = Logger.log,
        )
        try:
            threads = int(self.var_threads.get() or 128)
        except Exception:
            threads = 128
        self._p_engine.start(subnet,
                             self.var_p_mdns.get(),
                             self.var_p_sweep.get(),
                             self.var_p_snmp.get(),
                             threads)

    def _stop_printer_scan(self):
        if self._p_engine:
            self._p_engine.stop()
        self._lbl_p_progress.configure(text="Stopping …")

    def _on_p_progress(self, done: int, total: int):
        pct = (done / total * 100) if total else 0
        self._p_progress_var.set(pct)
        self._lbl_p_progress.configure(text=f"{done} / {total}   ({pct:.0f} %)")

    def _on_printer_found(self, c: dict):
        self._printer_rows.append(c)
        via = ", ".join(sorted(c.get("sources", set())))
        if c.get("mdns_services"):
            via += "  [" + ",".join(c["mdns_services"]) + "]"
        ports = "  ".join(
            f"{p}/{PRINTER_PORTS.get(p, '')}".rstrip("/")
            for p in sorted(c.get("ports", [])))
        conf = c.get("confidence", "Maybe")
        tag  = {"Certain": "certain", "Likely": "likely"}.get(conf, "maybe")
        self._ptree.insert("", "end", values=(
            c["ip"], conf, c.get("model", ""), c.get("name", ""),
            c.get("vendor", ""), ports, via), tags=(tag,))

    def _on_printer_done(self):
        self._p_scanning = False
        self._btn_pscan.configure(state="normal")
        self._btn_pstop.configure(state="disabled")
        self._p_progress_var.set(100)
        n = len(self._printer_rows)
        self._lbl_p_progress.configure(text=f"Done – {n} candidate(s)")
        if n == 0:
            self._lbl_p_progress.configure(text="Done – nothing found")

    def _clear_printers(self):
        for i in self._ptree.get_children():
            self._ptree.delete(i)
        self._printer_rows = []
        self._p_progress_var.set(0)
        self._lbl_p_progress.configure(text="Ready")

    # ---- Windows installed printers ----

    def _refresh_win_printers(self):
        for i in self._wtree.get_children():
            self._wtree.delete(i)
        Logger.log("Reading installed Windows printers …", "INFO")

        def _run():
            data = get_windows_printers()
            self.root.after(0, self._fill_win_printers, data)

        threading.Thread(target=_run, daemon=True).start()

    def _fill_win_printers(self, data: list):
        self._win_printers = data
        for p in data:
            st  = (p.get("status") or "").lower()
            tag = "offline" if ("offline" in st or "error" in st) else "ok"
            self._wtree.insert("", "end", values=(
                p.get("name", ""), p.get("address", ""), p.get("port", ""),
                p.get("driver", ""), p.get("status", ""),
                p.get("shared", "")), tags=(tag,))
        Logger.log(f"{len(data)} installed printer(s) found.", "INFO")

    def _open_add_printer(self):
        try:
            subprocess.Popen(
                ["rundll32.exe", "printui.dll,PrintUIEntry", "/il"])
        except Exception as e:
            messagebox.showerror("Add printer", f"Could not open wizard:\n{e}")

    def _open_printer_folder(self):
        try:
            subprocess.Popen(["control", "printers"], shell=True)
        except Exception as e:
            messagebox.showerror("Printers", f"Could not open folder:\n{e}")

    def _install_printer_port(self, ip: str):
        """Open the Add-Printer wizard pre-pointed at this TCP/IP address."""
        if not messagebox.askyesno(
                "Install printer",
                f"Create a standard TCP/IP printer port for {ip} and open the "
                f"Add Printer wizard?\n\n"
                f"You will still choose the driver yourself."):
            return

        def _run():
            ps = (f"$ErrorActionPreference='Stop';"
                  f"if (-not (Get-PrinterPort -Name 'IP_{ip}' "
                  f"-ErrorAction SilentlyContinue)) {{ "
                  f"Add-PrinterPort -Name 'IP_{ip}' -PrinterHostAddress '{ip}' }}")
            try:
                subprocess.run(
                    ["powershell", "-NoProfile", "-Command", ps],
                    capture_output=True, text=True, timeout=45,
                    creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
                Logger.log(f"TCP/IP printer port IP_{ip} ready.", "INFO")
            except Exception as e:
                Logger.log(f"Could not create printer port: {e}", "ERROR")
            self.root.after(0, self._open_add_printer)

        threading.Thread(target=_run, daemon=True).start()

    # ---- printer tree interaction ----

    def _ptree_dclick(self, _event):
        sel = self._ptree.selection()
        if sel:
            ip = self._ptree.item(sel[0], "values")[0]
            webbrowser.open(f"http://{ip}")

    def _ptree_rclick(self, event):
        row = self._ptree.identify_row(event.y)
        if not row:
            return
        self._ptree.selection_set(row)
        vals = self._ptree.item(row, "values")
        ip = vals[0]
        menu = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                       activebackground=C_TREE_SEL, font=FONT_SMALL)
        menu.add_command(label=f"Open web UI  (http://{ip})",
                         command=lambda: webbrowser.open(f"http://{ip}"))
        menu.add_command(label=f"Open web UI  (https://{ip})",
                         command=lambda: webbrowser.open(f"https://{ip}"))
        menu.add_separator()
        menu.add_command(label="🖨  Install this printer in Windows …",
                         command=lambda: self._install_printer_port(ip))
        menu.add_command(label="🔁  Point an installed printer at this IP …",
                         command=lambda: self._repoint_printer_dialog(ip))
        menu.add_separator()
        menu.add_command(label=f"Copy IP  ({ip})",
                         command=lambda: self._clip(ip))
        menu.add_command(label="Copy entire row",
                         command=lambda: self._clip(
                             "\t".join(str(v) for v in vals)))
        menu.add_command(label="Show full SNMP details …",
                         command=lambda: self._snmp_details(ip))
        menu.add_separator()
        menu.add_command(label="ping -t  (continuous)",
                         command=lambda: subprocess.Popen(
                             ["cmd", "/k", f"ping -t {ip}"],
                             creationflags=subprocess.CREATE_NEW_CONSOLE))
        try:
            menu.tk_popup(event.x_root, event.y_root)
        finally:
            menu.grab_release()

    def _wtree_rclick(self, event):
        row = self._wtree.identify_row(event.y)
        if not row:
            return
        self._wtree.selection_set(row)
        vals = self._wtree.item(row, "values")
        name, addr = vals[0], vals[1]
        menu = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                       activebackground=C_TREE_SEL, font=FONT_SMALL)
        if addr:
            menu.add_command(label=f"Open web UI  (http://{addr})",
                             command=lambda: webbrowser.open(f"http://{addr}"))
            menu.add_command(label=f"ping {addr}",
                             command=lambda: subprocess.Popen(
                                 ["cmd", "/k", f"ping -t {addr}"],
                                 creationflags=subprocess.CREATE_NEW_CONSOLE))
            menu.add_separator()
        menu.add_command(label="Open print queue",
                         command=lambda: subprocess.Popen(
                             ["rundll32.exe", "printui.dll,PrintUIEntry",
                              "/o", "/n", name]))
        menu.add_command(label="Printer properties",
                         command=lambda: subprocess.Popen(
                             ["rundll32.exe", "printui.dll,PrintUIEntry",
                              "/p", "/n", name]))
        menu.add_separator()
        menu.add_command(label="Copy printer name",
                         command=lambda: self._clip(name))
        menu.add_command(label="Copy entire row",
                         command=lambda: self._clip(
                             "\t".join(str(v) for v in vals)))
        try:
            menu.tk_popup(event.x_root, event.y_root)
        finally:
            menu.grab_release()

    def _repoint_printer_dialog(self, ip: str):
        """
        Re-point an already-installed Windows printer at a new IP address.
        This is the usual repair when a printer 'disappears': the driver is
        still installed, but its port points at an address the printer no
        longer has (DHCP gave it a different one, or the port uses a host
        name that no longer resolves).
        """
        printers = self._win_printers or get_windows_printers()
        self._win_printers = printers
        if not printers:
            messagebox.showinfo(
                "No printers",
                "Windows has no installed printers to re-point.\n\n"
                "Use 'Install this printer in Windows' instead.")
            return

        top = tk.Toplevel(self.root)
        top.title("Re-point printer")
        top.configure(bg=C_BG3)
        top.geometry("620x420")
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text=f"Point an installed printer at  {ip}",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_TITLE).pack(pady=(12, 4))
        tk.Label(top,
                 text="Choose the printer whose port should now point at this "
                      "address.\nThe driver stays exactly as it is – only the "
                      "port changes.",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL,
                 justify="center").pack(pady=(0, 10))

        lf = tk.Frame(top, bg=C_BG3)
        lf.pack(fill="both", expand=True, padx=14)
        lb = tk.Listbox(lf, bg=C_BG, fg=C_FG, font=FONT_MAIN,
                        selectbackground=C_TREE_SEL, relief="flat",
                        activestyle="none", highlightthickness=0)
        sb = ttk.Scrollbar(lf, orient="vertical", command=lb.yview)
        lb.configure(yscrollcommand=sb.set)
        lb.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        lb.bind("<MouseWheel>",
                lambda e: lb.yview_scroll(-1 * (e.delta // 120), "units"))

        for p in printers:
            cur = p.get("address") or p.get("port") or "?"
            lb.insert("end", f"{p.get('name','')}   →   {cur}")
        if printers:
            lb.selection_set(0)

        status = tk.Label(top, text="", bg=C_BG3, fg=C_YELLOW,
                          font=FONT_SMALL)
        status.pack(pady=(6, 0))

        def _do_repoint(_e=None):
            sel = lb.curselection()
            if not sel:
                status.configure(text="Select a printer first.", fg=C_YELLOW)
                return
            printer = printers[sel[0]]["name"]
            if not messagebox.askyesno(
                    "Re-point printer",
                    f"Point '{printer}' at {ip}?\n\n"
                    f"This needs administrator rights.",
                    parent=top):
                return
            status.configure(text="Working …", fg=C_YELLOW)
            btn.configure(state="disabled")

            def _run():
                port = f"IP_{ip}"
                ps = (
                    f"$ErrorActionPreference='Stop';"
                    f"if (-not (Get-PrinterPort -Name '{port}' "
                    f"-ErrorAction SilentlyContinue)) {{ "
                    f"Add-PrinterPort -Name '{port}' "
                    f"-PrinterHostAddress '{ip}' }};"
                    f"Set-Printer -Name '{printer}' -PortName '{port}';"
                    f"'OK'"
                )
                try:
                    res = subprocess.run(
                        ["powershell", "-NoProfile", "-NonInteractive",
                         "-Command", ps],
                        capture_output=True, text=True, timeout=60,
                        creationflags=getattr(
                            subprocess, "CREATE_NO_WINDOW", 0))
                    ok  = "OK" in (res.stdout or "")
                    err = (res.stderr or "").strip().splitlines()
                    msg = err[0] if err else "Unknown error"
                except Exception as e:
                    ok, msg = False, str(e)
                self.root.after(0, _finish, ok, msg, printer, port)

            threading.Thread(target=_run, daemon=True).start()

        def _finish(ok, msg, printer, port):
            btn.configure(state="normal")
            if ok:
                Logger.log(f"Printer '{printer}' re-pointed to {port}.", "INFO")
                top.destroy()
                self._flash_ok("Printer re-pointed")
                self._refresh_win_printers()
            else:
                status.configure(text=msg[:110], fg=C_RED)
                Logger.log(f"Re-point failed: {msg}", "ERROR")
                if "denied" in msg.lower() or "access" in msg.lower():
                    messagebox.showwarning(
                        "Administrator rights needed",
                        "Windows refused the change.\n\n"
                        "Close NetRadar and start it again with "
                        "'Run as administrator', then try once more.",
                        parent=top)

        br = tk.Frame(top, bg=C_BG3)
        br.pack(pady=12)
        btn = self._btn(br, "Re-point printer", _do_repoint,
                        bg=C_BTN_FIX, fg="white", width=18)
        btn.pack(side="left", padx=4)
        self._btn(br, "Cancel", top.destroy,
                  bg=C_BTN_NORM, fg=C_FG, width=10).pack(side="left", padx=4)
        lb.bind("<Double-1>", _do_repoint)
        lb.bind("<Return>",   _do_repoint)
        lb.focus_set()

    def _snmp_details(self, ip: str):
        """Query a handful of standard OIDs and show them in a dialog."""
        top = tk.Toplevel(self.root)
        top.title(f"SNMP details – {ip}")
        top.configure(bg=C_BG3)
        top.geometry("760x420")
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _e: top.destroy())

        tk.Label(top, text=f"SNMP query – {ip}", bg=C_BG3, fg=C_ACCENT,
                 font=FONT_TITLE).pack(pady=(10, 6))

        frame = tk.Frame(top, bg=C_BG3)
        frame.pack(fill="both", expand=True, padx=10, pady=(0, 8))
        txt = tk.Text(frame, bg=C_BG, fg=C_FG, font=FONT_MONO,
                      relief="flat", wrap="word",
                      insertofftime=0, insertontime=9999999)
        sb = ttk.Scrollbar(frame, orient="vertical", command=txt.yview)
        txt.configure(yscrollcommand=sb.set)
        txt.pack(side="left", fill="both", expand=True)
        sb.pack(side="right", fill="y")
        txt.bind("<MouseWheel>",
                 lambda e: txt.yview_scroll(-1 * (e.delta // 120), "units"))
        txt.insert("end", "Querying …\n")

        self._btn(top, "Close", top.destroy,
                  bg=C_BTN_NORM, fg=C_FG, width=10).pack(pady=(0, 10))

        oids = [
            ("System description", "1.3.6.1.2.1.1.1.0"),
            ("System name",        "1.3.6.1.2.1.1.5.0"),
            ("Location",           "1.3.6.1.2.1.1.6.0"),
            ("Contact",            "1.3.6.1.2.1.1.7.0"),
            ("Uptime (ticks)",     "1.3.6.1.2.1.1.3.0"),
            ("Device description", "1.3.6.1.2.1.25.3.2.1.3.1"),
            ("Printer name",       "1.3.6.1.2.1.43.5.1.1.16.1"),
            ("Serial number",      "1.3.6.1.2.1.43.5.1.1.17.1"),
            ("Page count",         "1.3.6.1.2.1.43.10.2.1.4.1.1"),
            ("Console message",    "1.3.6.1.2.1.43.16.5.1.2.1.1"),
        ]

        def _run():
            lines = []
            for label, oid in oids:
                val = snmp_get(ip, oid, timeout=1.2)
                lines.append(f"{label:<22} {val or '—'}")
            lines.append("")
            lines.append("(An empty value means the printer does not expose "
                         "that OID, or SNMP is disabled on it.)")
            self.root.after(0, _fill, "\n".join(lines))

        def _fill(text):
            try:
                txt.delete("1.0", "end")
                txt.insert("end", text)
            except Exception:
                pass

        threading.Thread(target=_run, daemon=True).start()

    def _export_printers_csv(self):
        if not self._printer_rows and not self._win_printers:
            messagebox.showinfo("Export", "Nothing to export yet.")
            return
        path = LOG_DIR / f"printers_{datetime.now():%Y%m%d_%H%M%S}.csv"
        try:
            with open(path, "w", newline="", encoding="utf-8-sig") as f:
                w = csv.writer(f, delimiter=";")
                w.writerow(["--- Found on network ---"])
                w.writerow(["IP", "Confidence", "Model", "Name",
                            "Vendor", "Ports", "Found via", "MAC"])
                for c in self._printer_rows:
                    w.writerow([
                        c["ip"], c.get("confidence", ""), c.get("model", ""),
                        c.get("name", ""), c.get("vendor", ""),
                        " ".join(str(p) for p in sorted(c.get("ports", []))),
                        " ".join(sorted(c.get("sources", set()))),
                        c.get("mac", "")])
                w.writerow([])
                w.writerow(["--- Installed in Windows ---"])
                w.writerow(["Name", "Address", "Port", "Driver",
                            "Status", "Shared"])
                for p in self._win_printers:
                    w.writerow([p.get("name", ""), p.get("address", ""),
                                p.get("port", ""), p.get("driver", ""),
                                p.get("status", ""), p.get("shared", "")])
            Logger.log(f"Printers exported to {path}", "INFO")
            self._flash_ok("Printer list exported")
        except Exception as e:
            messagebox.showerror("Export failed", str(e))

    # ------------------------------------------------------------------ #
    #  ARP CACHE TAB                                                       #
    # ------------------------------------------------------------------ #

    def _build_arp_tab(self):
        tab = self._tab_arp
        ctrl = tk.Frame(tab, bg=C_BG2)
        ctrl.pack(fill="x", padx=8, pady=8)

        self._btn(ctrl, "↻  Refresh ARP Cache", self._refresh_arp,
                  bg=C_BTN_SCAN, fg="white").pack(side="left")
        self._btn(ctrl, "Copy All", self._copy_arp,
                  bg=C_BTN_COPY, fg=C_FG).pack(side="left", padx=6)
        tk.Label(ctrl,
                 text="Shows all entries currently in your ARP cache — instant, no scan needed.",
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(side="left", padx=10)

        frame = tk.Frame(tab, bg=C_BG2)
        frame.pack(fill="both", expand=True, padx=8, pady=(0, 6))

        cols = ("ip", "mac", "type", "interface")
        self._arp_tree = ttk.Treeview(frame, columns=cols, show="headings")
        for c, h, w in [("ip", "IP Address", 155), ("mac", "MAC Address", 175),
                        ("type", "Type", 110), ("interface", "Interface", 450)]:
            self._arp_tree.heading(c, text=h, anchor="w")
            self._arp_tree.column(c, width=w, anchor="w")

        vsb2 = ttk.Scrollbar(frame, orient="vertical",   command=self._arp_tree.yview)
        hsb2 = ttk.Scrollbar(frame, orient="horizontal", command=self._arp_tree.xview)
        self._arp_tree.configure(yscrollcommand=vsb2.set, xscrollcommand=hsb2.set)
        self._arp_tree.grid(row=0, column=0, sticky="nsew")
        vsb2.grid(row=0, column=1, sticky="ns")
        hsb2.grid(row=1, column=0, sticky="ew")
        frame.rowconfigure(0, weight=1)
        frame.columnconfigure(0, weight=1)

        self._arp_tree.bind("<MouseWheel>",
            lambda e: self._arp_tree.yview_scroll(-1*(e.delta//120), "units"))

    # ------------------------------------------------------------------ #
    #  WINDOWS FIX TAB                                                     #
    # ------------------------------------------------------------------ #

    def _build_fix_tab(self):
        tab = self._tab_fix

        # Header row
        hdr = tk.Frame(tab, bg=C_BG3, pady=8)
        hdr.pack(fill="x")
        tk.Label(hdr, text="⚒  Windows 11 Network Visibility Fixes",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_TITLE).pack(
            side="left", padx=14)
        self._lbl_admin = tk.Label(hdr, text="", bg=C_BG3, font=FONT_SMALL)
        self._lbl_admin.pack(side="right", padx=14)
        self._update_admin_label()

        tk.Label(
            tab,
            text=("Apply these fixes on BOTH Windows 11 machines to make them see each other.\n"
                  "Administrator rights are required. A UAC prompt will appear if needed."),
            bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
            justify="left", wraplength=900,
        ).pack(anchor="w", padx=14, pady=(6, 4))

        # Bottom action strip (packed before canvas so it stays visible)
        bot = tk.Frame(tab, bg=C_BG2)
        bot.pack(side="bottom", fill="x", padx=8, pady=6)
        self._btn(bot, "▶  Apply ALL recommended fixes",
                  self._apply_all_fixes,
                  bg=C_BTN_SCAN, fg="white", padx=20).pack(side="left")
        tk.Label(bot,
                 text="Recommended: " + ", ".join(sorted(RECOMMENDED_FIXES)),
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(
            side="left", padx=12)

        # Scrollable fix cards
        canvas = tk.Canvas(tab, bg=C_BG2, highlightthickness=0)
        scrl   = ttk.Scrollbar(tab, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=scrl.set)
        scrl.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True, padx=(8, 0), pady=4)

        inner    = tk.Frame(canvas, bg=C_BG2)
        inner_id = canvas.create_window((0, 0), window=inner, anchor="nw")

        def _on_inner_conf(_e):
            canvas.configure(scrollregion=canvas.bbox("all"))

        def _on_canvas_conf(e):
            canvas.itemconfig(inner_id, width=e.width)

        inner.bind("<Configure>", _on_inner_conf)
        canvas.bind("<Configure>", _on_canvas_conf)
        canvas.bind("<MouseWheel>",
            lambda e: canvas.yview_scroll(-1*(e.delta//120), "units"))

        for fix in FIXES:
            is_rec = fix["id"] in RECOMMENDED_FIXES
            row_bg = C_FRAME if not is_rec else "#1a2a1a"

            card = tk.Frame(inner, bg=row_bg, padx=10, pady=6)
            card.pack(fill="x", padx=6, pady=3)

            left = tk.Frame(card, bg=row_bg)
            left.pack(side="left", fill="both", expand=True)

            lbl_text = ("★ " if is_rec else "   ") + fix["label"]
            tk.Label(left, text=lbl_text, bg=row_bg, fg=C_FG_BRIGHT,
                     font=FONT_BOLD, anchor="w").pack(anchor="w")
            tk.Label(left, text=fix["desc"], bg=row_bg, fg=C_FG_DIM,
                     font=FONT_SMALL, anchor="w",
                     wraplength=700).pack(anchor="w")

            cmd_short = fix["cmd"]
            if len(cmd_short) > 110:
                cmd_short = cmd_short[:110] + "…"
            tk.Label(left, text="CMD: " + cmd_short,
                     bg=row_bg, fg="#4a7fb5",
                     font=FONT_MONO, anchor="w").pack(anchor="w")

            right = tk.Frame(card, bg=row_bg)
            right.pack(side="right", padx=(12, 0))

            st_lbl = tk.Label(right, text="", bg=row_bg, font=FONT_SMALL,
                              width=30, anchor="e")
            st_lbl.pack(anchor="e", pady=(0, 4))
            self._fix_status[fix["id"]] = st_lbl

            apply_btn = self._btn(right, "Apply",
                                  lambda f=fix: self._apply_fix(f),
                                  bg=C_BTN_FIX, fg="white", width=10)
            apply_btn.pack(anchor="e")
            self._fix_btns[fix["id"]] = apply_btn

    def _update_admin_label(self):
        if is_admin():
            self._lbl_admin.configure(
                text="✔  Running as Administrator", fg=C_GREEN)
        else:
            self._lbl_admin.configure(
                text="⚠  Not Administrator – UAC prompt will appear for each fix",
                fg=C_YELLOW)

    # ------------------------------------------------------------------ #
    #  FAVORITES TAB                                                       #
    # ------------------------------------------------------------------ #

    def _build_favorites_tab(self):
        tab = self._tab_fav

        # ── Header ────────────────────────────────────────────────────
        hdr = tk.Frame(tab, bg=C_BG3, pady=8)
        hdr.pack(fill="x")
        tk.Label(hdr, text="★  Saved Network Drive Favorites",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_TITLE).pack(
            side="left", padx=14)

        right_hdr = tk.Frame(hdr, bg=C_BG3)
        right_hdr.pack(side="right", padx=10)
        self._btn(right_hdr, "⚡  Activate All",
                  self._activate_all_favorites,
                  bg=C_BTN_SCAN, fg="white", padx=16).pack(side="right", padx=4)
        self._btn(right_hdr, "＋  Add New Favorite",
                  self._add_favorite_dialog,
                  bg=C_BTN_FIX, fg="white", padx=14).pack(side="right", padx=4)

        tk.Label(
            tab,
            text=("Click a favorite to connect it instantly — no scanning needed.\n"
                  "Favorites (with their login) survive Windows restarts and a reinstall - "
                  "they are stored in  Helpfiles/0---Settings/netradar_favorites.json"),
            bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL,
            justify="left", wraplength=900,
        ).pack(anchor="w", padx=14, pady=(6, 2))
        ttk.Checkbutton(
            tab, text="Reconnect all favorites automatically when NetRadar starts",
            variable=self.var_auto, command=self._toggle_auto_connect,
        ).pack(anchor="w", padx=14, pady=(0, 4))

        tk.Frame(tab, bg=C_SEP, height=1).pack(fill="x", padx=8)

        # ── Scrollable cards area ──────────────────────────────────────
        canvas = tk.Canvas(tab, bg=C_BG2, highlightthickness=0)
        scrl   = ttk.Scrollbar(tab, orient="vertical", command=canvas.yview)
        canvas.configure(yscrollcommand=scrl.set)
        scrl.pack(side="right", fill="y")
        canvas.pack(side="left", fill="both", expand=True, padx=(8, 0), pady=4)

        self._fav_inner    = tk.Frame(canvas, bg=C_BG2)
        self._fav_inner_id = canvas.create_window(
            (0, 0), window=self._fav_inner, anchor="nw")

        def _on_inner_conf(_e):
            canvas.configure(scrollregion=canvas.bbox("all"))

        def _on_canvas_conf(e):
            canvas.itemconfig(self._fav_inner_id, width=e.width)

        self._fav_inner.bind("<Configure>", _on_inner_conf)
        canvas.bind("<Configure>", _on_canvas_conf)
        canvas.bind("<MouseWheel>",
            lambda e: canvas.yview_scroll(-1*(e.delta//120), "units"))
        self._fav_canvas = canvas

        self._fav_empty_lbl = tk.Label(
            self._fav_inner,
            text=("No favorites yet.\n\n"
                  "Add one with  ＋ Add New Favorite,\n"
                  "or right-click any host in the Scanner and choose\n"
                  "🖧  Map network drive … → Save as Favorite."),
            bg=C_BG2, fg=C_FG_DIM, font=FONT_MAIN,
            justify="center",
        )

        self._fav_cards: dict = {}   # name → frame (for refresh)
        self._render_favorites()

    def _render_favorites(self):
        """Rebuild the favorites card list from self._favorites."""
        for w in self._fav_inner.winfo_children():
            w.destroy()
        self._fav_cards.clear()

        if not self._favorites:
            self._fav_empty_lbl = tk.Label(
                self._fav_inner,
                text=("No favorites yet.\n\n"
                      "Add one with  ＋ Add New Favorite,\n"
                      "or right-click any host in the Scanner and choose\n"
                      "🖧  Map network drive … → Save as Favorite."),
                bg=C_BG2, fg=C_FG_DIM, font=FONT_MAIN,
                justify="center",
            )
            self._fav_empty_lbl.pack(pady=50)
            return

        for idx, fav in enumerate(self._favorites):
            self._render_fav_card(idx, fav)

    def _render_fav_card(self, idx: int, fav: dict):
        card_bg = C_FRAME
        card = tk.Frame(self._fav_inner, bg=card_bg, padx=12, pady=8,
                        relief="flat")
        card.pack(fill="x", padx=8, pady=3)

        # Left: info
        left = tk.Frame(card, bg=card_bg)
        left.pack(side="left", fill="both", expand=True)

        name_row = tk.Frame(left, bg=card_bg)
        name_row.pack(anchor="w")
        tk.Label(name_row, text="★ ", bg=card_bg, fg=C_YELLOW,
                 font=FONT_BOLD).pack(side="left")
        tk.Label(name_row, text=fav.get("name", "(unnamed)"),
                 bg=card_bg, fg=C_FG_BRIGHT, font=FONT_BOLD).pack(side="left")

        letter = fav.get("letter", "?:")
        path   = fav.get("path", "")
        user   = fav.get("user", "")
        detail = f"{letter}  →  {path}"
        if user:
            detail += f"   (user: {user})"
        tk.Label(left, text=detail,
                 bg=card_bg, fg=C_FG_DIM, font=FONT_SMALL).pack(anchor="w")

        # Status label (updated on connect)
        st_lbl = tk.Label(left, text="", bg=card_bg, font=FONT_SMALL,
                          fg=C_FG_DIM)
        st_lbl.pack(anchor="w")

        # Right: buttons
        right = tk.Frame(card, bg=card_bg)
        right.pack(side="right", padx=(10, 0))

        self._btn(right, "▶  Connect",
                  lambda f=fav, s=st_lbl: self._connect_favorite(f, s),
                  bg=C_BTN_SCAN, fg="white", width=12).pack(pady=2)
        self._btn(right, "✎  Edit",
                  lambda i=idx: self._edit_favorite_dialog(i),
                  bg=C_BTN_FIX, fg="white", width=12).pack(pady=2)
        self._btn(right, "✖  Delete",
                  lambda i=idx: self._delete_favorite(i),
                  bg=C_BTN_STOP, fg="white", width=12).pack(pady=2)

        self._fav_cards[fav.get("name", str(idx))] = (card, st_lbl)

    def _set_status(self, st_lbl, msg: str, col: str):
        """Set a favorite card's status label (safe if the card was re-drawn)."""
        try:
            if st_lbl is not None and st_lbl.winfo_exists():
                st_lbl.configure(text=msg, fg=col)
        except Exception:
            pass

    def _resolve_fav_login(self, fav: dict) -> tuple:
        """(user, password) of this favorite, or the login saved on another favorite
        of the same PC - one login serves all of that PC's drives."""
        user = fav.get("user", "").strip()
        pw   = _fav_decode_pw(fav.get("_pw", ""))
        if not user:
            user, pw = host_login(self._favorites, unc_host(fav.get("path", "")))
        return user, pw

    def _connect_worker(self, fav: dict, st_lbl, interactive: bool):
        """Connect ONE favorite (runs in a background thread)."""
        letter = fav.get("letter", "").strip()
        path   = fav.get("path", "").strip()
        host   = unc_host(path)
        user, pw = self._resolve_fav_login(fav)

        def say(msg, col):
            self.root.after(0, lambda: self._set_status(st_lbl, msg, col))

        if not letter or not path:
            say("⚠  Missing drive letter or path", C_YELLOW)
            return
        say("Connecting …", C_FG_DIM)

        if host and not smb_reachable(host):
            say("✘  PC not reachable - switched off, or another network?", C_RED)
            Logger.log(f"Favorite connect: {host} not reachable ({letter})", "WARN")
            return

        # Already there? Then leave it alone.
        mapped = dict(get_drive_info()[1])
        if (mapped.get(letter, "").lower() == path.lower()
                and os.path.isdir(letter + "\\")):
            say(f"✔  {letter} already connected", C_GREEN)
            return

        rc, out, code = 1, "", 0
        for attempt in (1, 2):
            run_tool(NET_EXE, ["use", letter, "/delete", "/y"])   # stale mapping
            args = ["use", letter, path, "/persistent:yes"]
            if user:
                args.append(f"/user:{user}")
                if pw:
                    args.append(pw)
            rc, out = run_tool(NET_EXE, args, timeout=45)
            if rc == 0:
                break
            code = net_error_code(out)
            if code == 1219 and host and attempt == 1:
                # Another login is already open to this PC: clear it, try once more.
                run_tool(NET_EXE, ["use", f"\\\\{host}\\IPC$", "/delete", "/y"])
                continue
            break

        if rc == 0:
            say(f"✔  {letter} connected", C_GREEN)
            Logger.log(f"Favorite connect: {letter} → {path}  OK", "INFO")
            if user and host and host not in self._cmdkey_done:
                self._cmdkey_done.add(host)
                remember_login(host, "", user, pw)    # Explorer stops asking too
            return

        Logger.log(f"Favorite connect: {letter} → {path}  FAIL  {out[:100]}", "WARN")
        if not user and code not in (53, 67, 85):
            say("🔑  Login needed for this PC", C_YELLOW)
            if interactive and host:
                self.root.after(0, lambda: self._ask_login(host))
            return
        hint = net_error_hint(code)
        say(f"✘  {hint or out or 'failed'}", C_RED)

    def _connect_many(self, favs: list, interactive: bool = True):
        """Connect several favorites one after the other in ONE background thread
        (two logins to the same PC at the same moment can clash)."""
        def _run():
            for fav in favs:
                key = fav.get("name", "")
                st  = self._fav_cards.get(key, (None, None))[1]
                try:
                    self._connect_worker(fav, st, interactive)
                except Exception as exc:
                    Logger.log(f"Favorite connect crashed: {exc}", "ERROR")
        threading.Thread(target=_run, daemon=True).start()

    def _connect_favorite(self, fav: dict, st_lbl: tk.Label = None):
        """Connect one favorite; update its status label."""
        def _run():
            try:
                self._connect_worker(fav, st_lbl, True)
            except Exception as exc:
                Logger.log(f"Favorite connect crashed: {exc}", "ERROR")
        threading.Thread(target=_run, daemon=True).start()

    def _activate_all_favorites(self):
        """Connect all favorites one after the other in the background."""
        if not self._favorites:
            messagebox.showinfo("Favorites", "No favorites saved yet.")
            return
        # Rebuild cards first so status labels exist
        self._render_favorites()
        self._connect_many(list(self._favorites), interactive=True)

    def _auto_connect_favorites(self):
        """At start: bring every saved drive back, silently (no login pop-ups)."""
        if not self._favorites:
            return
        self._render_favorites()
        Logger.log(f"Auto-connecting {len(self._favorites)} favorite drive(s) ...", "INFO")
        self._connect_many(list(self._favorites), interactive=False)

    def _toggle_auto_connect(self):
        self.cfg["auto_connect"] = bool(self.var_auto.get())
        save_settings(self.cfg)

    # ------------------------------------------------------------------ #
    #  LOGIN ONCE PER PC                                                   #
    # ------------------------------------------------------------------ #

    def _try_login(self, host: str, user: str, pw: str, cname: str) -> tuple:
        """Log in on the PC: 'NAME\\user' first, then the bare name.
        Returns (ok, user_that_worked, error_code, output)."""
        cands = [qualify_user(user, cname)]
        if user.strip() and user.strip() != cands[0]:
            cands.append(user.strip())
        last = (False, user, 0, "")
        for u in cands:
            ok, code, out = smb_login(host, u, pw)
            if ok:
                return True, u, 0, out
            last = (False, u, code, out)
        return last

    def _store_host_login(self, host: str, cname: str, user: str, pw: str):
        """Put the login on every favorite of this PC + Windows' credential store."""
        for f in self._favorites:
            if unc_host(f.get("path", "")) == host:
                f["user"] = user
                f["_pw"]  = _fav_encode_pw(pw)
        save_favorites(self._favorites)
        remember_login(host, cname, user, pw)
        self._cmdkey_done.add(host)

    def _ask_login(self, host: str):
        """Small dialog: the PC's Windows login, asked ONCE, used for all its drives."""
        if host in self._asking_login:
            return
        self._asking_login.add(host)

        dlg = tk.Toplevel(self.root)
        dlg.title("Login needed")
        dlg.configure(bg=C_BG3)
        dlg.transient(self.root)
        dlg.grab_set()
        dlg.focus_force()
        dlg.resizable(False, False)

        def _close(_e=None):
            self._asking_login.discard(host)
            dlg.destroy()
        dlg.bind("<Escape>", _close)
        dlg.protocol("WM_DELETE_WINDOW", _close)

        tk.Frame(dlg, bg=C_YELLOW, height=3).pack(fill="x")
        tk.Label(dlg, text=f"  🔑  Login for  {host}", bg=C_BG3, fg=C_YELLOW,
                 font=FONT_HEADER, anchor="w").pack(fill="x", padx=14, pady=(10, 2))
        tk.Label(dlg, text=("  Type the Windows login of THAT PC once.\n"
                            "  It is saved for all its drives and for File Explorer."),
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL, anchor="w",
                 justify="left").pack(fill="x", padx=14, pady=(0, 8))
        body = tk.Frame(dlg, bg=C_BG3, padx=18, pady=6)
        body.pack(fill="x")
        tk.Label(body, text="User name:", bg=C_BG3, fg=C_FG, font=FONT_SMALL,
                 width=12, anchor="w").grid(row=0, column=0, pady=4)
        var_u = tk.StringVar()
        e_u = self._entry(body, textvariable=var_u, width=28)
        e_u.grid(row=0, column=1, padx=(6, 0))
        tk.Label(body, text="Password:", bg=C_BG3, fg=C_FG, font=FONT_SMALL,
                 width=12, anchor="w").grid(row=1, column=0, pady=4)
        var_p = tk.StringVar()
        e_p = self._entry(body, textvariable=var_p, width=28, show="●")
        e_p.grid(row=1, column=1, padx=(6, 0))
        var_show = tk.BooleanVar(value=False)
        ttk.Checkbutton(body, text="Show password", variable=var_show,
                        command=lambda: e_p.configure(
                            show="" if var_show.get() else "●")).grid(
            row=2, column=1, sticky="w")
        lbl = tk.Label(dlg, text="", bg=C_BG3, font=FONT_SMALL, fg=C_FG_DIM,
                       wraplength=420, justify="left", anchor="nw", height=3)
        lbl.pack(fill="x", padx=14, pady=(4, 0))

        def _ok(_e=None):
            user, pw = var_u.get().strip(), var_p.get()
            if not user or not pw:
                lbl.configure(text="⚠  Fill in user name and password.", fg=C_YELLOW)
                return
            lbl.configure(text="Checking the login …", fg=C_FG_DIM)

            def _work():
                cname = get_netbios_name(host) or ""
                ok, u, code, out = self._try_login(host, user, pw, cname)
                def _done():
                    if not lbl.winfo_exists():
                        return
                    if ok:
                        self._store_host_login(host, cname, u, pw)
                        _close()
                        self._render_favorites()
                        self._connect_many(
                            [f for f in self._favorites
                             if unc_host(f.get("path", "")) == host], False)
                    else:
                        lbl.configure(text="✘  " + (net_error_hint(code) or out
                                                    or "Login failed."), fg=C_RED)
                self.root.after(0, _done)
            threading.Thread(target=_work, daemon=True).start()

        e_p.bind("<Return>", _ok)
        e_u.bind("<Return>", _ok)
        btn_row = tk.Frame(dlg, bg=C_BG3)
        btn_row.pack(pady=10, padx=14, fill="x")
        self._btn(btn_row, "Save login && connect", _ok, bg=C_BTN_SCAN, fg="white",
                  width=22).pack(side="left")
        self._btn(btn_row, "Cancel", _close, bg=C_BTN_NORM, fg=C_FG,
                  width=10).pack(side="right")
        e_u.focus_set()
        dlg.update_idletasks()
        x = self.root.winfo_x() + self.root.winfo_width()  // 2 - dlg.winfo_width()  // 2
        y = self.root.winfo_y() + self.root.winfo_height() // 2 - dlg.winfo_height() // 2
        dlg.geometry(f"+{x}+{y}")

    def _add_favorite_dialog(self, prefill: dict = None, edit_existing: bool = False):
        """Open dialog to create a new favorite (or edit if prefill given)."""
        dlg = tk.Toplevel(self.root)
        dlg.title("Add Favorite Drive" if not edit_existing else "Edit Favorite Drive")
        dlg.configure(bg=C_BG3)
        dlg.transient(self.root)
        dlg.grab_set()
        dlg.focus_force()
        dlg.resizable(False, False)
        dlg.bind("<Escape>", lambda _e: dlg.destroy())

        tk.Frame(dlg, bg=C_ACCENT, height=3).pack(fill="x")
        tk.Label(dlg,
                 text="  ★  Save Network Drive as Favorite",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_HEADER,
                 anchor="w").pack(fill="x", padx=14, pady=(10, 2))
        tk.Label(dlg,
                 text="  Favorites survive Windows restarts — click once to reconnect.",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL,
                 anchor="w").pack(fill="x", padx=14, pady=(0, 8))
        tk.Frame(dlg, bg=C_SEP, height=1).pack(fill="x", padx=14)

        body = tk.Frame(dlg, bg=C_BG3, padx=18, pady=12)
        body.pack(fill="x")

        def _lbl(row, text):
            tk.Label(body, text=text, bg=C_BG3, fg=C_FG,
                     font=FONT_SMALL, width=16, anchor="w").grid(
                row=row, column=0, sticky="w", pady=4)

        # ── Row 0: Favorite name ──────────────────────────────────────
        _lbl(0, "Favorite name:")
        var_name = tk.StringVar()
        e_name = self._entry(body, textvariable=var_name, width=30)
        e_name.grid(row=0, column=1, sticky="w", padx=(6, 0))
        e_name.delete(0, "end")
        e_name.insert(0, prefill.get("name", "") if prefill else "")

        # ── Row 1: Drive letter (Combobox with free letters) ──────────
        _lbl(1, "Drive letter:")
        import string as _str
        # Build list: currently free letters first, then all D-Z so editing always works
        _avail, _ = get_drive_info()
        _pref_letter = (prefill.get("letter", "") if prefill else "") or (
            _avail[0] if _avail else "Z:")
        # Make sure the preferred letter is in the list even if already mapped
        _all_letters = [f"{c}:" for c in _str.ascii_uppercase[3:]]
        _letter_list  = _avail + [l for l in _all_letters if l not in _avail]
        var_letter = tk.StringVar(value=_pref_letter)
        cb_letter = ttk.Combobox(body, textvariable=var_letter,
                                 values=_letter_list, width=5,
                                 font=FONT_MAIN)
        cb_letter.grid(row=1, column=1, sticky="w", padx=(6, 0))
        cb_letter.set(_pref_letter)      # force visible immediately

        # ── Row 2: Share path + quick-pick buttons ────────────────────
        _lbl(2, "Share path:")
        var_path = tk.StringVar()
        e_path = self._entry(body, textvariable=var_path, width=30)
        e_path.grid(row=2, column=1, sticky="w", padx=(6, 0))
        _init_path = prefill.get("path", "") if prefill else ""
        e_path.delete(0, "end")
        e_path.insert(0, _init_path)

        # Quick-pick row under the path field
        qp_frame = tk.Frame(body, bg=C_BG3)
        qp_frame.grid(row=3, column=1, sticky="w", padx=(6, 0), pady=(0, 4))
        tk.Label(qp_frame, text="Quick:", bg=C_BG3, fg=C_FG_DIM,
                 font=FONT_SMALL).pack(side="left", padx=(0, 4))

        QUICK_SHARES = [
            ("C$",           "C$"),
            ("D$",           "D$"),
            ("Users\\Public","Users\\Public"),
        ]

        def _set_share(share_suffix):
            """Replace share part after \\\\server\\share or just set if path is empty."""
            cur = var_path.get().strip()
            if cur.startswith("\\\\"):
                # Keep \\server\ prefix, replace everything after second backslash pair
                parts = cur.split("\\")
                # parts = ['', '', 'server', 'old_share', ...]
                server = parts[2] if len(parts) > 2 else ""
                new_path = f"\\\\{server}\\{share_suffix}" if server else f"\\\\?\\{share_suffix}"
            else:
                new_path = f"\\\\?\\{share_suffix}"
            e_path.delete(0, "end")
            e_path.insert(0, new_path)

        for btn_lbl, suffix in QUICK_SHARES:
            self._btn(qp_frame, btn_lbl,
                      lambda s=suffix: _set_share(s),
                      bg=C_BTN_COPY, fg=C_ACCENT,
                      padx=6, pady=2).pack(side="left", padx=2)

        # ── Row 4: Username ───────────────────────────────────────────
        _lbl(4, "Username:")
        var_user = tk.StringVar()
        e_user = self._entry(body, textvariable=var_user, width=30)
        e_user.grid(row=4, column=1, sticky="w", padx=(6, 0))
        e_user.delete(0, "end")
        e_user.insert(0, prefill.get("user", "") if prefill else "")

        # ── Row 5: Password ───────────────────────────────────────────
        _lbl(5, "Password:")
        var_pw = tk.StringVar()
        e_pw = self._entry(body, textvariable=var_pw, width=30)
        e_pw.configure(show="●")
        e_pw.grid(row=5, column=1, sticky="w", padx=(6, 0))
        e_pw.delete(0, "end")
        e_pw.insert(0, _fav_decode_pw(prefill.get("_pw", "")) if prefill else "")

        # Show/hide password toggle
        var_show = tk.BooleanVar(value=False)
        def _toggle_show():
            e_pw.configure(show="" if var_show.get() else "●")
        ttk.Checkbutton(body, text="Show password", variable=var_show,
                        command=_toggle_show).grid(
            row=6, column=1, sticky="w", pady=(0, 4))

        # Alias so _save() can read all vars uniformly
        vars_ = {"name": var_name, "letter": var_letter,
                 "path": var_path,  "user": var_user}

        lbl_status = tk.Label(dlg, text="", bg=C_BG3, font=FONT_SMALL,
                              fg=C_FG_DIM, wraplength=400, justify="left")
        lbl_status.pack(padx=14, pady=(4, 0))
        tk.Frame(dlg, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=(6, 0))

        def _save():
            name   = vars_["name"].get().strip()
            letter = vars_["letter"].get().strip().upper()
            path   = vars_["path"].get().strip()
            user   = vars_["user"].get().strip()
            pw     = var_pw.get()

            if not name:
                lbl_status.configure(text="⚠  Enter a favorite name.", fg=C_YELLOW)
                return
            if not letter or len(letter) < 2 or letter[1] != ":":
                lbl_status.configure(text="⚠  Drive letter must be like  Z:", fg=C_YELLOW)
                return
            if not path.startswith("\\\\"):
                lbl_status.configure(
                    text="⚠  Share path must start with  \\\\server\\share",
                    fg=C_YELLOW)
                return
            # Check duplicate name (unless editing the same entry)
            existing_names = [f["name"] for f in self._favorites]
            if not edit_existing and name in existing_names:
                lbl_status.configure(
                    text=f"⚠  A favorite named '{name}' already exists.",
                    fg=C_YELLOW)
                return

            fav = {"name": name, "letter": letter, "path": path,
                   "user": user, "_pw": _fav_encode_pw(pw)}
            if edit_existing and prefill is not None:
                # Replace existing entry by original name
                for i, f in enumerate(self._favorites):
                    if f["name"] == prefill["name"]:
                        self._favorites[i] = fav
                        break
                else:
                    # Original name not found — just append
                    self._favorites.append(fav)
            else:
                self._favorites.append(fav)
            save_favorites(self._favorites)
            self._render_favorites()
            Logger.log(f"Favorite saved: {name}  ({letter} → {path})", "INFO")
            dlg.destroy()

        btn_row = tk.Frame(dlg, bg=C_BG3)
        btn_row.pack(pady=10, padx=14, fill="x")
        self._btn(btn_row, "★  Save Favorite", _save,
                  bg=C_BTN_SCAN, fg="white", width=16).pack(side="left")
        self._btn(btn_row, "Close", dlg.destroy,
                  bg=C_BTN_NORM, fg=C_FG, width=10).pack(side="right")

        dlg.update_idletasks()
        x = self.root.winfo_x() + self.root.winfo_width()  // 2 - dlg.winfo_width()  // 2
        y = self.root.winfo_y() + self.root.winfo_height() // 2 - dlg.winfo_height() // 2
        dlg.geometry(f"+{x}+{y}")

    def _edit_favorite_dialog(self, idx: int):
        if 0 <= idx < len(self._favorites):
            self._add_favorite_dialog(prefill=self._favorites[idx], edit_existing=True)

    def _delete_favorite(self, idx: int):
        if 0 <= idx < len(self._favorites):
            name = self._favorites[idx].get("name", "this favorite")
            if messagebox.askyesno(
                    "Delete Favorite",
                    f"Delete  '{name}'?",
                    parent=self.root):
                del self._favorites[idx]
                save_favorites(self._favorites)
                self._render_favorites()
                Logger.log(f"Favorite deleted: {name}", "INFO")

    # ------------------------------------------------------------------ #
    #  LOG TAB                                                             #
    # ------------------------------------------------------------------ #

    def _build_log_tab(self):
        tab = self._tab_log
        ctrl = tk.Frame(tab, bg=C_BG2)
        ctrl.pack(fill="x", padx=8, pady=6)

        self._btn(ctrl, "Clear view",    self._clear_log,
                  bg=C_BTN_COPY, fg=C_FG).pack(side="left")
        self._btn(ctrl, "Open log file", self._open_log_file,
                  bg=C_BTN_COPY, fg=C_FG).pack(side="left", padx=6)
        tk.Label(ctrl, text=str(LOG_FILE),
                 bg=C_BG2, fg=C_FG_DIM, font=FONT_SMALL).pack(
            side="left", padx=8)

        frame = tk.Frame(tab, bg=C_BG2)
        frame.pack(fill="both", expand=True, padx=8, pady=(0, 6))

        self._log_text = tk.Text(
            frame, bg="#0a0e14", fg=C_FG_DIM,
            font=FONT_MONO, state="disabled",
            relief="flat", wrap="none",
            insertofftime=0, insertontime=9999999,
        )
        vsb = ttk.Scrollbar(frame, orient="vertical",   command=self._log_text.yview)
        hsb = ttk.Scrollbar(frame, orient="horizontal", command=self._log_text.xview)
        self._log_text.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)
        self._log_text.grid(row=0, column=0, sticky="nsew")
        vsb.grid(row=0, column=1, sticky="ns")
        hsb.grid(row=1, column=0, sticky="ew")
        frame.rowconfigure(0, weight=1)
        frame.columnconfigure(0, weight=1)

        self._log_text.bind("<MouseWheel>",
            lambda e: self._log_text.yview_scroll(-1*(e.delta//120), "units"))

        self._log_text.tag_configure("INFO",  foreground="#6aaa6a")
        self._log_text.tag_configure("WARN",  foreground=C_YELLOW)
        self._log_text.tag_configure("ERROR", foreground=C_RED)

    # ------------------------------------------------------------------ #
    #  SCANNER ACTIONS                                                     #
    # ------------------------------------------------------------------ #

    def _detect_subnet(self):
        ifaces = get_local_interfaces()
        if ifaces:
            labels = [f"{i['name']}  {i['ip']}  ({i['cidr']})" for i in ifaces]
            self._lbl_ifaces.configure(text="  |  ".join(labels), fg=C_GREEN)
            for i in ifaces:
                if not i["ip"].startswith("127."):
                    if not self.var_subnet.get():
                        self.var_subnet.set(i["cidr"])
                    break
        else:
            self._lbl_ifaces.configure(text="No adapters found", fg=C_RED)

    def _start_scan(self):
        if self._scanning:
            return
        subnet = self.var_subnet.get().strip()
        if not subnet:
            messagebox.showwarning("No Subnet",
                                   "Enter a subnet, e.g.  192.168.1.0/24")
            return
        try:
            ipaddress.IPv4Network(subnet, strict=False)
        except ValueError as e:
            messagebox.showerror("Invalid Subnet", str(e))
            return

        try:
            self.cfg["timeout"]     = float(self.var_timeout.get() or 0.8)
            self.cfg["max_threads"] = int(self.var_threads.get() or 128)
        except ValueError:
            pass

        self.cfg.update({
            "subnet":     subnet,
            "do_ports":   self.var_do_ports.get(),
            "do_nbtstat": self.var_do_nbt.get(),
            "do_dns":     self.var_do_dns.get(),
            "ports":      self.var_ports.get(),
        })

        self._hosts.clear()
        for item in self._tree.get_children():
            self._tree.delete(item)

        self._scanning = True
        self._btn_scan.configure(state="disabled")
        self._btn_stop.configure(state="normal")
        self._progress_var.set(0)
        self._lbl_progress.configure(text="Starting …")

        self._scan_engine = ScanEngine(
            cfg         = self.cfg,
            result_cb   = self._on_host_found,
            progress_cb = self._on_progress,
            done_cb     = self._on_scan_done,
            log_cb      = Logger.log,
        )
        self._scan_engine.start(subnet)

    def _stop_scan(self):
        if self._scan_engine:
            self._scan_engine.stop()
        self._btn_stop.configure(state="disabled")

    def _on_host_found(self, host: dict):
        self._hosts.append(host)
        self.root.after(0, self._insert_row, host)

    def _insert_row(self, host: dict):
        vals = (host["ip"], host["hostname"], host["netbios"],
                host["mac"], host["ports_str"], host["status"])
        tag  = "online" if host["status"] == "Online" else "arp_row"
        self._tree.insert("", "end", values=vals, tags=(tag,))

    def _on_progress(self, done: int, total: int):
        pct = (done / total * 100) if total else 0
        self.root.after(0, lambda: (
            self._progress_var.set(pct),
            self._lbl_progress.configure(
                text=f"{done}/{total}  ({pct:.0f}%)")
        ))

    def _on_scan_done(self):
        self.root.after(0, self._finalize_scan)

    def _finalize_scan(self):
        self._scanning = False
        self._btn_scan.configure(state="normal")
        self._btn_stop.configure(state="disabled")
        self._progress_var.set(100)
        n = len(self._hosts)
        self._lbl_progress.configure(text=f"Done – {n} host(s) found")

    def _clear_results(self):
        if self._scanning:
            return
        self._hosts.clear()
        for item in self._tree.get_children():
            self._tree.delete(item)
        self._progress_var.set(0)
        self._lbl_progress.configure(text="Ready")

    def _arp_quick_scan(self):
        """Load the current ARP cache into the scanner results – instant."""
        for item in self._tree.get_children():
            self._tree.delete(item)
        self._hosts.clear()
        arp = get_arp_table()
        for ip in sorted(arp.keys(),
                         key=lambda x: socket.inet_aton(x)):
            host = {"ip": ip, "hostname": "", "netbios": "",
                    "mac": arp[ip], "ports": [],
                    "ports_str": "", "status": "ARP"}
            self._hosts.append(host)
            self._insert_row(host)
        self._lbl_progress.configure(
            text=f"ARP cache loaded – {len(arp)} entries")
        Logger.log(f"ARP quick-scan: {len(arp)} entries.", "INFO")

    # ── Right-click context menu ───────────────────────────────────────

    def _tree_rclick(self, event):
        row = self._tree.identify_row(event.y)
        if not row:
            return
        self._tree.selection_set(row)
        vals = self._tree.item(row, "values")
        if not vals:
            return
        ip = vals[0]
        menu = tk.Menu(self.root, tearoff=0, bg=C_BG2, fg=C_FG,
                       activebackground=C_TREE_SEL, font=FONT_SMALL)
        menu.add_command(label=f"Copy IP  ({ip})",
                         command=lambda: self._clip(ip))
        menu.add_command(label="Copy entire row",
                         command=lambda: self._clip(
                             "\t".join(str(v) for v in vals)))
        menu.add_separator()
        menu.add_command(label="ping -t  (continuous)",
                         command=lambda: subprocess.Popen(
                             ["cmd", "/k", f"ping -t {ip}"],
                             creationflags=subprocess.CREATE_NEW_CONSOLE))
        menu.add_command(label="tracert",
                         command=lambda: subprocess.Popen(
                             ["cmd", "/k", f"tracert {ip}"],
                             creationflags=subprocess.CREATE_NEW_CONSOLE))
        menu.add_command(label="nbtstat -A  (NetBIOS detail)",
                         command=lambda: subprocess.Popen(
                             ["cmd", "/k", f"nbtstat -A {ip}"],
                             creationflags=subprocess.CREATE_NEW_CONSOLE))
        menu.add_command(label="pathping",
                         command=lambda: subprocess.Popen(
                             ["cmd", "/k", f"pathping {ip}"],
                             creationflags=subprocess.CREATE_NEW_CONSOLE))
        menu.add_separator()
        menu.add_command(label="Open in browser  (http://)",
                         command=lambda: webbrowser.open(f"http://{ip}"))
        menu.add_command(label="Open Remote Desktop  (RDP / mstsc)",
                         command=lambda: subprocess.Popen(
                             ["mstsc", f"/v:{ip}"]))
        menu.add_separator()
        menu.add_command(label="🖧  Map network drive …",
                         command=lambda: self._map_drive_dialog(ip))
        menu.add_command(label="🔌  Disconnect network drive …",
                         command=lambda: self._disconnect_drive_dialog(ip))
        try:
            menu.tk_popup(event.x_root, event.y_root)
        finally:
            menu.grab_release()

    def _clip(self, text: str):
        self.root.clipboard_clear()
        self.root.clipboard_append(text)

    # ------------------------------------------------------------------ #
    #  MAP / DISCONNECT NETWORK DRIVE                                      #
    # ------------------------------------------------------------------ #

    def _map_drive_dialog(self, ip: str):
        """Show a dialog to map a network drive to the selected host."""
        available, _ = get_drive_info()

        dlg = tk.Toplevel(self.root)
        dlg.title("Map Network Drive")
        dlg.configure(bg=C_BG3)
        dlg.transient(self.root)
        dlg.grab_set()
        dlg.focus_force()
        dlg.resizable(False, False)
        dlg.bind("<Escape>", lambda _e: dlg.destroy())

        # ── Header ────────────────────────────────────────────────────
        tk.Frame(dlg, bg=C_ACCENT, height=3).pack(fill="x")
        tk.Label(dlg, text="  🖧  Map Network Drive",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_HEADER,
                 anchor="w").pack(fill="x", padx=14, pady=(10, 4))
        tk.Frame(dlg, bg=C_SEP, height=1).pack(fill="x", padx=14)

        body = tk.Frame(dlg, bg=C_BG3, padx=18, pady=12)
        body.pack(fill="x")

        LW = 16   # label column width

        def _lbl(row, text):
            tk.Label(body, text=text, bg=C_BG3, fg=C_FG,
                     font=FONT_SMALL, width=LW, anchor="w").grid(
                row=row, column=0, sticky="w", pady=4)

        # ── Row 0: IP address ──────────────────────────────────────────
        _lbl(0, "IP address:")
        var_ip = tk.StringVar(value=ip)
        e_ip = self._entry(body, textvariable=var_ip, width=26)
        e_ip.grid(row=0, column=1, columnspan=2, sticky="w", padx=(6, 0))
        e_ip.delete(0, "end")
        e_ip.insert(0, ip)

        # ── Row 1: Computer name (auto-detect, editable) ───────────────
        _lbl(1, "Computer name:")
        var_cname = tk.StringVar(value="resolving…")
        e_cname = self._entry(body, textvariable=var_cname, width=22)
        e_cname.grid(row=1, column=1, sticky="w", padx=(6, 0))
        e_cname.configure(fg=C_FG_DIM)

        def _resolve_name():
            """Try NetBIOS first, then DNS; fill in computer name."""
            name = get_netbios_name(ip)
            if not name:
                name = resolve_hostname(ip)
            if not name:
                name = ip
            try:
                e_cname.after(0, lambda: (
                    e_cname.configure(fg=C_FG_BRIGHT),
                    var_cname.set(name),
                    e_cname.delete(0, "end"),
                    e_cname.insert(0, name),
                ))
            except Exception:
                pass

        threading.Thread(target=_resolve_name, daemon=True).start()

        # ── Row 2: Share dropdown ──────────────────────────────────────
        _lbl(2, "Share on remote PC:")
        SHARE_LIST = ["Users\\Public"] + [f"{c}$" for c in
                      "CDEFGHIJKLMNOPQRSTUVWXYZ"]
        var_share = tk.StringVar(value="Users\\Public")
        cb_share = ttk.Combobox(body, textvariable=var_share,
                                values=SHARE_LIST, width=18,
                                font=FONT_MAIN)
        cb_share.grid(row=2, column=1, sticky="w", padx=(6, 0))
        cb_share.set("Users\\Public")

        # ── Row 3: Map as (free drive letter on THIS PC) ──────────────
        _lbl(3, "Map as drive:")
        _all_letters = [f"{c}:" for c in "CDEFGHIJKLMNOPQRSTUVWXYZ"]
        _letter_list  = available + [l for l in _all_letters if l not in available]
        _default_map  = available[0] if available else "Z:"
        var_letter = tk.StringVar(value=_default_map)
        cb_letter = ttk.Combobox(body, textvariable=var_letter,
                                 values=_letter_list, width=5,
                                 font=FONT_MAIN)
        cb_letter.grid(row=3, column=1, sticky="w", padx=(6, 0))
        cb_letter.set(_default_map)

        # ── Path preview (updates live) ────────────────────────────────
        tk.Frame(body, bg=C_SEP, height=1).grid(
            row=4, column=0, columnspan=3, sticky="ew", pady=(6, 2))
        tk.Label(body, text="Full path:", bg=C_BG3, fg=C_FG_DIM,
                 font=FONT_SMALL, width=LW, anchor="w").grid(
            row=5, column=0, sticky="w")
        lbl_preview = tk.Label(body, text="", bg=C_BG3, fg=C_ACCENT,
                               font=FONT_MONO, anchor="w")
        lbl_preview.grid(row=5, column=1, columnspan=2, sticky="w", padx=(6, 0))

        def _update_preview(*_):
            cur_ip    = var_ip.get().strip() or ip
            cur_share = var_share.get().strip()
            lbl_preview.configure(text=f"\\\\{cur_ip}\\{cur_share}")

        var_ip.trace_add("write", _update_preview)
        var_share.trace_add("write", _update_preview)
        _update_preview()

        tk.Frame(body, bg=C_SEP, height=1).grid(
            row=6, column=0, columnspan=3, sticky="ew", pady=(6, 2))

        # ── Row 7: Username ────────────────────────────────────────────
        _lbl(7, "Username:")
        var_user = tk.StringVar()
        self._entry(body, textvariable=var_user, width=22).grid(
            row=7, column=1, sticky="w", padx=(6, 0))

        # ── Row 8: Password ────────────────────────────────────────────
        _lbl(8, "Password:")
        var_pass = tk.StringVar()
        e_pw2 = self._entry(body, textvariable=var_pass, width=22)
        e_pw2.configure(show="●")
        e_pw2.grid(row=8, column=1, sticky="w", padx=(6, 0))

        # ── Row 9: Persistent ──────────────────────────────────────────
        var_persist = tk.BooleanVar(value=True)
        ttk.Checkbutton(body, text="Reconnect at login  (persistent)",
                        variable=var_persist).grid(
            row=9, column=0, columnspan=3, sticky="w", pady=(8, 0))

        # ── Status label ───────────────────────────────────────────────
        lbl_status = tk.Label(dlg, text="", bg=C_BG3, font=FONT_SMALL,
                              fg=C_FG_DIM, wraplength=440, justify="left")
        lbl_status.pack(padx=14, pady=(4, 0))
        tk.Frame(dlg, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=(6, 0))

        # ── Map Drive action ───────────────────────────────────────────
        def _do_map():
            cur_ip   = var_ip.get().strip()
            share    = var_share.get().strip()
            letter   = var_letter.get().strip()
            path     = f"\\\\{cur_ip}\\{share}"
            user     = var_user.get().strip()
            pw       = var_pass.get()

            if not cur_ip or not share:
                lbl_status.configure(text="⚠  Fill in IP and share.", fg=C_YELLOW)
                return
            if not letter:
                lbl_status.configure(text="⚠  Choose a drive letter.", fg=C_YELLOW)
                return

            persist_flag = "yes" if var_persist.get() else "no"
            cmd = ["use", letter, path, f"/persistent:{persist_flag}"]
            if user:
                cmd += [f"/user:{user}"]
                if pw:
                    cmd += [pw]
            lbl_status.configure(text="Connecting …", fg=C_FG_DIM)
            dlg.update_idletasks()
            try:
                rc, out = run_tool(NET_EXE, cmd, timeout=25)
                if rc == 0:
                    lbl_status.configure(
                        text=f"✔  {letter} mapped to {path}", fg=C_GREEN)
                    Logger.log(f"Drive mapped: {letter} → {path}", "INFO")
                    new_avail, _ = get_drive_info()
                    cb_letter.configure(values=new_avail +
                        [l for l in _all_letters if l not in new_avail])
                    if new_avail:
                        var_letter.set(new_avail[0])
                        cb_letter.set(new_avail[0])
                else:
                    hint = net_error_hint(net_error_code(out))
                    lbl_status.configure(
                        text=f"✘  {hint or out or 'net use failed'}", fg=C_RED)
                    Logger.log(f"Drive map failed ({letter} → {path}): {out}", "WARN")
            except Exception as exc:
                lbl_status.configure(text=f"✘  {exc}", fg=C_RED)

        # ── Save as Favorite ───────────────────────────────────────────
        def _save_fav():
            cur_ip   = var_ip.get().strip()
            share    = var_share.get().strip()
            letter   = var_letter.get().strip()
            cname    = var_cname.get().strip()
            # Name: "COMPUTERNAME C$" or "COMPUTERNAME Users\Public"
            share_label = share.rstrip("$") + ":" if share.endswith("$") else share
            fav_name = f"{cname}  {share_label}"
            self._add_favorite_dialog(prefill={
                "name":   fav_name,
                "letter": letter,
                "path":   f"\\\\{cur_ip}\\{share}",
                "user":   var_user.get().strip(),
                "_pw":    _fav_encode_pw(var_pass.get()),
            })

        btn_row = tk.Frame(dlg, bg=C_BG3)
        btn_row.pack(pady=10, padx=14, fill="x")
        self._btn(btn_row, "Map Drive", _do_map,
                  bg=C_BTN_SCAN, fg="white", width=12).pack(side="left")
        self._btn(btn_row, "★  Save as Favorite", _save_fav,
                  bg=C_BTN_COPY, fg=C_ACCENT, width=18).pack(side="left", padx=6)
        self._btn(btn_row, "Close", dlg.destroy,
                  bg=C_BTN_NORM, fg=C_FG, width=10).pack(side="right")

        dlg.update_idletasks()
        x = self.root.winfo_x() + self.root.winfo_width()  // 2 - dlg.winfo_width()  // 2
        y = self.root.winfo_y() + self.root.winfo_height() // 2 - dlg.winfo_height() // 2
        dlg.geometry(f"+{x}+{y}")

    def _disconnect_drive_dialog(self, ip: str):
        """Show a dialog to disconnect drives that point to the selected host."""
        _, mapped = get_drive_info()
        # Filter to drives whose UNC path contains this IP
        host_drives = [(l, u) for l, u in mapped
                       if ip in u]

        dlg = tk.Toplevel(self.root)
        dlg.title("Disconnect Network Drive")
        dlg.configure(bg=C_BG3)
        dlg.transient(self.root)
        dlg.grab_set()
        dlg.focus_force()
        dlg.resizable(False, False)
        dlg.bind("<Escape>", lambda _e: dlg.destroy())

        tk.Frame(dlg, bg=C_RED, height=3).pack(fill="x")
        tk.Label(dlg, text="  🔌  Disconnect Network Drive",
                 bg=C_BG3, fg=C_RED, font=FONT_HEADER,
                 anchor="w").pack(fill="x", padx=14, pady=(10, 4))
        tk.Label(dlg, text=f"  Host: {ip}",
                 bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL,
                 anchor="w").pack(fill="x", padx=14, pady=(0, 8))
        tk.Frame(dlg, bg=C_SEP, height=1).pack(fill="x", padx=14)

        body = tk.Frame(dlg, bg=C_BG3, padx=18, pady=10)
        body.pack(fill="x")

        lbl_status = tk.Label(dlg, text="", bg=C_BG3, font=FONT_SMALL,
                              fg=C_FG_DIM, wraplength=360, justify="left")

        if not host_drives:
            tk.Label(body,
                     text=f"No mapped drives found pointing to  {ip}.\n\n"
                          "Select a drive letter below to disconnect it manually:",
                     bg=C_BG3, fg=C_FG_DIM, font=FONT_SMALL,
                     justify="left").pack(anchor="w")
            _, all_mapped = get_drive_info()
            all_letters = [l for l, _ in all_mapped]
        else:
            tk.Label(body,
                     text="Drives mapped to this host:",
                     bg=C_BG3, fg=C_FG, font=FONT_BOLD).pack(
                anchor="w", pady=(0, 6))
            for letter, unc in host_drives:
                tk.Label(body, text=f"  {letter}  →  {unc}",
                         bg=C_BG3, fg=C_FG_BRIGHT, font=FONT_MAIN).pack(
                    anchor="w")
            all_letters = [l for l, _ in host_drives]

        tk.Label(body, text="\nDisconnect drive:", bg=C_BG3, fg=C_FG,
                 font=FONT_SMALL).pack(anchor="w", pady=(8, 0))

        default_letter = all_letters[0] if all_letters else ""
        var_dc = tk.StringVar(value=default_letter)
        cb2 = ttk.Combobox(body, textvariable=var_dc,
                           values=all_letters or [], width=6,
                           state="readonly" if all_letters else "disabled",
                           font=FONT_MAIN)
        cb2.pack(anchor="w", pady=(4, 0))

        var_force = tk.BooleanVar(value=False)
        ttk.Checkbutton(body, text="Force disconnect even if files are open  (/y)",
                        variable=var_force).pack(anchor="w", pady=(8, 0))

        lbl_status.pack(padx=14, pady=(4, 0))
        tk.Frame(dlg, bg=C_SEP, height=1).pack(fill="x", padx=14, pady=(8, 0))

        def _do_dc():
            letter = var_dc.get().strip()
            if not letter:
                return
            cmd = ["use", letter, "/delete"]
            if var_force.get():
                cmd.append("/y")
            lbl_status.configure(text="Disconnecting …", fg=C_FG_DIM)
            dlg.update_idletasks()
            try:
                rc, out = run_tool(NET_EXE, cmd, timeout=15)
                if rc == 0:
                    lbl_status.configure(
                        text=f"✔  {letter} disconnected.", fg=C_GREEN)
                    Logger.log(f"Drive disconnected: {letter}", "INFO")
                    # Remove from list
                    remaining = [l for l in cb2["values"] if l != letter]
                    cb2.configure(values=remaining,
                                  state="readonly" if remaining else "disabled")
                    var_dc.set(remaining[0] if remaining else "")
                else:
                    lbl_status.configure(
                        text=f"✘  {out or 'net use /delete failed'}", fg=C_RED)
            except Exception as exc:
                lbl_status.configure(text=f"✘  {exc}", fg=C_RED)

        btn_row = tk.Frame(dlg, bg=C_BG3)
        btn_row.pack(pady=10, padx=14, fill="x")
        self._btn(btn_row, "Disconnect", _do_dc,
                  bg=C_BTN_STOP, fg="white", width=12).pack(side="left")
        self._btn(btn_row, "Close", dlg.destroy,
                  bg=C_BTN_NORM, fg=C_FG, width=10).pack(side="right")

        dlg.update_idletasks()
        x = self.root.winfo_x() + self.root.winfo_width()  // 2 - dlg.winfo_width()  // 2
        y = self.root.winfo_y() + self.root.winfo_height() // 2 - dlg.winfo_height() // 2
        dlg.geometry(f"+{x}+{y}")

    def _export_csv(self):
        if not self._hosts:
            messagebox.showinfo("Export", "No results to export.")
            return
        ts   = datetime.now().strftime("%Y%m%d_%H%M%S")
        path = LOG_DIR / f"netradar_scan_{ts}.csv"
        try:
            with open(path, "w", newline="", encoding="utf-8") as f:
                fields = ["ip","hostname","netbios","mac","ports_str","status"]
                w = csv.DictWriter(f, fieldnames=fields)
                w.writeheader()
                for h in self._hosts:
                    w.writerow({k: h.get(k, "") for k in fields})
            self._flash_ok(f"Exported to:\n{path.name}")
            Logger.log(f"Exported {len(self._hosts)} results → {path}", "INFO")
        except Exception as e:
            messagebox.showerror("Export Error", str(e))

    # ------------------------------------------------------------------ #
    #  ARP CACHE ACTIONS                                                   #
    # ------------------------------------------------------------------ #

    def _refresh_arp(self):
        for item in self._arp_tree.get_children():
            self._arp_tree.delete(item)
        try:
            out = subprocess.check_output(
                ["arp", "-a"], text=True, errors="ignore",
                creationflags=subprocess.CREATE_NO_WINDOW,
            )
            iface_line = ""
            for line in out.splitlines():
                s = line.strip()
                if s.lower().startswith("interface:"):
                    iface_line = s
                    continue
                parts = s.split()
                if len(parts) >= 3:
                    ip_s, mac_s, typ = parts[0], parts[1], parts[2]
                    try:
                        ipaddress.ip_address(ip_s)
                        self._arp_tree.insert(
                            "", "end",
                            values=(ip_s, mac_s.upper(), typ, iface_line))
                    except Exception:
                        pass
            Logger.log("ARP cache refreshed.", "INFO")
        except Exception as e:
            Logger.log(f"ARP refresh: {e}", "ERROR")

    def _copy_arp(self):
        lines = ["\t".join(str(x) for x in self._arp_tree.item(i, "values"))
                 for i in self._arp_tree.get_children()]
        self._clip("\n".join(lines))
        self._flash_ok("ARP table copied to clipboard.")

    # ------------------------------------------------------------------ #
    #  WINDOWS FIX ACTIONS                                                 #
    # ------------------------------------------------------------------ #

    def _apply_fix(self, fix: dict):
        btn = self._fix_btns[fix["id"]]
        lbl = self._fix_status[fix["id"]]
        btn.configure(state="disabled", text="Running…")
        lbl.configure(text="Running…", fg=C_YELLOW)

        def _run():
            ok, out = run_fix_command(fix["cmd"])
            summary = out[:80] if out else ("OK" if ok else "Failed")
            self.root.after(0, self._fix_done, fix["id"], ok, summary)
            Logger.log(
                f"Fix [{fix['id']}]: {'OK' if ok else 'FAIL'}  {out[:140]}",
                "INFO" if ok else "WARN",
            )

        threading.Thread(target=_run, daemon=True).start()

    def _fix_done(self, fix_id: str, ok: bool, msg: str):
        self._fix_btns[fix_id].configure(state="normal", text="Apply")
        lbl = self._fix_status[fix_id]
        if ok:
            lbl.configure(text="✔  " + msg, fg=C_GREEN)
        else:
            lbl.configure(text="✖  " + msg, fg=C_RED)

    def _apply_all_fixes(self):
        for fix in FIXES:
            if fix["id"] in RECOMMENDED_FIXES:
                self._apply_fix(fix)

    # ------------------------------------------------------------------ #
    #  LOG ACTIONS                                                         #
    # ------------------------------------------------------------------ #

    def _on_log_cb(self, line: str, level: str):
        self.root.after(0, self._append_log, line, level)

    def _append_log(self, line: str, level: str):
        max_lines = int(self.cfg.get("log_max_lines", 2000))
        self._log_text.configure(state="normal")
        self._log_text.insert("end", line, level)
        n_lines = int(self._log_text.index("end-1c").split(".")[0])
        if n_lines > max_lines:
            self._log_text.delete("1.0", f"{n_lines - max_lines}.0")
        self._log_text.see("end")
        self._log_text.configure(state="disabled")

    def _clear_log(self):
        self._log_text.configure(state="normal")
        self._log_text.delete("1.0", "end")
        self._log_text.configure(state="disabled")

    def _open_log_file(self):
        if LOG_FILE.exists():
            os.startfile(str(LOG_FILE))
        else:
            messagebox.showinfo("Log", "Log file not yet created.")

    # ------------------------------------------------------------------ #
    #  MISC / UTILITY                                                      #
    # ------------------------------------------------------------------ #

    def _on_tab_change(self, _event):
        idx = self.nb.index(self.nb.select())
        self.cfg["last_tab"] = idx
        if idx == 1:   # Printers tab – load the Windows list once
            if not self._win_printers:
                self._refresh_win_printers()
        elif idx == 2:  # ARP Cache tab
            self._refresh_arp()

    def _flash_ok(self, msg: str):
        """Show a borderless success popup that auto-closes after 1 second."""
        top = tk.Toplevel(self.root)
        top.overrideredirect(True)
        top.configure(bg=C_GREEN)
        tk.Label(top, text=msg, bg=C_GREEN, fg="white",
                 font=FONT_BOLD, padx=22, pady=14).pack()
        self.root.update_idletasks()
        x = self.root.winfo_x() + self.root.winfo_width()  // 2 - 130
        y = self.root.winfo_y() + self.root.winfo_height() // 2 - 35
        top.geometry(f"+{x}+{y}")
        top.after(1000, top.destroy)

    def _on_close(self):
        if self._scanning and self._scan_engine:
            self._scan_engine.stop()
        if self._p_scanning and self._p_engine:
            self._p_engine.stop()
        try:
            self.cfg.update({
                "p_mdns":  self.var_p_mdns.get(),
                "p_sweep": self.var_p_sweep.get(),
                "p_snmp":  self.var_p_snmp.get(),
            })
        except Exception:
            pass
        try:
            self.cfg.update({
                "geometry":     self.root.geometry(),
                "subnet":       self.var_subnet.get(),
                "timeout":      float(self.var_timeout.get() or 0.8),
                "max_threads":  int(self.var_threads.get() or 128),
                "do_ports":     self.var_do_ports.get(),
                "do_nbtstat":   self.var_do_nbt.get(),
                "do_dns":       self.var_do_dns.get(),
                "ports":        self.var_ports.get(),
            })
        except Exception:
            pass
        save_settings(self.cfg)
        self.root.destroy()

    # ------------------------------------------------------------------ #
    #  ABOUT DIALOG                                                        #
    # ------------------------------------------------------------------ #

    def _show_about(self):
        top = tk.Toplevel(self.root)
        top.title("About NetRadar")
        top.configure(bg=C_BG3)
        top.resizable(False, False)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _e: top.destroy())

        hdr = tk.Frame(top, bg=C_BG3)
        hdr.pack(fill="x")
        tk.Label(hdr, text="◉",   bg=C_BG3, fg=C_ACCENT,
                 font=("Consolas", 36)).pack(pady=(18, 0))
        tk.Label(hdr, text="NetRadar",
                 bg=C_BG3, fg=C_ACCENT,
                 font=("Consolas", 20, "bold")).pack()
        tk.Label(hdr, text="Local Network Scanner",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Consolas", 9, "italic")).pack(pady=(2, 10))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20)

        tk.Label(top, text='Created by  Lars "Issu" Olsson',
                 bg=C_BG3, fg=C_FG,
                 font=("Consolas", 10, "bold")).pack(pady=(14, 0))

        DOC_URL = (
            "https://docs.google.com/document/d/"
            "1B6y3CP-DafUKoXF9Apg4BpEl2m1j0kghRgD7lweF41s/edit?usp=sharing"
        )
        doc_lbl = tk.Label(top, text="📄  View documentation",
                           bg=C_BG3, fg=C_ACCENT,
                           font=("Consolas", 9, "underline"), cursor="hand2")
        doc_lbl.pack(pady=(6, 2))
        doc_lbl.bind("<Button-1>", lambda _e: webbrowser.open(DOC_URL))
        doc_lbl.bind("<Enter>",    lambda _e: doc_lbl.configure(fg="#b4d4ff"))
        doc_lbl.bind("<Leave>",    lambda _e: doc_lbl.configure(fg=C_ACCENT))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(14, 0))

        tk.Label(top,
                 text="☕  If you enjoy NetRadar, a small gift is always welcome!",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Consolas", 8, "italic"),
                 wraplength=300, justify="center").pack(pady=(10, 6))

        donate_frame = tk.Frame(top, bg="#252535", padx=16, pady=10)
        donate_frame.pack(fill="x", padx=20, pady=(0, 6))

        REVOLUT_URL = "https://revolut.me/lars72oeh"
        PAYPAL_URL  = "https://paypal.me/issusbarn"
        WISE_URL    = "https://wise.com/pay/me/larsdenniso"

        for label, url in [
            ("💳  Revolut", REVOLUT_URL),
            ("💰  PayPal",  PAYPAL_URL),
            ("🏦  Wise",    WISE_URL),
        ]:
            lbl = tk.Label(donate_frame, text=label,
                           bg="#252535", fg=C_ACCENT,
                           font=("Consolas", 9, "underline"), cursor="hand2")
            lbl.pack(pady=2)
            _u = url
            lbl.bind("<Button-1>", lambda _e, u=_u: webbrowser.open(u))
            lbl.bind("<Enter>",    lambda _e, l=lbl: l.configure(fg="#b4d4ff"))
            lbl.bind("<Leave>",    lambda _e, l=lbl: l.configure(fg=C_ACCENT))

        tk.Frame(top, bg=C_SEP, height=1).pack(fill="x", padx=20, pady=(8, 0))
        tk.Label(top, text="Press ESC to close",
                 bg=C_BG3, fg=C_FG_DIM,
                 font=("Consolas", 8, "italic")).pack(pady=8)

    # ------------------------------------------------------------------ #
    #  HELP DIALOG                                                         #
    # ------------------------------------------------------------------ #

    def _show_help(self):
        top = tk.Toplevel(self.root)
        top.title("NetRadar – Help")
        top.configure(bg=C_BG2)
        top.transient(self.root)
        top.grab_set()
        top.focus_force()
        top.bind("<Escape>", lambda _e: top.destroy())
        top.geometry("760x640")

        hdr = tk.Frame(top, bg=C_BG3, pady=8)
        hdr.pack(fill="x")
        tk.Label(hdr, text="◉  NetRadar – Help & Documentation",
                 bg=C_BG3, fg=C_ACCENT, font=FONT_TITLE).pack(
            padx=14, anchor="w")

        frame = tk.Frame(top, bg=C_BG2)
        frame.pack(fill="both", expand=True, padx=8, pady=6)

        txt = tk.Text(
            frame, bg="#0a0e14", fg=C_FG,
            font=("Consolas", 9), wrap="word",
            relief="flat", padx=14, pady=10,
            insertofftime=0, insertontime=9999999,
        )
        vsb = ttk.Scrollbar(frame, orient="vertical", command=txt.yview)
        txt.configure(yscrollcommand=vsb.set)
        txt.pack(side="left", fill="both", expand=True)
        vsb.pack(side="right", fill="y")
        txt.bind("<MouseWheel>",
            lambda e: txt.yview_scroll(-1*(e.delta//120), "units"))

        txt.tag_configure("h1",  foreground=C_ACCENT,  font=("Consolas",11,"bold"))
        txt.tag_configure("h2",  foreground=C_GREEN,   font=("Consolas",10,"bold"))
        txt.tag_configure("kw",  foreground=C_YELLOW,  font=("Consolas", 9,"bold"))
        txt.tag_configure("dim", foreground=C_FG_DIM,  font=("Consolas", 8,"italic"))

        HELP = [
("h1", "NETRADAR – LOCAL NETWORK SCANNER\n\n"),
("",   "NetRadar finds computers and devices on your LAN using a three-phase approach:\n"
       "ping sweep, ARP cache enrichment, and DNS/NetBIOS/port probing.\n\n"),

("h1", "═══  SCANNER TAB  ═══\n\n"),
("h2", "Subnet\n"),
("",   "  The IP range to scan.  Example: 192.168.1.0/24  (254 addresses).\n"
       "  Detected automatically from your network adapters.\n"
       "  You can also enter a single IP (192.168.1.5/32) or a wider range (/16).\n\n"),
("h2", "Timeout (s)\n"),
("",   "  How long to wait for each ping reply.  0.5 = fast, 1.5 = thorough.\n\n"),
("h2", "Threads\n"),
("",   "  Number of simultaneous probes.  128 is a good default.\n"
       "  Increase for faster scans; reduce if your router becomes unstable.\n\n"),
("h2", "Resolve DNS / NetBIOS names / Check ports\n"),
("",   "  DNS     – reverse-lookup each IP to get its hostname.\n"
       "  NetBIOS – query Windows computer names via nbtstat -A.\n"
       "  Ports   – probe the TCP port list on each alive host.\n\n"),
("h2", "▶ Scan  (or press ENTER in the Subnet field)\n"),
("",   "  Phase 1 – Ping sweep of all IPs in the subnet.\n"
       "  Phase 2 – Read ARP cache → MAC addresses.\n"
       "  Phase 3 – Enrich each alive host: DNS, NetBIOS, open ports.\n\n"),
("h2", "ARP quick-scan\n"),
("",   "  Instantly shows all entries from your ARP cache.\n"
       "  No pinging – just reads what your PC has already communicated with.\n\n"),
("h2", "Right-click on a result row\n"),
("",   "  Copy IP, copy row, open continuous ping / tracert / nbtstat / pathping\n"
       "  in a terminal window, open HTTP in browser, or launch RDP.\n\n"),
("h2", "Export CSV\n"),
("",   "  Saves all scan results as a CSV file in  Helpfiles/0---Empty/.\n\n"),

("h1", "═══  🖨 PRINTERS TAB  ═══\n\n"),
("",   "  A dedicated printer hunt.  Use this when Windows cannot find your\n"
       "  network printer.  The normal Scanner tab relies on ping, and most\n"
       "  printers STOP ANSWERING PING while asleep — but they still answer on\n"
       "  their printing ports.  This tab probes those ports directly.\n\n"),
("h2", "mDNS / Bonjour\n"),
("",   "  Sends one multicast question to 224.0.0.251 asking\n"
       "  '_ipp', '_ipps', '_printer', '_pdl-datastream', '_scanner', '_uscan'.\n"
       "  Almost every printer made after ~2010 answers this, and the answer\n"
       "  usually contains the printer's advertised name.\n"
       "  No Bonjour service needs to be installed.\n\n"),
("h2", "Port sweep\n"),
("",   "  Tries TCP 9100 (RAW/JetDirect), 515 (LPD) and 631 (IPP) on every\n"
       "  address in the subnet.  This is the method that finds sleeping\n"
       "  printers and printers with mDNS switched off.\n\n"),
("h2", "SNMP model lookup\n"),
("",   "  Asks each candidate over SNMP (UDP 161, community 'public') for its\n"
       "  device description and system name — that is where the real model\n"
       "  name comes from, e.g. 'HP LaserJet MFP M28w'.\n"
       "  If the printer has SNMP disabled, NetRadar falls back to reading the\n"
       "  title of its built-in web page instead.\n\n"),
("h2", "Confidence column\n"),
("",   "  Certain – multiple printing ports and/or mDNS printer service.\n"
       "  Likely  – one strong indicator (e.g. port 9100 only).\n"
       "  Maybe   – weak match; check it manually before trusting it.\n\n"),
("h2", "Found via column\n"),
("",   "  Which method(s) discovered the device: mDNS, Port, SNMP, HTTP.\n\n"),
("h2", "Double-click a row\n"),
("",   "  Opens the printer's built-in web page (http://<ip>).  Nearly every\n"
       "  network printer has one — that is where you see ink/toner levels,\n"
       "  the network settings and often the model name.\n\n"),
("h2", "Right-click a row\n"),
("",   "  Open web UI (http / https), copy IP or row, show full SNMP details\n"
       "  (serial number, page count, console message), continuous ping, and\n"
       "  'Install this printer in Windows' — which creates a standard TCP/IP\n"
       "  printer port for that IP and opens the Add Printer wizard.\n\n"),
("h2", "Installed printers  (lower list)\n"),
("",   "  Everything Windows already has installed, with the IP address each\n"
       "  TCP/IP port points at.  This is the fastest way to see that a printer\n"
       "  is installed but pointing at an OLD IP address — the single most\n"
       "  common reason a network printer 'disappears'.\n"
       "  Right-click for the print queue or the printer properties.\n\n"),
("h2", "If your printer still is not found\n"),
("",   "  1. Check the subnet.  A printer on 192.168.0.x will never be found\n"
       "     while you scan 192.168.1.0/24.  Print the printer's own network\n"
       "     configuration page from its front panel to see its real IP.\n"
       "  2. Wake the printer (press a button) and scan again.\n"
       "  3. Make sure the printer is on the same Wi-Fi band/network as the PC —\n"
       "     guest networks and some 5 GHz/2.4 GHz splits block discovery.\n"
       "  4. Use the Windows Fix tab to enable Network Discovery.\n"
       "  5. If the printer is connected to another PC, it is a shared printer,\n"
       "     not a network printer — look for \\\\thatpc\\printername instead.\n\n"),

("h1", "═══  ARP CACHE TAB  ═══\n\n"),
("",   "  Displays the raw ARP table from your PC (arp -a).\n"
       "  Entries appear here once your PC has communicated with a host.\n"
       "  The tab auto-refreshes whenever you switch to it.\n\n"),

("h1", "═══  ★ FAVORITES TAB  ═══\n\n"),
("",   "  Save network drive shortcuts that reconnect instantly — no scanning needed.\n"
       "  Favorites survive reboots and are stored in\n"
       "  Helpfiles/0---Settings/netradar_favorites.json\n\n"),
("h2", "＋ Add New Favorite\n"),
("",   "  Opens a dialog where you fill in:\n"
       "    Favorite name  – a label for the card (e.g. 'NAS media')\n"
       "    Drive letter   – e.g. Z:  (free letters shown first)\n"
       "    Share path     – e.g. \\\\server\\share  (must start with \\\\)\n"
       "    Username / Password  – optional credentials\n"
       "  Quick-pick buttons (C$, D$, Users\\Public) speed up path entry.\n\n"),
("h2", "▶ Connect\n"),
("",   "  Runs  net use <letter> <path>  for that favorite.\n"
       "  The status label on the card turns green on success or red on failure.\n"
       "  If no login is saved for that PC, a small login box asks ONCE; the login\n"
       "  is then used for all favorites of that PC and stored in Windows' own\n"
       "  credential store, so File Explorer stops asking too.\n\n"),
("h2", "⚡ Activate All\n"),
("",   "  Connects every favorite in one go.  With 'Reconnect all favorites\n"
       "  automatically' ticked this also happens every time NetRadar starts -\n"
       "  after a Windows reinstall just start NetRadar once.\n\n"),
("h2", "✎ Edit  /  ✖ Delete\n"),
("",   "  Edit updates the saved favorite in place.\n"
       "  Delete asks for confirmation before removing it.\n\n"),
("h2", "Add from Scanner\n"),
("",   "  Right-click any host in the Scanner and choose\n"
       "  🖧  Map network drive … → Save as Favorite\n"
       "  to pre-fill the dialog with that host's IP.\n\n"),

("h1", "═══  WINDOWS FIX TAB  ═══\n\n"),
("",   "  One-click fixes for the most common reasons two Windows 11 PCs\n"
       "  can't see each other on a local network.\n"
       "  Run on BOTH machines.  Administrator rights required.\n\n"),

("h2", "★ Recommended fixes (applied by 'Apply ALL'):\n\n"),
("kw", "  Allow inbound Ping (ICMPv4)\n"),
("",   "     Your PC will not respond to pings unless this rule is enabled.\n"
       "     NetRadar's scanner relies on ping to detect hosts.\n\n"),
("kw", "  Enable Network Discovery (Private)\n"),
("",   "     Opens the firewall rule that lets your PC broadcast its presence\n"
       "     and find other machines on the same network.\n\n"),
("kw", "  Enable File & Printer Sharing\n"),
("",   "     Required for SMB file shares and the Windows network browser.\n\n"),
("kw", "  Set network profile to Private\n"),
("",   "     Windows blocks discovery on Public profile networks.\n"
       "     This command switches your current connection to Private.\n\n"),
("kw", "  Enable NetBIOS over TCP/IP\n"),
("",   "     Broadcasts your computer name so others can find you by name.\n\n"),
("kw", "  Start Function Discovery services\n"),
("",   "     fdphost, FDResPub, SSDPSRV, upnphost – these background services\n"
       "     power the Windows Network panel.  Often disabled on fresh Win11.\n\n"),

("h2", "▶ Apply ALL recommended fixes\n"),
("",   "  Runs all six fixes above in one go.\n"
       "  A UAC elevation prompt will appear if NetRadar is not already\n"
       "  running as Administrator.\n\n"),

("h1", "═══  LOG TAB  ═══\n\n"),
("",   "  Timestamped log of every action.  Colour-coded by severity.\n"
       "  Log file location:  Helpfiles/0---Empty/netradar_log.txt\n\n"),

("h1", "═══  TIPS FOR WINDOWS 11 NETWORK VISIBILITY  ═══\n\n"),
("",   "  • Both PCs must be on the same subnet, e.g. 192.168.1.x\n"
       "  • Both PCs must have Network Discovery enabled (private profile)\n"
       "  • Both PCs must respond to pings (ICMPv4 inbound rule)\n"
       "  • Function Discovery services must be running on both machines\n"
       "  • After applying fixes, restart the services or reboot\n"
       "  • Use NetRadar's Scanner to verify – if a PC responds to ping it\n"
       "    will appear in results even if Windows Explorer can't see it\n"
       "  • Check that both PCs are on the same physical switch / VLAN\n"
       "  • Temporarily disable third-party firewalls to isolate the issue\n\n"),

("dim","  Press ESC to close.\n"),
        ]

        txt.configure(state="normal")
        for tag, text in HELP:
            txt.insert("end", text, tag if tag else ())
        txt.configure(state="disabled")

        tk.Button(
            top, text="Close  [ESC]", command=top.destroy,
            bg=C_BTN_NORM, fg=C_FG, font=FONT_BOLD,
            relief="flat", cursor="hand2",
            activebackground=C_SEP, bd=0,
            pady=6, padx=18,
        ).pack(pady=(0, 8))


# *************** DEL 09 – CRASH CATCHER & ENTRY POINT ***************
# ToDo: Global exception hook writes full traceback to crash file + shows dialog.

def _crash_handler(exc_type, exc_val, exc_tb):
    msg  = "".join(traceback.format_exception(exc_type, exc_val, exc_tb))
    ts   = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    path = LOG_DIR / "netradar_CRASH.txt"
    try:
        with open(path, "a", encoding="utf-8") as f:
            f.write(f"\n{'='*60}\n[{ts}] CRASH\n{msg}\n")
    except Exception:
        pass
    try:
        messagebox.showerror(
            "NetRadar – Unexpected Error",
            f"An unexpected error occurred:\n\n{exc_val}\n\n"
            f"Full details saved to:\n{path}",
        )
    except Exception:
        pass


def _set_window_icon(root: tk.Tk) -> None:
    """Set window + taskbar icon from Icons/NetRadar.ico (Windows-aware)."""
    if platform.system() != "Windows":
        return
    ico_path = str(BASE_DIR / "Icons" / "NetRadar.ico")
    if not Path(ico_path).is_file():
        return
    try:
        root.iconbitmap(ico_path)
    except Exception:
        pass
    try:
        user32          = ctypes.windll.user32
        LR_LOADFROMFILE = 0x0010
        LR_DEFAULTSIZE  = 0x0040
        IMAGE_ICON      = 1
        WM_SETICON      = 0x0080
        hwnd = user32.FindWindowW(None, root.title())
        if not hwnd:
            return
        hbig = user32.LoadImageW(None, ico_path, IMAGE_ICON,  0,  0,
                                 LR_LOADFROMFILE | LR_DEFAULTSIZE)
        hsml = user32.LoadImageW(None, ico_path, IMAGE_ICON, 16, 16,
                                 LR_LOADFROMFILE)
        if hbig: user32.SendMessageW(hwnd, WM_SETICON, 1, hbig)
        if hsml: user32.SendMessageW(hwnd, WM_SETICON, 0, hsml)
    except Exception:
        pass


def main():
    sys.excepthook = _crash_handler
    # AppUserModelID must be set BEFORE tk.Tk() for correct taskbar grouping
    try:
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            "Issu.NetRadar.1")
    except Exception:
        pass
    root = tk.Tk()
    NetRadarApp(root)
    # after(0) fires on first mainloop tick — after tkinter resets the icon
    root.after(0, lambda: _set_window_icon(root))
    root.mainloop()


if __name__ == "__main__":
    main()
