"""Command-line interface for checksum."""

from __future__ import annotations

import argparse
import hashlib
import logging
import sys
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Final

from PySide2.QtCore import QDir
from PySide2.QtWidgets import (
    QApplication,
    QCheckBox,
    QComboBox,
    QDialog,
    QFileDialog,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QRadioButton,
    QTextEdit,
    QVBoxLayout,
    QWidget,
)

# Style constants for consistent UI design
_UI_CONSTANTS = {
    # Dimensions
    "BUTTON_HEIGHT": 22,
    "INPUT_HEIGHT": 22,
    "COMPACT_SPACING": 4,
    "TIGHT_SPACING": 2,
    "MIN_MARGIN": 2,
    "SMALL_MARGIN": 8,
    "MEDIUM_MARGIN": 12,
    "LARGE_MARGIN": 16,
    # Widths
    "BUTTON_WIDTH_LARGE": 120,
    "BUTTON_WIDTH_MEDIUM": 100,
    "BUTTON_WIDTH_SMALL": 80,
    "INPUT_WIDTH_MIN": 280,
    "RESULT_WIDTH": 500,
    "RESULT_HEIGHT": 150,
    "LANGUAGE_COMBO_WIDTH": 100,
    # Fonts
    "FONT_SIZE_LARGE": 16,
    "FONT_SIZE_MEDIUM": 15,
    "FONT_SIZE_SMALL": 12,
    "FONT_FAMILY": "'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif",
    "MONO_FONT": "'Consolas', 'Microsoft YaHei UI', monospace",
    # Colors (aligned with pypack_gui style)
    "PRIMARY_BLUE": "#3b82f6",
    "PRIMARY_DARK": "#1d4ed8",
    "BORDER_COLOR": "#cbd5e1",
    "BACKGROUND_LIGHT": "#ffffff",
    "BACKGROUND_CARD": "#f8fafc",
    "TEXT_PRIMARY": "#0f172a",
    "TEXT_SECONDARY": "#64748b",
    # Label styling - Simple and clean design
    "LABEL_PADDING_VERTICAL": 4,
    "LABEL_PADDING_HORIZONTAL": 8,
    "LABEL_BORDER_RADIUS": 4,
    "LABEL_BACKGROUND": "transparent",
    "LABEL_TEXT_COLOR": "#0f172a",
    "LABEL_BORDER_COLOR": "transparent",
}


# Layout factory methods for consistent configuration
class LayoutFactory:
    """Factory methods for creating consistent layouts and configurations."""

    @staticmethod
    def create_compact_layout(
        spacing: int = _UI_CONSTANTS["COMPACT_SPACING"],
        margins: tuple = (_UI_CONSTANTS["MIN_MARGIN"],) * 4,
    ) -> QHBoxLayout:
        """Create horizontally compact layout."""
        layout = QHBoxLayout()
        layout.setSpacing(spacing)
        layout.setContentsMargins(*margins)
        return layout

    @staticmethod
    def create_vertical_compact_layout(
        spacing: int = _UI_CONSTANTS["COMPACT_SPACING"],
        margins: tuple = (_UI_CONSTANTS["MIN_MARGIN"],) * 4,
    ) -> QVBoxLayout:
        """Create vertically compact layout."""
        layout = QVBoxLayout()
        layout.setSpacing(spacing)
        layout.setContentsMargins(*margins)
        return layout

    @staticmethod
    def configure_compact_widget(
        widget: QWidget,
        spacing: int = _UI_CONSTANTS["TIGHT_SPACING"],
        margins: tuple = (
            0,
            _UI_CONSTANTS["MIN_MARGIN"],
            0,
            _UI_CONSTANTS["MIN_MARGIN"],
        ),
    ) -> None:
        """Configure widget with compact layout settings."""
        if hasattr(widget, "layout") and widget.layout():
            layout = widget.layout()
            layout.setSpacing(spacing)
            layout.setContentsMargins(*margins)


# Modern unified stylesheet for checksum module - aligned with pypack_gui style
_CHECKSUM_STYLESHEET = """
/* Main window and global styles - Modern design aligned with pypack_gui */
QMainWindow, QDialog {
    background-color: #f8fafc;
    font-family: 'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif;
    font-size: 16px;
}

QWidget {
    font-family: 'Microsoft YaHei UI', 'Segoe UI', 'PingFang SC', sans-serif;
    font-size: 16px;
}

/* Main dialog styling with modern card design */
ChecksumDialog {
    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                    stop:0 #ffffff, stop:1 #f1f5f9);
    border: 1px solid #e2e8f0;
    border-radius: 16px;
    color: #0f172a;
}

ChecksumDialog::title {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 #3b82f6, stop:1 #1d4ed8);
    color: white;
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    border-bottom: 2px solid #1e40af;
    font-size: 18px;
    font-weight: 600;
    padding: 14px 22px;
    letter-spacing: 0.5px;
    text-transform: uppercase;
}

/* Modern group box styling with unified blue theme */
QGroupBox {
    background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                                    stop:0 #ffffff, stop:1 #f8fafc);
    border: 1px solid #cbd5e1;
    border-radius: 12px;
    margin: 8px;
    padding-top: 24px;
    font-weight: 500;
}

QGroupBox::title {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 #3b82f6, stop:1 #1d4ed8);
    color: white;
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    border-bottom: 2px solid #1e40af;
    padding: 6px 14px;
    font-size: 15px;
    font-weight: 600;
}

/* Unified button styling with modern hover effects - aligned with pypack_gui */
QPushButton {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 #3b82f6, stop:1 #2563eb);
    color: white;
    border: none;
    border-radius: 8px;
    padding: 12px 20px;
    font-size: 15px;
    font-weight: 500;
    min-height: 36px;
    font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
}

QPushButton:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 #2563eb, stop:1 #1d4ed8);
}

QPushButton:pressed {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                              stop:0 #1d4ed8, stop:1 #1e40af);
}

QPushButton:disabled {
    background: #94a3b8;
    color: #cbd5e1;
}

/* Input controls with modern styling - aligned with pypack_gui */
QLineEdit, QTextEdit {
    background-color: #ffffff;
    border: 2px solid #cbd5e1;
    border-radius: 8px;
    padding: 12px 16px;
    font-size: 16px;
    font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
    selection-background-color: #dbeafe;
    min-height: 28px;
}

QLineEdit:focus, QTextEdit:focus {
    border: 2px solid #3b82f6;
    outline: none;
}

/* Radio buttons with modern design */
QRadioButton {
    spacing: 8px;
    font-size: 15px;
    font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
}

QRadioButton::indicator {
    width: 18px;
    height: 18px;
    border-radius: 9px;
    border: 2px solid #cbd5e1;
    background-color: white;
}

QRadioButton::indicator:hover {
    border: 2px solid #3b82f6;
}

QRadioButton::indicator:checked {
    background-color: #3b82f6;
    border: 2px solid #3b82f6;
}

/* Checkboxes with modern styling */
QCheckBox {
    spacing: 8px;
    font-size: 15px;
    font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
}

QCheckBox::indicator {
    width: 18px;
    height: 18px;
    border-radius: 4px;
    border: 2px solid #cbd5e1;
    background-color: white;
}

QCheckBox::indicator:hover {
    border: 2px solid #3b82f6;
}

QCheckBox::indicator:checked {
    background-color: #3b82f6;
    border: 2px solid #3b82f6;
}

/* Labels with modern typography */
QLabel {
    font-size: 15px;
    color: #334155;
    font-family: 'Microsoft YaHei UI', 'Segoe UI', sans-serif;
}

/* ComboBox styling */
QComboBox {
    background-color: #ffffff;
    border: 2px solid #cbd5e1;
    border-radius: 8px;
    padding: 10px 14px;
    font-size: 15px;
    font-family: 'Consolas', 'Microsoft YaHei UI', monospace;
    min-height: 28px;
}

QComboBox:hover {
    border: 2px solid #94a3b8;
}

QComboBox:focus {
    border: 2px solid #3b82f6;
}

QComboBox::drop-down {
    border: none;
    width: 20px;
}

/* Scrollbar styling */
QScrollBar:vertical {
    border: none;
    background-color: #f1f5f9;
    width: 12px;
    border-radius: 6px;
    margin: 2px;
}

QScrollBar::handle:vertical {
    background-color: #94a3b8;
    border-radius: 6px;
    min-height: 20px;
}

QScrollBar::handle:vertical:hover {
    background-color: #64748b;
}

/* Status and result areas with specialized styling */
#m_teChecksum {
    background-color: #f0fdf4;
    border: 2px solid #86efac;
    border-radius: 8px;
    font-family: 'Consolas', 'Courier New', monospace;
    font-size: 14px;
    color: #166534;
    padding: 12px 16px;
}

#m_teChecksum:focus {
    border: 2px solid #22c55e;
    background-color: #dcfce7;
}

/* Special styling for comparison input */
#m_leCompare {
    background-color: #fffbeb;
    border: 2px solid #fbbf24;
    border-radius: 8px;
    padding: 12px 16px;
}

#m_leCompare:focus {
    border: 2px solid #f59e0b;
    background-color: #fef3c7;
}

/* Object name specific styling for enhanced visual hierarchy */
#dataSourceGroup::title {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 #3b82f6, stop:1 #1d4ed8);
}

#algorithmPanel::title {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 #8b5cf6, stop:1 #7c3aed);
}

#comparisonGroup::title {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 #f59e0b, stop:1 #d97706);
}

#resultGroup::title {
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                              stop:0 #10b981, stop:1 #059669);
}
"""

logger = logging.getLogger(__name__)


class HashAlgorithm(Enum):
    """Supported hash algorithms."""

    MD5 = "md5"
    SHA1 = "sha1"
    SHA256 = "sha256"
    SHA384 = "sha384"
    SHA512 = "sha512"
    BLAKE2B = "blake2b"
    BLAKE2S = "blake2s"


@dataclass
class ChecksumResult:
    """Checksum calculation result."""

    algorithm: HashAlgorithm
    hash_value: str
    input_type: str  # "string" or "file"
    input_source: str
    comparison_passed: bool | None = None


@dataclass
class ChecksumConfig:
    """Checksum tool configuration."""

    default_algorithm: HashAlgorithm = HashAlgorithm.MD5
    enable_comparison: bool = False
    output_format: str = "hex"


class ChecksumCalculator:
    """Core checksum calculation engine."""

    SUPPORTED_ALGORITHMS: Final[set[HashAlgorithm]] = set(HashAlgorithm)

    def __init__(self, config: ChecksumConfig | None = None) -> None:
        """Initialize checksum calculator with configuration."""
        self.config = config or ChecksumConfig()
        self._current_algorithm = self.config.default_algorithm

    def calculate_string_checksum(self, content: str, algorithm: HashAlgorithm | None = None) -> str:
        """Calculate checksum for string content."""
        if not content:
            raise ValueError("Content cannot be empty")

        alg = algorithm or self._current_algorithm
        hash_func = getattr(hashlib, alg.value)
        return hash_func(content.encode("utf-8")).hexdigest()

    def calculate_file_checksum(self, file_path: Path, algorithm: HashAlgorithm | None = None) -> str:
        """Calculate checksum for file content."""
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")

        alg = algorithm or self._current_algorithm
        hash_func = getattr(hashlib, alg.value)
        hasher = hash_func()

        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(8192), b""):
                hasher.update(chunk)

        return hasher.hexdigest()

    def verify_checksum(self, calculated: str, expected: str) -> bool:
        """Verify calculated checksum against expected value."""
        return calculated.lower() == expected.lower()

    def set_algorithm(self, algorithm: HashAlgorithm) -> None:
        """Set current hash algorithm."""
        if algorithm not in self.SUPPORTED_ALGORITHMS:
            raise ValueError(f"Unsupported algorithm: {algorithm}")
        self._current_algorithm = algorithm

    @property
    def current_algorithm(self) -> HashAlgorithm:
        """Get current hash algorithm."""
        return self._current_algorithm


class ChecksumDialog(QDialog):
    """Checksum calculation dialog interface."""

    def __init__(self) -> None:
        """Initialize checksum dialog."""
        QDialog.__init__(self)
        self.setWindowTitle(_translation_manager.tr("window_title"))
        self.resize(537, 475)

        # Initialize core calculator
        self.calculator = ChecksumCalculator()

        # Apply integrated styles
        self._apply_styles()

        # Create UI elements
        self._create_ui()
        self._init_ui()
        self.current_file_path: str = ""

        # Add language selector
        self._add_language_selector()

    def _create_ui(self) -> None:
        """Create modern user interface with optimized layout and organization."""
        # Main layout with extreme compact spacing
        main_layout = LayoutFactory.create_vertical_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(_UI_CONSTANTS["SMALL_MARGIN"],) * 4,
        )
        self.setLayout(main_layout)

        # Data source group with extreme compact design
        data_group = QGroupBox(_translation_manager.tr("data_source"))
        data_group.setObjectName("dataSourceGroup")
        data_layout = LayoutFactory.create_vertical_compact_layout(
            spacing=_UI_CONSTANTS["TIGHT_SPACING"],
            margins=(_UI_CONSTANTS["MIN_MARGIN"],) * 4,
        )
        data_group.setLayout(data_layout)

        # String input section with improved label spacing
        string_section = QWidget()
        string_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(
                0,
                _UI_CONSTANTS["MIN_MARGIN"],
                0,
                _UI_CONSTANTS["MIN_MARGIN"],
            ),
        )
        string_section.setLayout(string_layout)

        # Add explicit label for string input
        string_label = QLabel(_translation_manager.tr("input_string"))
        string_label.setStyleSheet(
            f"""
            font-size: {_UI_CONSTANTS["FONT_SIZE_MEDIUM"]}px;
            font-weight: 500;
            color: {_UI_CONSTANTS["LABEL_TEXT_COLOR"]};
            padding: (
                {_UI_CONSTANTS["LABEL_PADDING_VERTICAL"]}px
                {_UI_CONSTANTS["LABEL_PADDING_HORIZONTAL"]}px
            );
            font-family: {_UI_CONSTANTS["FONT_FAMILY"]};
            """
        )
        string_label.setMinimumHeight(24)
        string_layout.addWidget(string_label)

        self.m_leString = QLineEdit()
        self.m_leString.setMinimumHeight(_UI_CONSTANTS["INPUT_HEIGHT"])
        self.m_leString.setStyleSheet("padding: 2px;")
        self.m_pbGenerateString = QPushButton(_translation_manager.tr("calculate_checksum"))
        self.m_pbGenerateString.setMinimumWidth(_UI_CONSTANTS["BUTTON_WIDTH_LARGE"])
        self.m_pbGenerateString.setMinimumHeight(_UI_CONSTANTS["BUTTON_HEIGHT"])
        self.m_pbGenerateString.setStyleSheet("padding: 2px 8px;")

        string_layout.addWidget(self.m_leString, 1)
        string_layout.addWidget(self.m_pbGenerateString)

        # File input section with improved label spacing
        file_section = QWidget()
        file_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(
                0,
                _UI_CONSTANTS["MIN_MARGIN"],
                0,
                _UI_CONSTANTS["MIN_MARGIN"],
            ),
        )
        file_section.setLayout(file_layout)

        # Add explicit label for file input
        file_label = QLabel(_translation_manager.tr("input_file"))
        file_label.setStyleSheet(
            f"""
            font-size: {_UI_CONSTANTS["FONT_SIZE_MEDIUM"]}px;
            font-weight: 500;
            color: {_UI_CONSTANTS["LABEL_TEXT_COLOR"]};
            padding: (
                {_UI_CONSTANTS["LABEL_PADDING_VERTICAL"]}px
                {_UI_CONSTANTS["LABEL_PADDING_HORIZONTAL"]}px
            );
            font-family: {_UI_CONSTANTS["FONT_FAMILY"]};
            """
        )
        file_label.setMinimumHeight(24)
        file_layout.addWidget(file_label)

        self.m_leFile = QLineEdit()
        self.m_leFile.setMinimumSize(_UI_CONSTANTS["INPUT_WIDTH_MIN"], 0)
        self.m_leFile.setMinimumHeight(_UI_CONSTANTS["INPUT_HEIGHT"])
        self.m_leFile.setStyleSheet("padding: 2px;")
        self.m_pbOpenFile = QPushButton(_translation_manager.tr("browse"))
        self.m_pbOpenFile.setMinimumWidth(_UI_CONSTANTS["BUTTON_WIDTH_SMALL"])
        self.m_pbOpenFile.setMinimumHeight(_UI_CONSTANTS["BUTTON_HEIGHT"])
        self.m_pbOpenFile.setStyleSheet("padding: 2px 6px;")
        self.m_pbGenerateFile = QPushButton(_translation_manager.tr("calculate_checksum"))
        self.m_pbGenerateFile.setMinimumWidth(_UI_CONSTANTS["BUTTON_WIDTH_LARGE"])
        self.m_pbGenerateFile.setMinimumHeight(_UI_CONSTANTS["BUTTON_HEIGHT"])
        self.m_pbGenerateFile.setStyleSheet("padding: 2px 8px;")

        file_layout.addWidget(self.m_leFile, 1)
        file_layout.addWidget(self.m_pbOpenFile)
        file_layout.addWidget(self.m_pbGenerateFile)

        # Add sections to data layout
        data_layout.addWidget(string_section)
        data_layout.addWidget(file_section)

        # Main content area with extreme compact grid layout
        content_area = QWidget()
        content_layout = QHBoxLayout(content_area)
        content_layout.setSpacing(6)  # 极致压缩内容区域间距

        # Left panel - Algorithm selection
        algo_panel = QGroupBox(_translation_manager.tr("algorithm"))
        algo_panel.setObjectName("algorithmPanel")
        algo_layout = QVBoxLayout(algo_panel)
        algo_layout.setSpacing(8)
        algo_layout.setContentsMargins(12, 12, 12, 12)

        # Algorithm radio buttons with modern styling
        algorithms = [
            ("MD5", True),
            ("SHA1", False),
            ("SHA256", False),
            ("SHA384", False),
            ("SHA512", False),
            ("Blake2b", False),
            ("Blake2s", False),
        ]

        for algo_name, is_checked in algorithms:
            radio_button = QRadioButton(_translation_manager.tr(algo_name))
            radio_button.setChecked(is_checked)
            setattr(self, f"m_rb{algo_name}", radio_button)
            algo_layout.addWidget(radio_button)

        algo_layout.addStretch()

        # Right panel - Comparison and Results with extreme compact spacing
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)
        right_layout.setSpacing(6)  # 极致压缩右侧面板间距

        # Comparison section
        compare_group = QGroupBox(_translation_manager.tr("comparison"))
        compare_group.setObjectName("comparisonGroup")
        compare_layout = QVBoxLayout(compare_group)
        compare_layout.setSpacing(8)
        compare_layout.setContentsMargins(12, 12, 12, 12)

        self.m_cbEnableCompare = QCheckBox(_translation_manager.tr("enable_comparison"))
        self.m_leCompare = QLineEdit()
        self.m_leCompare.setPlaceholderText("Enter expected checksum...")
        self.m_leCompare.setEnabled(False)

        compare_layout.addWidget(self.m_cbEnableCompare)
        compare_layout.addWidget(self.m_leCompare)

        # Results section
        result_group = QGroupBox(_translation_manager.tr("checksum_result"))
        result_group.setObjectName("resultGroup")
        result_layout = QVBoxLayout(result_group)
        result_layout.setContentsMargins(12, 12, 12, 12)

        self.m_teChecksum = QTextEdit()
        self.m_teChecksum.setReadOnly(True)
        self.m_teChecksum.setMinimumWidth(500)
        self.m_teChecksum.setMinimumHeight(150)
        self.m_teChecksum.setPlaceholderText("Calculated checksum will appear here...")

        result_layout.addWidget(self.m_teChecksum)

        # Assemble layout
        right_layout.addWidget(compare_group)
        right_layout.addWidget(result_group)
        right_layout.addStretch()

        content_layout.addWidget(algo_panel)
        content_layout.addWidget(right_panel, 1)

        # Add everything to main layout
        main_layout.addWidget(data_group)
        main_layout.addWidget(content_area, 1)

        # Store algorithm buttons mapping
        self.algorithm_buttons: dict[str, QRadioButton] = {
            "MD5": self.m_rbMD5,
            "SHA1": self.m_rbSHA1,
            "SHA256": self.m_rbSHA256,
            "SHA384": self.m_rbSHA384,
            "SHA512": self.m_rbSHA512,
            "Blake2b": self.m_rbBlake2b,
            "Blake2s": self.m_rbBlake2s,
        }

        # Store group box references for dynamic title updates
        self.group_boxes: dict[str, QGroupBox] = {
            "data_source": data_group,
            "algorithm": algo_panel,
            "comparison": compare_group,
            "checksum_result": result_group,
        }

    def _apply_styles(self) -> None:
        """Apply integrated QSS styles to the dialog."""
        try:
            self.setStyleSheet(_CHECKSUM_STYLESHEET)
        except Exception as e:
            logger.warning(f"Failed to apply styles: {e}")

    def _add_language_selector(self) -> None:
        """Add language selection combobox with label to the dialog."""
        # Create horizontal layout for language selector with minimal height
        language_layout = LayoutFactory.create_compact_layout(
            spacing=_UI_CONSTANTS["COMPACT_SPACING"],
            margins=(0, _UI_CONSTANTS["MIN_MARGIN"], 0, _UI_CONSTANTS["MIN_MARGIN"]),
        )

        # Create language label and store reference for updates
        self.language_label = QLabel(_translation_manager.tr("language"))
        self.language_label.setStyleSheet(f"font-weight: bold; font-size: {_UI_CONSTANTS['FONT_SIZE_SMALL']}px;")

        # Create language selector
        self.language_combo = QComboBox()
        self.language_combo.setMinimumWidth(_UI_CONSTANTS["LANGUAGE_COMBO_WIDTH"])
        self.language_combo.setMinimumHeight(_UI_CONSTANTS["BUTTON_HEIGHT"])
        self.language_combo.setStyleSheet("padding: 2px 4px;")  # 优化内边距
        for lang_code, lang_name in _translation_manager.get_available_languages():
            self.language_combo.addItem(lang_name, lang_code)

        # Set default to Chinese
        self.language_combo.setCurrentIndex(0)  # Chinese is first
        self.language_combo.currentIndexChanged.connect(self._change_language)

        # Add widgets to layout
        language_layout.addWidget(self.language_label)
        language_layout.addWidget(self.language_combo)
        language_layout.addStretch()  # Push to left side

        # Add to main layout
        main_layout = self.layout()
        if main_layout:
            # Insert language selector at the top
            main_layout.insertLayout(0, language_layout)

    def _change_language(self, index: int) -> None:
        """Change UI language and update all text elements."""
        # Get selected language
        lang_code = self.language_combo.itemData(index)
        if lang_code == Language.CHINESE.value:
            _translation_manager.set_language(Language.CHINESE)
        else:
            _translation_manager.set_language(Language.ENGLISH)

        # Update all UI elements
        self._update_ui_text()

    def _update_ui_text(self) -> None:
        """Update all UI text elements to current language with optimized bulk updates."""
        # Bulk update operations for better performance
        tr = _translation_manager.tr  # Cache translation function

        # Update window title
        self.setWindowTitle(tr("window_title"))

        # Update group box titles
        self._update_group_box_titles()

        # Update language selector label
        if hasattr(self, "language_label"):
            self.language_label.setText(tr("language"))

        # Update button texts with bulk assignment
        button_updates = {
            self.m_pbGenerateString: tr("calculate_checksum"),
            self.m_pbOpenFile: tr("browse"),
            self.m_pbGenerateFile: tr("calculate_checksum"),
        }
        for button, text in button_updates.items():
            button.setText(text)

        # Update checkbox text
        self.m_cbEnableCompare.setText(tr("enable_comparison"))

        # Update static labels
        self._update_static_labels()

        # Update algorithm radio buttons with bulk assignment
        algorithm_updates = {
            self.m_rbMD5: tr("MD5"),
            self.m_rbSHA1: tr("SHA1"),
            self.m_rbSHA256: tr("SHA256"),
            self.m_rbSHA384: tr("SHA384"),
            self.m_rbSHA512: tr("SHA512"),
            self.m_rbBlake2b: tr("Blake2b"),
            self.m_rbBlake2s: tr("Blake2s"),
        }
        for button, text in algorithm_updates.items():
            button.setText(text)

    def _update_group_box_titles(self) -> None:
        """Update all group box titles to current language with streamlined logic."""
        # Direct bulk update without redundant condition checks
        if hasattr(self, "group_boxes"):
            tr = _translation_manager.tr
            for key, group_box in self.group_boxes.items():
                group_box.setTitle(tr(key))

    def _update_static_labels(self) -> None:
        """Update static labels in the UI by traversing widget hierarchy."""
        # Store label references during creation for easier updating
        if not hasattr(self, "_static_labels"):
            self._static_labels = {}
            self._find_and_store_labels()

        # Update stored labels
        for key, label in self._static_labels.items():
            if key == "input_string":
                label.setText(_translation_manager.tr("input_string"))
            elif key == "input_file":
                label.setText(_translation_manager.tr("input_file"))

    def _find_and_store_labels(self) -> None:
        """Find and store references to static labels in the UI."""
        # Traverse the widget hierarchy to find our static labels
        data_group = self.findChild(QGroupBox)
        if data_group:
            # Find labels within data source group
            for child in data_group.findChildren(QLabel):
                if child.text() in [
                    "输入字符串",
                    "Input String",
                    "输入文件",
                    "Input File",
                ]:
                    if "字符" in child.text() or "String" in child.text():
                        self._static_labels["input_string"] = child
                    elif "文件" in child.text() or "File" in child.text():
                        self._static_labels["input_file"] = child

    def _init_ui(self) -> None:
        """Initialize user interface connections with modern event handling."""
        # Connect algorithm radio buttons
        for radio_button in self.algorithm_buttons.values():
            radio_button.toggled.connect(self._on_algorithm_changed)

        # Initialize comparison feature with enhanced logic
        self.enable_comparison: bool = False
        self.m_cbEnableCompare.setChecked(False)
        self.m_cbEnableCompare.toggled.connect(self._toggle_comparison)
        self.m_leCompare.textChanged.connect(self._on_comparison_text_changed)

        # Connect action buttons with modern signal handling
        self.m_pbGenerateString.clicked.connect(self._generate_string_checksum)
        self.m_pbOpenFile.clicked.connect(self._open_file_dialog)
        self.m_pbGenerateFile.clicked.connect(self._generate_file_checksum)

        # Add placeholder text updates
        self.m_leString.textChanged.connect(self._update_string_placeholder)
        self.m_leFile.textChanged.connect(self._update_file_placeholder)

    def _toggle_comparison(self) -> None:
        """Toggle checksum comparison feature with enhanced UX."""
        self.enable_comparison = self.m_cbEnableCompare.isChecked()
        self.m_leCompare.setEnabled(self.enable_comparison)
        if not self.enable_comparison:
            self.m_leCompare.clear()

    def _on_comparison_text_changed(self, text: str) -> None:
        """Handle comparison text changes for real-time validation."""
        # Could add real-time validation here if needed
        pass

    def _update_string_placeholder(self, text: str) -> None:
        """Update string input placeholder based on content."""
        if text:
            self.m_leString.setPlaceholderText("")
        else:
            self.m_leString.setPlaceholderText(_translation_manager.tr("input_string"))

    def _update_file_placeholder(self, text: str) -> None:
        """Update file input placeholder based on content."""
        if text:
            self.m_leFile.setPlaceholderText("")
        else:
            self.m_leFile.setPlaceholderText(_translation_manager.tr("input_file"))

    def _on_algorithm_changed(self) -> None:
        """Handle hash algorithm selection change."""
        for algorithm_name, radio_button in self.algorithm_buttons.items():
            if radio_button.isChecked():
                try:
                    # Map UI algorithm names to HashAlgorithm enum members
                    algorithm_mapping = {
                        "MD5": HashAlgorithm.MD5,
                        "SHA1": HashAlgorithm.SHA1,
                        "SHA256": HashAlgorithm.SHA256,
                        "SHA384": HashAlgorithm.SHA384,
                        "SHA512": HashAlgorithm.SHA512,
                        "Blake2b": HashAlgorithm.BLAKE2B,
                        "Blake2s": HashAlgorithm.BLAKE2S,
                    }

                    if algorithm_name in algorithm_mapping:
                        algorithm = algorithm_mapping[algorithm_name]
                        self.calculator.set_algorithm(algorithm)
                    else:
                        logger.error(f"Unknown hash algorithm: {algorithm_name}")
                    break
                except Exception as e:
                    logger.error(f"Error setting algorithm {algorithm_name}: {e}")

    def _generate_string_checksum(self) -> None:
        """Generate checksum for input string."""
        content = self.m_leString.text()
        if not content.strip():
            self.m_teChecksum.setText(_translation_manager.tr("please_enter_string"))
            return

        try:
            hash_value = self.calculator.calculate_string_checksum(content)
            result_text = hash_value

            # Add comparison result if enabled
            if self.enable_comparison:
                expected = self.m_leCompare.text().strip()
                if not expected:
                    self.m_teChecksum.setText(_translation_manager.tr("please_enter_comparison"))
                    return

                is_match = self.calculator.verify_checksum(hash_value, expected)
                verification_msg = (
                    _translation_manager.tr("verification_passed")
                    if is_match
                    else _translation_manager.tr("verification_failed")
                )
                result_text += f"\n{verification_msg}"

            self.m_teChecksum.setText(result_text)
        except Exception as e:
            logger.error(f"Failed to calculate string checksum: {e}")
            self.m_teChecksum.setText(f"Error: {e!s}")

    def _open_file_dialog(self) -> None:
        """Open file selection dialog."""
        dialog = QFileDialog()
        filename, _ = dialog.getOpenFileName(
            self,
            _translation_manager.tr("select_file"),
            QDir.currentPath(),
            _translation_manager.tr("all_files"),
        )

        if filename:
            self.current_file_path = filename
            self.m_leFile.setText(filename)

    def _generate_file_checksum(self) -> None:
        """Generate checksum for selected file."""
        if not self.current_file_path or not Path(self.current_file_path).exists():
            self.m_teChecksum.setText("Please select a valid file")
            return

        try:
            file_path = Path(self.current_file_path)
            hash_value = self.calculator.calculate_file_checksum(file_path)
            result_text = hash_value

            # Add comparison result if enabled
            if self.enable_comparison:
                expected = self.m_leCompare.text().strip()
                if not expected:
                    self.m_teChecksum.setText("Please enter comparison value")
                    return

                is_match = self.calculator.verify_checksum(hash_value, expected)
                result_text += f"\nVerification: {'PASSED' if is_match else 'FAILED'}"

            self.m_teChecksum.setText(result_text)
        except Exception as e:
            logger.error(f"Failed to calculate file checksum: {e}")
            self.m_teChecksum.setText(f"Error: {e!s}")


def parse_cli_arguments() -> argparse.Namespace:
    """Parse command line arguments for checksum tool."""
    parser = argparse.ArgumentParser(
        description="Calculate and verify file/string checksums",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  checksum --algorithm sha256 --string "hello world"
  checksum --algorithm md5 --file document.pdf
  checksum --algorithm sha256 --file data.zip --compare "expected_hash_value"
        """,
    )

    parser.add_argument(
        "--algorithm",
        "-a",
        choices=[alg.value for alg in HashAlgorithm],
        default=HashAlgorithm.MD5.value,
        help="Hash algorithm to use (default: md5)",
    )

    input_group = parser.add_mutually_exclusive_group(required=True)
    input_group.add_argument("--string", "-s", help="Calculate checksum for string content")
    input_group.add_argument("--file", "-f", type=Path, help="Calculate checksum for file")

    parser.add_argument("--compare", "-c", help="Verify calculated checksum against expected value")

    parser.add_argument("--gui", action="store_true", help="Launch graphical user interface")

    return parser.parse_args()


def run_cli_mode(args: argparse.Namespace) -> int:
    """Run checksum tool in command line mode."""
    try:
        # Initialize calculator
        algorithm = HashAlgorithm(args.algorithm)
        config = ChecksumConfig(default_algorithm=algorithm)
        calculator = ChecksumCalculator(config)

        # Calculate checksum
        if args.string is not None:
            result = calculator.calculate_string_checksum(args.string)
            input_desc = f'string "{args.string}"'
        elif args.file is not None:
            if not args.file.exists():
                print(f"Error: File not found: {args.file}")
                return 1
            result = calculator.calculate_file_checksum(args.file)
            input_desc = f'file "{args.file}"'
        else:
            print("Error: Either --string or --file must be specified")
            return 1

        # Output result
        print(f"Algorithm: {algorithm.value.upper()}")
        print(f"Input: {input_desc}")
        print(f"Checksum: {result}")

        # Verify if comparison requested
        if args.compare:
            is_valid = calculator.verify_checksum(result, args.compare)
            print(f"Verification: {'PASSED' if is_valid else 'FAILED'}")
            return 0 if is_valid else 1

        return 0

    except Exception as e:
        print(f"Error: {e}")
        return 1


def gui_main() -> int:
    """Run checksum tool in graphical user interface mode."""
    try:
        app = QApplication(sys.argv)
        window = ChecksumDialog()
        window.show()
        return app.exec_()
    except Exception as e:
        print(f"Error launching GUI: {e}")
        return 1


def main() -> None:
    """Run main entry point for checksum tool."""
    args = parse_cli_arguments()

    if args.gui:
        sys.exit(gui_main())
    else:
        sys.exit(run_cli_mode(args))


# Multi-language support
class Language(Enum):
    """Supported languages."""

    CHINESE = "zh"
    ENGLISH = "en"


class TranslationManager:
    """Manage UI translations."""

    def __init__(self) -> None:
        """Initialize translation manager with default Chinese."""
        self.current_language = Language.CHINESE
        self.translations = self._load_translations()

    def _load_translations(self) -> dict[str, dict[str, str]]:
        """Load translation dictionaries."""
        return {
            Language.CHINESE.value: {
                # Window title
                "window_title": "校验和计算器 v1.0",
                # Language selector
                "language": "语言",
                # Group box titles
                "data_source": "数据源",
                "algorithm": "算法",
                "comparison": "比较",
                "checksum_result": "校验和结果",
                # Labels
                "input_string": "输入字符串",
                "input_file": "输入文件",
                # Buttons
                "calculate_checksum": "计算校验和",
                "browse": "浏览",
                "enable_comparison": "启用比较",
                # Algorithm names (keep English as they are technical terms)
                "MD5": "MD5",
                "SHA1": "SHA1",
                "SHA256": "SHA256",
                "SHA384": "SHA384",
                "SHA512": "SHA512",
                "Blake2b": "Blake2b",
                "Blake2s": "Blake2s",
                # Messages
                "please_enter_string": "请输入字符串内容",
                "please_enter_comparison": "请输入比较值",
                "select_file": "选择文件",
                "verification_passed": "验证通过",
                "verification_failed": "验证失败",
                "all_files": "所有文件 (*.*)",
            },
            Language.ENGLISH.value: {
                # Window title
                "window_title": "Checksum Calculator v1.0",
                # Language selector
                "language": "Language",
                # Group box titles
                "data_source": "Data Source",
                "algorithm": "Algorithm",
                "comparison": "Comparison",
                "checksum_result": "Checksum Result",
                # Labels
                "input_string": "Input String",
                "input_file": "Input File",
                # Buttons
                "calculate_checksum": "Calculate Checksum",
                "browse": "Browse",
                "enable_comparison": "Enable Comparison",
                # Algorithm names
                "MD5": "MD5",
                "SHA1": "SHA1",
                "SHA256": "SHA256",
                "SHA384": "SHA384",
                "SHA512": "SHA512",
                "Blake2b": "Blake2b",
                "Blake2s": "Blake2s",
                # Messages
                "please_enter_string": "Please enter string content",
                "please_enter_comparison": "Please enter comparison value",
                "select_file": "Select file",
                "verification_passed": "Verification: PASSED",
                "verification_failed": "Verification: FAILED",
                "all_files": "All files (*.*)",
            },
        }

    def set_language(self, language: Language) -> None:
        """Set current language."""
        self.current_language = language

    def tr(self, key: str) -> str:
        """Translate key to current language."""
        return self.translations[self.current_language.value].get(key, key)

    def get_available_languages(self) -> list[tuple[str, str]]:
        """Get available languages for UI display."""
        return [
            (Language.CHINESE.value, "中文"),
            (Language.ENGLISH.value, "English"),
        ]


# Global translation manager
_translation_manager = TranslationManager()
