Есть скрипт, который выдаёт ошибку, когда пытаешься выделить несколько прокси из списка через Ctrl:

PS D:\ip_info> python ip_info.py
Traceback (most recent call last):
  File "D:\ip_info\ip_info.py", line 214, in keyPressEvent
    if event.matches(QKeySequence.StandardKey.SelectAll):
                     ^^^^^^^^^^^^
NameError: name 'QKeySequence' is not defined

Вот скрипт:

import sys
import requests
import re
import os
import json
import pycountry  # Импортируем pycountry для сопоставления стран с кодами
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QCheckBox,
    QListWidget, QVBoxLayout, QHBoxLayout, QSystemTrayIcon, QMenu, QMessageBox,
    QMenuBar, QRadioButton, QButtonGroup, QDialog, QSpacerItem, QSizePolicy, QWidget
)
from PyQt6.QtGui import QIcon, QAction, QDesktopServices, QCursor, QPixmap
from PyQt6.QtCore import Qt, QUrl, QTimer, pyqtSignal
from cryptography.fernet import Fernet  # Импортируем Fernet для шифрования


# Пути к файлам и каталогам
PROXY_FILE = 'D:\\ip_info\\settings\\proxies.json'
SETTINGS_FILE = 'D:\\ip_info\\settings\\settings.json'
ICON_PATH = 'D:\\ip_info\\icons\\app_ip.ico'
CRYPT_DIR = 'D:\\ip_info\\settings\\cryptography'
CRYPT_KEY_FILE = os.path.join(CRYPT_DIR, 'key.key')


# Unified style for all buttons
BUTTON_STYLE = """
    QPushButton {
        border: none;
        background-color: #4CAF50;  /* Button color (soft green) */
        color: white;  /* Text color */
        padding: 10px 20px;
        border-radius: 5px;  /* Rounded corners */
    }
    QPushButton:hover {
        background-color: #45a049;  /* Button color on hover */
    }
"""

# New style for the Delete Proxy button (soft red)
BUTTON_STYLE_DELETE = """
    QPushButton {
        border: none;
        background-color: #f44336;  /* Soft red color */
        color: white;  /* Text color */
        padding: 10px 20px;
        border-radius: 5px;  /* Rounded corners */
    }
    QPushButton:hover {
        background-color: #da190b;  /* Darker red on hover */
    }
"""

# Style for QCheckBox when disabled
CHECKBOX_STYLE = """
    QCheckBox {
        color: white;
    }
    QCheckBox:disabled {
        color: #7f7f7f;  /* Gray color for disabled text */
    }
"""


def get_ip_and_isp(proxy_data=None, use_proxy=False, service_url='https://ipinfo.io/json'):
    try:
        proxies = None
        if use_proxy and proxy_data:
            protocol = proxy_data.get('protocol', 'socks5')
            server_port = proxy_data['server_port']
            username = proxy_data.get('username')
            password = proxy_data.get('password')
            proxy_url = f"{protocol}://{server_port}"
            if username and password:
                proxy_url = f"{protocol}://{username}:{password}@{server_port}"
            proxies = {
                'http': proxy_url,
                'https': proxy_url,
            }
        response = requests.get(service_url, proxies=proxies, timeout=10)
        data = response.json()
        
        if 'ipinfo.io' in service_url:
            ip = data.get('ip', 'N/A')
            org = data.get('org', 'N/A')
            city = data.get('city', 'N/A')
            country = data.get('country', 'N/A')

            # Extract ISP name without AS number
            if org.startswith('AS'):
                isp = ' '.join(org.split(' ')[1:])
            else:
                isp = org

        elif 'ipapi.co' in service_url:
            ip = data.get('ip', 'N/A')
            isp = data.get('org', 'N/A')
            city = data.get('city', 'N/A')
            country = data.get('country_name', 'N/A')  # ipapi.co использует 'country_name'

            # Extract ISP name without AS number
            if isp.startswith('AS'):
                isp = ' '.join(isp.split(' ')[1:])

        elif 'ip-api.com' in service_url:
            if data.get('status') != 'success':
                raise ValueError('API response status not success')
            ip = data.get('query', 'N/A')
            isp = data.get('isp', 'N/A')
            city = data.get('city', 'N/A')
            country = data.get('country', 'N/A')

        else:
            ip = 'N/A'
            isp = 'N/A'
            city = 'N/A'
            country = 'N/A'

        # Remove legal forms (case-insensitive and considering quotes)
        legal_forms = ['PJSC', 'LLC', 'JSC', 'OJSC', 'АО', 'ОАО', 'ЗАО', 'ООО', 'ПАО']
        pattern = r'\b(' + '|'.join(legal_forms) + r')\b'
        isp = re.sub(pattern, '', isp, flags=re.IGNORECASE).strip()

        # Remove extra characters like quotes or special symbols
        isp = isp.replace('"', '').replace('«', '').replace('»', '').strip()

        # Remove extra spaces
        isp = ' '.join(isp.split())

        return ip, isp, city, country
    except Exception as e:
        print(f"Error in get_ip_and_isp: {e}")  # Логирование ошибки для отладки
        return 'Ошибка', 'Ошибка', 'Ошибка', 'Ошибка'


class AboutDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('О программе')
        self.setFixedSize(400, 200)
        self.setWindowIcon(parent.icon if parent and hasattr(parent, 'icon') else QIcon())

        layout = QVBoxLayout()

        # Title
        title_label = QLabel("JustWoofIP")
        title_font = title_label.font()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(title_label)

        # Version
        version_label = QLabel("Версия: 1.0.0-20241101")
        version_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(version_label)

        # Website with link
        site_label = QLabel()
        site_label.setText(
            'Сайт: <a href="https://chat.mistral.ai" style="color: #1E90FF; font-weight: bold; text-decoration: none;">https://chat.mistral.ai</a>'
        )
        site_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        site_label.setOpenExternalLinks(False)  # Disable automatic link opening
        site_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
        site_label.linkActivated.connect(self.open_link)
        site_label.setStyleSheet("""
            QLabel {
                color: white;
                background-color: #1e1e1e;
            }
            a:hover {
                text-decoration: underline;
            }
        """)

        layout.addWidget(site_label)

        # Spacer for padding
        spacer = QSpacerItem(20, 40, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding)
        layout.addItem(spacer)

        # Close button
        close_button = QPushButton("Закрыть")
        close_button.clicked.connect(self.close)
        close_button.setStyleSheet(BUTTON_STYLE)
        close_button.setFixedWidth(100)
        close_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        layout.addWidget(close_button, alignment=Qt.AlignmentFlag.AlignCenter)

        self.setLayout(layout)
        self.setStyleSheet("background-color: #1e1e1e; color: white;")

    def open_link(self, link):
        QDesktopServices.openUrl(QUrl(link))
        self.close()


class ClickableLabel(QLabel):
    clicked = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.clicked.emit()
        super().mousePressEvent(event)


class ProxyListWidget(QListWidget):
    def keyPressEvent(self, event):
        if event.matches(QKeySequence.StandardKey.SelectAll):
            self.selectAll()
        else:
            super().keyPressEvent(event)


class MyApp(QMainWindow):
    def __init__(self):
        super().__init__()

        self.minimize_to_tray = False  # Default initialization
        self.current_service_url = None  # Для хранения текущего URL сервиса

        # Инициализируем шифрование
        self.load_or_generate_key()

        self.initUI()

    def load_or_generate_key(self):
        """Загружает существующий ключ или генерирует новый."""
        if not os.path.exists(CRYPT_KEY_FILE):
            key = Fernet.generate_key()
            os.makedirs(os.path.dirname(CRYPT_KEY_FILE), exist_ok=True)
            with open(CRYPT_KEY_FILE, 'wb') as key_file:
                key_file.write(key)
        else:
            with open(CRYPT_KEY_FILE, 'rb') as key_file:
                key = key_file.read()
        self.fernet = Fernet(key)

    def initUI(self):
        self.setWindowTitle('JustWoofIP')
        self.setStyleSheet("background-color: #1e1e1e; color: white;")

        # Set icon
        if os.path.exists(ICON_PATH):
            self.icon = QIcon(ICON_PATH)
            self.setWindowIcon(self.icon)
        else:
            self.icon = QIcon()

        # Create central widget and layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout()
        central_widget.setLayout(layout)

        # Menu Bar
        self.create_menu()

        # IP and Copy Button
        hbox_ip = QHBoxLayout()
        ip_label = QLabel("Мой IP:")
        self.ip_text = QLineEdit()
        self.ip_text.setReadOnly(True)
        self.ip_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_ip.addWidget(ip_label)
        hbox_ip.addWidget(self.ip_text)

        # Copy Button next to IP
        self.copy_ip_button = QPushButton("Копировать")
        self.copy_ip_button.clicked.connect(self.copy_ip)
        self.copy_ip_button.setStyleSheet(BUTTON_STYLE)
        self.copy_ip_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        hbox_ip.addWidget(self.copy_ip_button)
        layout.addLayout(hbox_ip)

        # ISP, City, Country Fields with Flag
        hbox_isp = QHBoxLayout()
        
        # ISP
        isp_label = QLabel("Мой ISP:")
        self.isp_text = QLineEdit()
        self.isp_text.setReadOnly(True)
        self.isp_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_isp.addWidget(isp_label)
        hbox_isp.addWidget(self.isp_text)

        # City
        city_label = QLabel("Город:")
        self.city_text = QLineEdit()
        self.city_text.setReadOnly(True)
        self.city_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_isp.addWidget(city_label)
        hbox_isp.addWidget(self.city_text)

        # Country
        country_label = QLabel("Страна:")
        self.country_text = QLineEdit()
        self.country_text.setReadOnly(True)
        self.country_text.setStyleSheet("background-color: #323232; color: white;")
        hbox_isp.addWidget(country_label)
        hbox_isp.addWidget(self.country_text)

        # Flag Label (Clickable)
        self.flag_label = ClickableLabel()
        self.flag_label.setFixedSize(32, 24)  # Размер флага
        self.flag_label.clicked.connect(self.open_service_url)  # Подключение сигнала клика
        hbox_isp.addWidget(self.flag_label)

        layout.addLayout(hbox_isp)

        # Use Proxy checkbox and notification
        hbox_use_proxy = QHBoxLayout()
        self.use_proxy_checkbox = QCheckBox("Использовать прокси")
        self.use_proxy_checkbox.setChecked(False)  # Default: proxy not used
        # Apply styles to QCheckBox
        self.use_proxy_checkbox.setStyleSheet(CHECKBOX_STYLE)
        hbox_use_proxy.addWidget(self.use_proxy_checkbox)

        # Notification Label
        self.notification_label = QLabel("", self)
        self.notification_label.setStyleSheet("""
            QLabel {
                background-color: rgba(50, 50, 50, 200);
                color: white;
                padding: 5px 10px;
                border-radius: 5px;
                font-weight: bold;
            }
        """)
        self.notification_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.notification_label.hide()

        # Add stretch and notification to the same row
        hbox_use_proxy.addStretch()
        hbox_use_proxy.addWidget(self.notification_label)
        layout.addLayout(hbox_use_proxy)

        # =======================
        # 1. Изменённый ввод "Добавить прокси" на два поля в двух строках
        # =======================
        # Первая строка: "Прокси" и "Порт"
        hbox_proxy_port = QHBoxLayout()
        proxy_label = QLabel("Прокси:")
        self.proxy_input = QLineEdit()
        self.proxy_input.setPlaceholderText("protocol://proxy")
        self.proxy_input.setStyleSheet("background-color: #323232; color: white;")
        self.proxy_input.returnPressed.connect(self.on_add_proxy)  # Подключение Enter
        port_label = QLabel("Порт:")
        self.port_input = QLineEdit()
        self.port_input.setPlaceholderText("Port")
        self.port_input.setStyleSheet("background-color: #323232; color: white;")
        self.port_input.returnPressed.connect(self.on_add_proxy)  # Подключение Enter
        hbox_proxy_port.addWidget(proxy_label)
        hbox_proxy_port.addWidget(self.proxy_input)
        hbox_proxy_port.addWidget(port_label)
        hbox_proxy_port.addWidget(self.port_input)
        layout.addLayout(hbox_proxy_port)

        # Вторая строка: "Имя пользователя" и "Пароль"
        hbox_auth = QHBoxLayout()
        username_label = QLabel("Имя пользователя:")
        self.username_input = QLineEdit()
        self.username_input.setPlaceholderText("Username")
        self.username_input.setStyleSheet("background-color: #323232; color: white;")
        self.username_input.returnPressed.connect(self.on_add_proxy)  # Подключение Enter
        password_label = QLabel("Пароль:")
        self.password_input = QLineEdit()
        self.password_input.setPlaceholderText("Password")
        self.password_input.setStyleSheet("background-color: #323232; color: white;")
        self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
        self.password_input.returnPressed.connect(self.on_add_proxy)  # Подключение Enter
        hbox_auth.addWidget(username_label)
        hbox_auth.addWidget(self.username_input)
        hbox_auth.addWidget(password_label)
        hbox_auth.addWidget(self.password_input)
        layout.addLayout(hbox_auth)

        # =======================
        # 2. Размещение списка прокси и кнопок справа без стилизации полосы прокрутки
        # =======================
        hbox3 = QHBoxLayout()

        # Proxy List
        self.saved_proxy_choice = ProxyListWidget()
        # Enable multiple selection
        self.saved_proxy_choice.setSelectionMode(QListWidget.SelectionMode.ExtendedSelection)
        # Set size policy to make it occupy 50% of the available width
        self.saved_proxy_choice.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        hbox3.addWidget(self.saved_proxy_choice, 1)  # Stretch factor 1

        # Vertical layout for buttons
        vbox_buttons = QVBoxLayout()

        # Save Proxy Button
        self.add_proxy_button = QPushButton("Сохранить прокси")
        self.add_proxy_button.setStyleSheet(BUTTON_STYLE)
        self.add_proxy_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.add_proxy_button.clicked.connect(self.on_add_proxy)

        # Delete Proxy Button with soft red color
        self.delete_proxy_button = QPushButton("Удалить выбранные прокси")
        self.delete_proxy_button.setStyleSheet(BUTTON_STYLE_DELETE)
        self.delete_proxy_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.delete_proxy_button.clicked.connect(self.on_delete_proxy)

        # Add buttons to the vertical layout with spacing
        vbox_buttons.addStretch()
        vbox_buttons.addWidget(self.add_proxy_button)
        vbox_buttons.addSpacing(10)  # Add spacing between buttons
        vbox_buttons.addWidget(self.delete_proxy_button)
        vbox_buttons.addStretch()

        # Add vertical button layout to the main horizontal layout
        hbox3.addLayout(vbox_buttons, 0)  # Stretch factor 0 to prevent stretching

        layout.addLayout(hbox3)

        # Service Selection with Additional ip-api.com
        hbox5 = QHBoxLayout()
        service_label = QLabel("Выбор сервиса:")
        self.service_group = QButtonGroup()
        self.ipinfo_radio = QRadioButton("ipinfo.io")
        self.ipapi_radio = QRadioButton("ipapi.co")
        self.ipapi_radio_new = QRadioButton("ip-api.com")  # New radio button
        self.service_group.addButton(self.ipinfo_radio)
        self.service_group.addButton(self.ipapi_radio)
        self.service_group.addButton(self.ipapi_radio_new)  # Add to group
        self.ipinfo_radio.setChecked(True)  # Default selection
        hbox5.addWidget(service_label)
        hbox5.addWidget(self.ipinfo_radio)
        hbox5.addWidget(self.ipapi_radio)
        hbox5.addWidget(self.ipapi_radio_new)  # Add to layout
        layout.addLayout(hbox5)

        # Get IP and ISP Button
        self.get_button = QPushButton("Получить IP и ISP")
        self.get_button.setStyleSheet(BUTTON_STYLE)
        self.get_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        self.get_button.clicked.connect(self.on_get_button)

        # Center the Get Button
        hbox_get = QHBoxLayout()
        hbox_get.addStretch()
        hbox_get.addWidget(self.get_button)
        hbox_get.addStretch()
        layout.addLayout(hbox_get)

        # Load saved proxies and settings
        self.load_saved_proxies()
        self.load_settings()

        # Create System Tray Icon
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.icon)
        self.tray_icon.setToolTip('JustWoofIP')
        self.tray_icon.activated.connect(self.on_tray_icon_activated)
        self.create_tray_menu()
        self.tray_icon.show()

    def create_menu(self):
        menubar = self.menuBar()

        # "Файл" Menu
        file_menu = menubar.addMenu('Файл')
        exit_action = QAction('Выход', self)
        exit_action.triggered.connect(self.on_menu_exit)
        file_menu.addAction(exit_action)

        # "Настройки" Menu
        settings_menu = menubar.addMenu('Настройки')
        minimize_to_tray_action = QAction('Сворачивать в трей при закрытии', self, checkable=True)
        minimize_to_tray_action.setChecked(self.minimize_to_tray)
        minimize_to_tray_action.triggered.connect(self.on_minimize_to_tray_toggled)
        settings_menu.addAction(minimize_to_tray_action)

        # "Справка" Menu
        help_menu = menubar.addMenu('Справка')
        about_action = QAction('О программе', self)
        about_action.triggered.connect(self.show_about_dialog)
        help_menu.addAction(about_action)

        # Set styles for the menu
        menubar.setStyleSheet("""
            QMenuBar {
                background-color: #323232;
                color: white;
            }
            QMenuBar::item:selected {
                background-color: #464646;
            }
            QMenu {
                background-color: #323232;
                color: white;
            }
            QMenu::item:selected {
                background-color: #464646;
            }
            QMenu::item:pressed {
                background-color: #5a5a5a;
            }
        """)

    def create_tray_menu(self):
        menu = QMenu()
        show_action = QAction("Показать", self)
        exit_action = QAction("Выход", self)
        show_action.triggered.connect(self.on_tray_show)
        exit_action.triggered.connect(self.on_tray_exit)
        menu.addAction(show_action)
        menu.addAction(exit_action)
        self.tray_icon.setContextMenu(menu)

    def on_tray_icon_activated(self, reason):
        if reason == QSystemTrayIcon.ActivationReason.Trigger:
            self.on_tray_show()

    def on_tray_show(self):
        self.showNormal()
        self.activateWindow()

    def on_tray_exit(self):
        self.tray_icon.hide()
        self.close()

    def on_menu_exit(self):
        self.tray_icon.hide()
        self.close()

    def on_minimize_to_tray_toggled(self, checked):
        self.minimize_to_tray = checked

    def closeEvent(self, event):
        self.save_settings()
        if self.minimize_to_tray:
            self.hide()
            event.ignore()
        else:
            self.tray_icon.hide()
            event.accept()

    def load_saved_proxies(self):
        self.saved_proxies = []
        if os.path.exists(PROXY_FILE):
            try:
                with open(PROXY_FILE, 'r', encoding='utf-8') as f:
                    encrypted_proxies = json.load(f)
                # Расшифровываем учётные данные и сохраняем в self.saved_proxies
                for proxy in encrypted_proxies:
                    decrypted_proxy = {
                        'protocol': proxy.get('protocol', 'socks5'),
                        'server_port': proxy.get('server_port', '')
                    }
                    if 'username' in proxy:
                        try:
                            decrypted_username = self.fernet.decrypt(proxy['username'].encode()).decode()
                            decrypted_proxy['username'] = decrypted_username
                        except Exception as e:
                            print(f"Ошибка расшифровки имени пользователя: {e}")
                    if 'password' in proxy:
                        try:
                            decrypted_password = self.fernet.decrypt(proxy['password'].encode()).decode()
                            decrypted_proxy['password'] = decrypted_password
                        except Exception as e:
                            print(f"Ошибка расшифровки пароля: {e}")
                    self.saved_proxies.append(decrypted_proxy)
                self.update_saved_proxy_list()
            except Exception as e:
                print(f"Ошибка загрузки прокси: {e}")
        self.update_proxy_checkbox_state()  # Обновляем состояние чекбокса после загрузки прокси

    def save_proxies(self):
        # Перед сохранением шифруем учётные данные
        proxies_to_save = []
        for proxy in self.saved_proxies:
            proxy_copy = {
                'protocol': proxy.get('protocol', 'socks5'),
                'server_port': proxy.get('server_port', '')
            }
            if 'username' in proxy and proxy['username']:
                proxy_copy['username'] = self.fernet.encrypt(proxy['username'].encode()).decode()
            if 'password' in proxy and proxy['password']:
                proxy_copy['password'] = self.fernet.encrypt(proxy['password'].encode()).decode()
            proxies_to_save.append(proxy_copy)
        
        os.makedirs(os.path.dirname(PROXY_FILE), exist_ok=True)  # Ensure directory exists
        try:
            with open(PROXY_FILE, 'w', encoding='utf-8') as f:
                json.dump(proxies_to_save, f, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"Ошибка сохранения прокси: {e}")

    def update_saved_proxy_list(self):
        self.saved_proxy_choice.clear()
        for proxy in self.saved_proxies:
            display_text = f"{proxy['protocol']}://{proxy['server_port']}"
            if proxy.get('username') and proxy.get('password'):
                display_text += f" (***:***)"  # Маскировка username и password
            elif proxy.get('username'):
                display_text += f" (***:---)"  # Только username
            elif proxy.get('password'):
                display_text += f" (---:***)"  # Только password
            self.saved_proxy_choice.addItem(display_text)
        self.update_proxy_checkbox_state()  # Update checkbox state after updating the list

    def update_proxy_checkbox_state(self):
        if len(self.saved_proxies) == 0:
            self.use_proxy_checkbox.setChecked(False)
            self.use_proxy_checkbox.setEnabled(False)
        else:
            self.use_proxy_checkbox.setEnabled(True)

    def load_settings(self):
        if os.path.exists(SETTINGS_FILE):
            try:
                with open(SETTINGS_FILE, 'r', encoding='utf-8') as f:
                    settings = json.load(f)
                use_proxy = settings.get('use_proxy', False)
                minimize_to_tray = settings.get('minimize_to_tray', False)
                selected_proxy_index = settings.get('selected_proxy_index', -1)
                selected_service = settings.get('selected_service', 'ipinfo.io')

                self.use_proxy_checkbox.setChecked(use_proxy)
                self.minimize_to_tray = minimize_to_tray
                if 0 <= selected_proxy_index < len(self.saved_proxies):
                    self.saved_proxy_choice.setCurrentRow(selected_proxy_index)
                if selected_service == 'ipinfo.io':
                    self.ipinfo_radio.setChecked(True)
                elif selected_service == 'ipapi.co':
                    self.ipapi_radio.setChecked(True)
                elif selected_service == 'ip-api.com':
                    self.ipapi_radio_new.setChecked(True)
            except Exception as e:
                print(f"Ошибка загрузки настроек: {e}")
        else:
            # If settings file doesn't exist, set default values
            self.use_proxy_checkbox.setChecked(False)
            self.minimize_to_tray = False
            self.ipinfo_radio.setChecked(True)

    def save_settings(self):
        selected_service = 'ipinfo.io'
        if self.ipinfo_radio.isChecked():
            selected_service = 'ipinfo.io'
        elif self.ipapi_radio.isChecked():
            selected_service = 'ipapi.co'
        elif self.ipapi_radio_new.isChecked():
            selected_service = 'ip-api.com'

        settings = {
            'use_proxy': self.use_proxy_checkbox.isChecked(),
            'minimize_to_tray': self.minimize_to_tray,
            'selected_proxy_index': self.saved_proxy_choice.currentRow(),
            'selected_service': selected_service
        }
        os.makedirs(os.path.dirname(SETTINGS_FILE), exist_ok=True)  # Ensure directory exists
        try:
            with open(SETTINGS_FILE, 'w', encoding='utf-8') as f:
                json.dump(settings, f, ensure_ascii=False, indent=4)
        except Exception as e:
            print(f"Ошибка сохранения настроек: {e}")

    def on_get_button(self):
        use_proxy = self.use_proxy_checkbox.isChecked()
        if self.ipinfo_radio.isChecked():
            service_url = 'https://ipinfo.io/json'
        elif self.ipapi_radio.isChecked():
            service_url = 'https://ipapi.co/json/'
        elif self.ipapi_radio_new.isChecked():
            service_url = 'http://ip-api.com/json/'
        else:
            service_url = 'https://ipinfo.io/json'  # Default

        self.current_service_url = service_url  # Сохраняем текущий сервис

        proxy_data = None
        if use_proxy:
            selected_indices = self.saved_proxy_choice.selectedIndexes()
            if selected_indices:
                # Use the first selected proxy
                selected_index = selected_indices[0].row()
                if 0 <= selected_index < len(self.saved_proxies):
                    proxy_data = self.saved_proxies[selected_index].copy()  # Копируем данные прокси
            elif len(self.saved_proxies) > 0:
                # Automatically apply the first proxy if none selected
                proxy_data = self.saved_proxies[0].copy()

        ip, isp, city, country = get_ip_and_isp(proxy_data, use_proxy, service_url)
        self.ip_text.setText(ip)
        self.isp_text.setText(isp)
        self.city_text.setText(city)
        self.country_text.setText(country)

        # Обновляем флаг страны
        self.update_country_flag(country)

    def on_add_proxy(self):
        proxy = self.proxy_input.text().strip()
        port = self.port_input.text().strip()
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()

        # Проверка обязательных полей и условий
        if not proxy or not port:
            self.show_notification_inline("Прокси и порт обязательны", duration=2000)
            return

        if password and not username:
            self.show_notification_inline("Имя пользователя обязательно при наличии пароля", duration=2000)
            return

        if '://' in proxy:
            try:
                protocol, server = proxy.split('://', 1)
            except ValueError:
                self.show_notification_inline("Некорректный формат прокси", duration=2000)
                return
        else:
            protocol = 'socks5'  # Default protocol
            server = proxy

        # Валидация порта
        if not port.isdigit():
            self.show_notification_inline("Порт должен быть числом", duration=2000)
            return

        server_port = f"{server}:{port}"

        # Проверка на дублирование прокси
        duplicate = False
        for existing_proxy in self.saved_proxies:
            if existing_proxy['protocol'] == protocol and existing_proxy['server_port'] == server_port:
                duplicate = True
                break

        if duplicate:
            self.show_notification_inline("Прокси с таким адресом и портом уже существует", duration=2000)
            return

        # Создаём словарь прокси с расшифрованными данными
        proxy_data = {'protocol': protocol, 'server_port': server_port}

        if username:
            proxy_data['username'] = username
        if password:
            proxy_data['password'] = password

        # Добавить прокси в список и сохранить
        self.saved_proxies.append(proxy_data)
        self.save_proxies()
        self.update_saved_proxy_list()

        # Очищаем поля ввода
        self.proxy_input.clear()
        self.port_input.clear()
        self.username_input.clear()
        self.password_input.clear()

        self.show_notification_inline("Прокси сохранен", duration=2000)

    def on_delete_proxy(self):
        selected_indices = self.saved_proxy_choice.selectedIndexes()
        if not selected_indices:
            self.show_notification_inline("Не выбран прокси для удаления", duration=2000)
            return

        # Collect unique row numbers to delete
        rows_to_delete = sorted({index.row() for index in selected_indices}, reverse=True)

        for row in rows_to_delete:
            if 0 <= row < len(self.saved_proxies):
                del self.saved_proxies[row]

        self.save_proxies()
        self.update_saved_proxy_list()

        # Автоматически выбрать следующий прокси после удаления
        total = self.saved_proxy_choice.count()
        if total > 0:
            # Если список не пуст, выбрать первый прокси
            self.saved_proxy_choice.setCurrentRow(0)

        self.show_notification_inline("Выбранные прокси удалены", duration=2000)

    def copy_ip(self):
        ip = self.ip_text.text().strip()
        if ip and ip != 'N/A' and ip != 'Ошибка':
            clipboard = QApplication.clipboard()
            clipboard.setText(ip)
            self.show_notification_inline("IP-адрес скопирован", duration=2000)
        else:
            self.show_notification_inline("Нечего копировать", duration=2000)

    def show_notification_inline(self, message, duration=1000):
        """Show notification in the designated space next to the proxy checkbox."""
        self.notification_label.setText(message)
        self.notification_label.adjustSize()
        self.notification_label.setFixedHeight(30)
        # Center the notification in the available space
        self.notification_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.notification_label.show()

        # Create a timer to hide the notification after `duration` milliseconds
        QTimer.singleShot(duration, self.notification_label.hide)

    def show_about_dialog(self):
        dialog = AboutDialog(self)
        dialog.exec()

    def select_all_proxies(self):
        self.saved_proxy_choice.selectAll()

    def update_country_flag(self, country_name):
        """Загружает и отображает флаг страны по её названию."""
        try:
            if not country_name or country_name == 'N/A' or country_name == 'Ошибка':
                self.flag_label.clear()
                return

            # Получаем объект страны из pycountry
            try:
                country = pycountry.countries.lookup(country_name)
            except LookupError:
                # Попытка fuzzy поиска
                try:
                    search_results = pycountry.countries.search_fuzzy(country_name)
                    country = search_results[0] if search_results else None
                except:
                    country = None

            if country:
                country_code = country.alpha_2.lower()

                # URL флага (используем FlagCDN)
                # Пример: https://flagcdn.com/32x24/us.png
                flag_url = f"https://flagcdn.com/32x24/{country_code}.png"

                response = requests.get(flag_url, timeout=10)
                if response.status_code == 200:
                    pixmap = QPixmap()
                    pixmap.loadFromData(response.content)
                    self.flag_label.setPixmap(pixmap)
                else:
                    # Если флаг не найден, очищаем QLabel
                    self.flag_label.clear()
            else:
                # Ручное сопоставление для "Russia"
                if country_name.lower() == "russia":
                    country_code = "ru"
                    flag_url = f"https://flagcdn.com/32x24/{country_code}.png"
                    response = requests.get(flag_url, timeout=10)
                    if response.status_code == 200:
                        pixmap = QPixmap()
                        pixmap.loadFromData(response.content)
                        self.flag_label.setPixmap(pixmap)
                    else:
                        self.flag_label.clear()
                else:
                    print(f"Не удалось найти код страны для: {country_name}")
                    self.flag_label.clear()
        except Exception as e:
            print(f"Ошибка загрузки флага: {e}")
            self.flag_label.clear()

    def open_service_url(self):
        """Открывает веб-страницу сервиса проверки IP при клике на флаг."""
        if self.current_service_url:
            QDesktopServices.openUrl(QUrl(self.current_service_url))
        else:
            self.show_notification_inline("Сервис не выбран", duration=2000)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyApp()
    ex.show()
    sys.exit(app.exec())