"""
Translations for the Excel Filter GUI
Supports English and German languages using JSON files for better maintainability
"""

import json
import os
from pathlib import Path

class Translations:
    """
    Translation manager for the Excel Filter GUI
    Loads translations from JSON files for better maintainability and collaboration
    """

    def __init__(self, language="de"):
        """
        Initialize translations with default language

        Args:
            language: Default language code ('en' or 'de')
        """
        self.current_language = language
        self.translations = {}

        # Load translations from JSON files
        self.load_translations()

    def load_translations(self):
        """
        Load translation files from the locales directory
        """
        import sys
        # Determine the base path for resources
        if getattr(sys, 'frozen', False):
            # If the application is run as a bundle, the PyInstaller bootloader
            # extends the sys module by a flag frozen=True and sets the app 
            # path into variable _MEIPASS'.
            base_path = Path(sys._MEIPASS)
        else:
            base_path = Path(__file__).parent

        locales_dir = base_path / "locales"

        # Create locales directory if it doesn't exist and we are not frozen
        # (cannot create files in _MEIPASS usually, or it's temporary)
        if not getattr(sys, 'frozen', False):
            locales_dir.mkdir(exist_ok=True)

        # Load each language file
        for lang_code in ["en", "de"]:
            lang_file = locales_dir / f"{lang_code}.json"
            if lang_file.exists():
                try:
                    with open(lang_file, 'r', encoding='utf-8') as f:
                        self.translations[lang_code] = json.load(f)
                except Exception as e:
                    print(f"Error loading {lang_file}: {e}")
                    self.translations[lang_code] = {}
            else:
                # Create default language file if it doesn't exist
                self.create_default_translations(lang_code, lang_file)

    def create_default_translations(self, lang_code, lang_file):
        """
        Create default translation files
        """
        if lang_code == "en":
            translations = self.get_english_translations()
        else:
            translations = self.get_german_translations()

        self.translations[lang_code] = translations

        # Save to file
        try:
            with open(lang_file, 'w', encoding='utf-8') as f:
                json.dump(translations, f, indent=2, ensure_ascii=False)
        except Exception as e:
            print(f"Error creating {lang_file}: {e}")

    def get_english_translations(self):
        """
        Get default English translations
        """
        return {
            "app_title": "Excel Filter Tool",
            "tab_config": "Configuration",
            "tab_execution": "Execution",
            "tab_regex_builder": "Regex Builder",
            "tab_help": "Help",
            "config_section": "Configuration",
            "load_button": "Load",
            "save_button": "Save",
            "input_file": "Input file:",
            "output_file": "Output file:",
            "browse_button": "Browse...",
            "worksheet": "Worksheet:",
            "process_button": "🚀 PROCESS",
            "status_ready": "Ready",
            "success": "Success",
            "error": "Error",
            "language": "Language:",
            "english": "English",
            "german": "German",
            "help_content": "\nExcel Filter Tool\n\nFUNCTION\n--------------------------\nThe Excel Filter Tool is a data analysis and filtering tool for Excel files.\nIt enables automatic extraction, filtering, and transformation of data based on configurable search criteria.\n\nMain features:\n• Intelligent text search using regex patterns\n• Numeric filtering (greater/less than, between values)\n• Column-based filtering\n\nWORKFLOW\n----------------------------------------\nThe workflow is divided into four main phases, each with its own tabs:\n\n1. CONFIGURATION\n- Select the input Excel file\n- Specify the output file\n- Select the worksheet to filter\n- Configure filter criteria (regex and/or numeric)\n- Select columns to be included\n- Save/load configurations for recurring tasks\n\n2. PATTERN CREATION (Regex-Builder Tab)\n- Use the visual regex builder for easy pattern creation\n- Select from predefined components (text, numbers, special characters)\n- Define quantities (once, multiple times, optional)\n- Add optional anchors and groups\n- Test patterns with sample texts\n- Manage stored patterns\n\n3. EXECUTION\n- Review the command to execute before processing\n- Start the analysis\n- Track progress in real time\n- Automatic opening of the result file\n\nADVANCED CONFIGURATION OPTIONS\n----------------------------------\n\nRegex Filtering (Standard Mode)\n- Search for text patterns with full regex support\n- Support for complex search patterns\n- Word boundaries, case sensitivity, special characters\n\nNumeric Filtering\n- Filter by numeric values (greater/less than)\n- Range filtering (between values)\n- Cross-column numeric search\n\nColumn-Based Filtering\n- Selection of specific columns to search\n- Automatic column detection from Excel files\n- Individual column selection for targeted search\n\nCONFIGURATION MANAGEMENT\n--------------------------\n• Save/load configurations for recurring tasks\n• Personal pattern library with custom regex patterns\n• Automatic saving of recently used file paths\n• Restoration of previous work sessions\n",
            
            # Config Tab
            "tooltip_config_section": "You can save and load configurations instead of entering everything every time.",
            "enable_regex": "Enable Regex Filter",
            "tooltip_enable_regex": "If enabled, regex patterns are used for filtering",
            "regex_options": " Regex Options ",
            "regex_pattern": "Regex Pattern:",
            "preset_patterns": "Preset Patterns:",
            "apply_regex_column": "Apply Regex to Column:",
            "all_columns": "All Columns",
            "manage_patterns": "Manage Patterns...",
            "enable_numeric": "Enable Numeric Filter",
            "numeric_filters": "Numeric Filters",
            "column": "Column:",
            "comparison": "Comparison:",
            "value": "Value:",
            "regex_builder_info": "Custom patterns for filtering can be created in the Regex Builder.",
            "enable_column_selection": "Enable Column Selection",
            "column_selection": "Column Selection",
            "select_all": "Select All",
            "deselect_all": "Deselect All",
            "proceed_to_execution": "Proceed to Execution",
            "msg_no_regex_copy": "No regex pattern used - only selected columns will be copied",
            "msg_warn_no_selection": "Warning: No regex pattern and no columns selected - all data will be copied",
            "msg_copy_all": "Copying all columns",
            "msg_copy_selected": "Copying selected columns: {}",
            "msg_written_success": "Successfully written: {}",
            "msg_ask_open": "Do you want to open the output file?",
            "msg_process_success": "Processing completed successfully",
            "msg_process_failed": "Processing failed",
            "numeric_invalid": "❌ Invalid numeric value",
            "numeric_incomplete": "Configuration incomplete",
            "filter_desc": "Filter: {} {} {}",

            # Execution Tab
            "ready_to_execute": "Ready to execute...",
            "status_ready": "Ready",
            "command_to_execute": "Command to Execute",
            "execute_button": "EXECUTE",
            "activity_log": "Activity Log",
            "clear_log": "Clear",
            "save_log": "Save",
            "log_cleared": "Log cleared",
            "ready_for_execution": "Excel Filter ready for execution",
            "configure_and_execute": "Configure settings and click 'EXECUTE'",
            "error_main_gui_not_connected": "Error: Main GUI not connected",
            "input_file_label": "Input File:",
            "output_file_label": "Output File:",
            "search_pattern_label": "Search Pattern:",
            "worksheet_label": "Worksheet:",
            "columns_label": "Columns:",
            "numeric_filter_label": "Numeric Filter: {column} {operator} {value}",
            "not_selected": "(not selected)",
            "not_specified": "(not specified)",
            "more_columns": "(+{} more)",
            "error_updating_command_display": "Error updating command display: {error}",
            "execution_running": "Running...",
            "waiting": "WAITING...",
            "execution_started": "▶️ Execution started",
            "execution_completed": "✅ Execution completed successfully",
            "execution_failed": "❌ Execution failed with errors",
            "log_saved": "💾 Log saved: {file}",

            # Regex Builder Tab
            "tab_builder": "🧱 Block Builder",
            "tab_tester": "🧪 Tester",
            "tab_examples": "📚 Examples",
            "step_1": "📝 Step 1: Search Character",
            "step_2": "🔢 Step 2: How often?",
            "step_3": "⚙️ Step 3: Options",
            "btn_letters": "🔤 Letters",
            "desc_letters": "a-z, A-Z",
            "btn_digits": "🔢 Digits",
            "desc_digits": "0-9",
            "btn_alphanum": "🔤🔢 Alphanum.",
            "desc_alphanum": "Letters+Digits",
            "btn_any": "❓ Any",
            "desc_any": "Any Character",
            "btn_custom": "📝 Custom Text",
            "desc_custom": "Your Text",
            "btn_special": "⚙️ Special",
            "desc_special": "Punctuation",
            "btn_once": "🎯 1-time",
            "desc_once": "Exactly once",
            "btn_one_plus": "➕ 1+ times",
            "desc_one_plus": "At least 1-time",
            "btn_zero_one": "❓ 0-1 times",
            "desc_zero_one": "Optional",
            "btn_zero_plus": "♾️ 0+ times",
            "desc_zero_plus": "Any number of times",
            "btn_n_times": "📏 N-times",
            "desc_n_times": "Exactly N-times",
            "btn_m_n_times": "📊 M-N times",
            "desc_m_n_times": "M to N-times",
            "btn_start": "^ Start",
            "desc_start": "Line start",
            "btn_end": "$ End",
            "desc_end": "Line end",
            "btn_word": "\\b Word",
            "desc_word": "Word boundary",
            "btn_group": "( ) Group",
            "desc_group": "Grouping",
            "btn_or": "| OR",
            "desc_or": "Alternative",
            "btn_alt": "(?: ) Alt.",
            "desc_alt": "Non-capturing group",
            "preview": "👀 Preview",
            "selection": "Selection:",
            "btn_add": "➕ Add",
            "btn_reset": "🔄 Reset",
            "regex_result": "🎯 Regex Pattern",
            "btn_manage": "📝 Manage Patterns",
            "btn_save_preset": "💾 Save as Pattern",
            "btn_copy": "📋 Copy",
            "btn_reset_pattern": "🔄 Reset Pattern",
            "btn_undo": "↶ Undo",
            "btn_redo": "↷ Redo",
            "btn_apply": "💾 Apply to Main",
            "btn_test": "🧪 Test",
            "test_input": "Enter Test Text:",
            "test_text_frame": "📝 Test Text",
            "test_pattern_frame": "🔍 Regex Pattern",
            "btn_load_example": "📋 Load Example",
            "result_label": "Result:",
            "matches_label": "Found Matches:",
            "common_examples": "📚 Common Regex Examples",
            "msg_pattern_applied": "Regex pattern applied to main window!",
            "msg_main_not_avail": "Main window reference not available. Copy pattern manually.",
            "msg_no_pattern_apply": "No regex pattern available to apply",
            "msg_copied": "Regex pattern copied to clipboard!",
            "msg_no_pattern_copy": "No regex pattern available to copy",
            "msg_no_undo": "No more undo actions available",
            "msg_no_redo": "No more redo actions available",
            "msg_enter_pattern": "❌ Please enter a regex pattern",
            "msg_enter_text": "❌ Please enter a test text",
            "msg_pattern_found": "✅ Pattern found! {} matches ({} unique)",
            "msg_no_matches": "❌ No matches found",
            "msg_invalid_regex": "❌ Invalid regex pattern: {}",
            "msg_example_loaded": "Example loaded - click 'Test'",
            "builder_desc_letters": "Letters (a-z, A-Z)",
            "builder_desc_digits": "Digits (0-9)",
            "builder_desc_alphanum": "Letters and Digits",
            "builder_desc_any": "Any character",
            "builder_desc_custom": "The text: '{}'",
            "builder_desc_custom_generic": "Your custom text",
            "builder_desc_special": "Special characters (space, dot, comma, etc.)",
            "builder_desc_once": "appears exactly once",
            "builder_desc_one_plus": "appears once or more",
            "builder_desc_zero_one": "is optional (0 or 1 time)",
            "builder_desc_zero_plus": "appears any number of times (0 or more)",
            "builder_desc_n_times": "appears exactly {} times",
            "builder_desc_m_n_times": "appears {} to {} times",
            "builder_desc_start": "at line start",
            "builder_desc_end": "at line end",
            "builder_desc_word": "as whole word",
            "builder_desc_or": "with alternatives",
            "default_test_text": "Sample text with error and warning 123 numbers and email: test@example.com",
            "default_result": "Test result appears here...",
            "no_matches": "No matches",
            "auto_desc": "Description automatically generated...",
            "select_char_first": "Select a character type first...",
            "enter_name": "Enter name",
            "save_pattern": "Save Pattern",
            "name_for_pattern": "Name for new pattern:",
            "msg_save_success": "Pattern '{}' saved successfully",
            "overwrite_confirm": "Pattern '{}' already exists. Overwrite?",
            
            # Additional keys needed for gui_new.py
            "errors_and_warnings": "Errors and Warnings",
            "errors_only": "Errors only",
            "warnings_only": "Warnings only",
            "critical_errors": "Critical Errors",
            "numbers_100_199": "Numbers 100-199",
            "email_addresses": "E-mail addresses",
            "phone_numbers": "Phone numbers (DE)",
            "date_yyyy_mm_dd": "Date (YYYY-MM-DD)",
            
            "desc_errors_and_warnings": "Finds 'error', 'warning' or 'critical'",
            "desc_errors_only": "Finds 'error'",
            "desc_warnings_only": "Finds 'warning'",
            "desc_critical_errors": "Finds 'critical'",
            "desc_numbers_100_199": "Finds numbers from 100 to 199",
            "desc_email_addresses": "Finds standard e-mail addresses",
            "desc_phone_numbers": "Finds phone numbers (German format)",
            "desc_date_yyyy_mm_dd": "Finds dates in ISO format",
        }

    def get_german_translations(self):
        """
        Get default German translations
        """
        return {
            "app_title": "Excel Filter Tool",
            "tab_config": "Konfiguration",
            "tab_execution": "Ausführung",
            "tab_regex_builder": "Regex-Builder",
            "tab_help": "Hilfe",
            "config_section": "Konfiguration",
            "load_button": "Laden",
            "save_button": "Speichern",
            "input_file": "Eingabedatei:",
            "output_file": "Ausgabedatei:",
            "browse_button": "Durchsuchen...",
            "worksheet": "Arbeitsblatt:",
            "process_button": "🚀 VERARBEITEN",
            "status_ready": "Bereit",
            "success": "Erfolg",
            "error": "Fehler",
            "language": "Sprache:",
            "english": "Englisch",
            "german": "Deutsch",
            "help_content": "\nExcel Filter Tool\n\nFUNKTION\n--------------------------\nDas Excel Filter Tool ist ein Werkzeug zur Datenanalyse und -filterung von Excel-Dateien.\nEs ermöglicht das automatische Extrahieren, Filtern und Transformieren von Daten basierend auf einstellbaren Suchkriterien.\n\nHauptfunktionen:\n• Intelligente Textsuche anhand von Regex-Mustern\n• Numerische Filterung (größer/kleiner als, zwischen Werten)\n• Spaltenbasierte Filterung\n\nARBEITSABLAUF\n----------------------------------------\nDer Arbeitsablauf ist in vier Hauptphasen unterteilt, die jeweils eigene Tabs haben:\n\n1. KONFIGURATION\n- Wähle die Eingabe-Excel-Datei aus\n- Bestimme die Ausgabedatei\n- Wähle das zu filternde Arbeitsblatt\n- Konfiguriere die Filterkriterien (Regex und/oder numerisch)\n- Wählen die Spalten aus, welche übernommen werden sollen\n- Speicher/Lade die Konfigurationen für wiederkehrende Aufgaben\n\n2. MUSTER-ERSTELLUNG (Regex-Builder-Tab)\n- Nutze den visuellen Regex-Builder für zur einfachen Mustererstellung\n- Wähle aus vorgefertigten Bausteinen (Text, Zahlen, Spezialzeichen)\n- Definiere Mengen (einmal, mehrmals, optional)\n- Füge optionale Anker und Gruppen hinzu\n- Teste die Muster mit Beispieltexten\n- Verwalte gespeicherte Muster\n\n3. AUSFÜHRUNG\n- Überprüfe den auszuführenden Befehl vor der Verarbeitung\n- Starten die Analyse\n- Verfolgen den Fortschritt in Echtzeit\n- Automatische Öffnung der Ergebnisdatei\n\nERWEITERTE KONFIGURATIONSOPTIONEN\n----------------------------------\n\nRegex-Filterung (Standardmodus)\n- Suche nach Textmustern mit voller Regex-Unterstützung\n- Unterstützung für komplexe Suchmuster\n- Wortgrenzen, Groß-/Kleinschreibung, Spezialzeichen\n\nNumerische Filterung\n- Filtern nach Zahlenwerten (größer/kleiner als)\n- Bereichsfilterung (zwischen Werten)\n- Spaltenübergreifende numerische Suche\n\nSpaltenbasierte Filterung\n- Auswahl spezifischer zu durchsuchender Spalten\n- Automatische Spaltenerkennung aus Excel-Dateien\n- Individuelle Spaltenauswahl für zielgerichtete Suche\n\nKONFIGURATIONSMANAGEMENT\n--------------------------\n• Speichern/Laden von Konfigurationen für wiederkehrende Aufgaben\n• Persönliche Musterbibliothek mit benutzerdefinierten Regex-Mustern\n• Automatische Speicherung von zuletzt verwendeten Dateipfaden\n• Wiederherstellung vorheriger Arbeitssitzungen\n",
            
            # Config Tab
            "tooltip_config_section": "Du kannst Konfigurationen speichern und laden, statt alles jedes Mal neu einzugeben.",
            "enable_regex": "Regex-Filter aktivieren",
            "tooltip_enable_regex": "Wenn aktiviert, werden Regex-Muster für die Filterung verwendet",
            "regex_options": " Regex-Optionen ",
            "regex_pattern": "Regex-Muster:",
            "preset_patterns": "Voreingestellte Muster:",
            "apply_regex_column": "Regex auf Spalte anwählen:",
            "all_columns": "Alle Spalten",
            "manage_patterns": "Muster verwalten…",
            "enable_numeric": "Numerische Filter aktivieren",
            "numeric_filters": "Numerische Filter",
            "column": "Spalte:",
            "comparison": "Vergleich:",
            "value": "Wert:",
            "regex_builder_info": "Eigene Muster zur Filterung können im Regex-Builder erstellt werden.",
            "enable_column_selection": "Spaltenauswahl aktivieren",
            "column_selection": "Spaltenauswahl",
            "select_all": "Alle auswählen",
            "deselect_all": "Alle abwählen",
            "proceed_to_execution": "Weiter zur Ausführung",
            "msg_no_regex_copy": "Kein Regex-Muster verwendet - es werden nur die ausgewählten Spalten kopiert",
            "msg_warn_no_selection": "Warnung: Kein Regex-Muster und keine Spalten ausgewählt - alle Daten werden kopiert",
            "msg_copy_all": "Kopiere alle Spalten",
            "msg_copy_selected": "Kopiere ausgewählte Spalten: {}",
            "msg_written_success": "Erfolgreich geschrieben: {}",
            "msg_ask_open": "Möchten Sie die Ausgabedatei öffnen?",
            "msg_process_success": "Verarbeitung erfolgreich abgeschlossen",
            "msg_process_failed": "Verarbeitung fehlgeschlagen",
            "numeric_invalid": "❌ Ungültiger numerischer Wert",
            "numeric_incomplete": "Konfiguration unvollständig",
            "filter_desc": "Filter: {} {} {}",

            # Execution Tab
            "ready_to_execute": "Bereit zur Ausführung...",
            "status_ready": "Bereit",
            "command_to_execute": "Auszuführender Befehl",
            "execute_button": "AUSFÜHREN",
            "activity_log": "Aktivitätsprotokoll",
            "clear_log": "Löschen",
            "save_log": "Speichern",
            "log_cleared": "Protokoll gelöscht",
            "ready_for_execution": "Excel Filter bereit zur Ausführung",
            "configure_and_execute": "Konfigurieren Sie die Einstellungen und klicken Sie auf 'AUSFÜHREN'",
            "error_main_gui_not_connected": "Fehler: Haupt-GUI nicht verbunden",
            "input_file_label": "Eingabedatei:",
            "output_file_label": "Ausgabedatei:",
            "search_pattern_label": "Suchmuster:",
            "worksheet_label": "Arbeitsblatt:",
            "columns_label": "Spalten:",
            "numeric_filter_label": "Numerischer Filter: {column} {operator} {value}",
            "not_selected": "(nicht ausgewählt)",
            "not_specified": "(nicht angegeben)",
            "more_columns": "(+{} weitere)",
            "error_updating_command_display": "Fehler beim Aktualisieren der Befehlsanzeige: {error}",
            "execution_running": "Läuft...",
            "waiting": "WARTEN...",
            "execution_started": "▶️ Ausführung gestartet",
            "execution_completed": "✅ Ausführung erfolgreich abgeschlossen",
            "execution_failed": "❌ Ausführung mit Fehlern beendet",
            "log_saved": "💾 Protokoll gespeichert: {file}",

            # Regex Builder Tab
            "tab_builder": "🧱 Baustein-Builder",
            "tab_tester": "🧪 Tester",
            "tab_examples": "📚 Beispiele",
            "step_1": "📝 Schritt 1: Zeichen suchen",
            "step_2": "🔢 Schritt 2: Wie oft?",
            "step_3": "⚙️ Schritt 3: Optionen",
            "btn_letters": "🔤 Buchstaben",
            "desc_letters": "a-z, A-Z",
            "btn_digits": "🔢 Zahlen",
            "desc_digits": "0-9",
            "btn_alphanum": "🔤🔢 Alphanum.",
            "desc_alphanum": "Buchst.+Zahlen",
            "btn_any": "❓ Beliebig",
            "desc_any": "Ein Zeichen",
            "btn_custom": "📝 Eigener Text",
            "desc_custom": "Ihr Text",
            "btn_special": "⚙️ Spezial",
            "desc_special": "Satzzeichen",
            "btn_once": "🎯 1-mal",
            "desc_once": "Genau einmal",
            "btn_one_plus": "➕ 1+ mal",
            "desc_one_plus": "Mindestens 1-mal",
            "btn_zero_one": "❓ 0-1 mal",
            "desc_zero_one": "Optional",
            "btn_zero_plus": "♾️ 0+ mal",
            "desc_zero_plus": "Beliebig oft",
            "btn_n_times": "📏 N-mal",
            "desc_n_times": "Genau N-mal",
            "btn_m_n_times": "📊 M-N mal",
            "desc_m_n_times": "M bis N-mal",
            "btn_start": "^ Anfang",
            "desc_start": "Zeilenanfang",
            "btn_end": "$ Ende",
            "desc_end": "Zeilenende",
            "btn_word": "\\b Wort",
            "desc_word": "Wortgrenze",
            "btn_group": "( ) Gruppe",
            "desc_group": "Gruppierung",
            "btn_or": "| ODER",
            "desc_or": "Alternative",
            "btn_alt": "(?: ) Alt.",
            "desc_alt": "Gruppe o. Speicher",
            "preview": "👀 Vorschau",
            "selection": "Auswahl:",
            "btn_add": "➕ Hinzufügen",
            "btn_reset": "🔄 Zurücksetzen",
            "regex_result": "🎯 Regex-Muster",
            "btn_manage": "📝 Muster verwalten",
            "btn_save_preset": "💾 Als Muster speichern",
            "btn_copy": "📋 Kopieren",
            "btn_reset_pattern": "🔄 Muster zurücksetzen",
            "btn_undo": "↶ Rückgängig",
            "btn_redo": "↷ Wiederholen",
            "btn_apply": "💾 In Hauptfenster übernehmen",
            "btn_test": "🧪 Testen",
            "test_input": "Testtext eingeben:",
            "test_text_frame": "📝 Testtext",
            "test_pattern_frame": "🔍 Regex-Muster",
            "btn_load_example": "📋 Beispiel laden",
            "result_label": "Ergebnis:",
            "matches_label": "Gefundene Treffer:",
            "common_examples": "📚 Häufig verwendete Regex-Beispiele",
            "msg_pattern_applied": "Regex-Muster wurde in das Hauptfenster übernommen!",
            "msg_main_not_avail": "Hauptfenster-Referenz nicht verfügbar. Kopieren Sie das Muster manuell.",
            "msg_no_pattern_apply": "Kein Regex-Muster zum Übernehmen verfügbar",
            "msg_copied": "Regex-Muster wurde in die Zwischenablage kopiert!",
            "msg_no_pattern_copy": "Kein Regex-Muster zum Kopieren verfügbar",
            "msg_no_undo": "Keine weiteren Rückgängig-Aktionen verfügbar",
            "msg_no_redo": "Keine Wiederholen-Aktionen verfügbar",
            "msg_enter_pattern": "❌ Bitte geben Sie ein Regex-Muster ein",
            "msg_enter_text": "❌ Bitte geben Sie einen Testtext ein",
            "msg_pattern_found": "✅ Muster gefunden! {} Treffer (davon {} einzigartig)",
            "msg_no_matches": "❌ Keine Treffer gefunden",
            "msg_invalid_regex": "❌ Ungültiges Regex-Muster: {}",
            "msg_example_loaded": "Beispiel geladen - klicken Sie auf 'Testen'",
            "builder_desc_letters": "Buchstaben (a-z, A-Z)",
            "builder_desc_digits": "Zahlen (0-9)",
            "builder_desc_alphanum": "Buchstaben und Zahlen",
            "builder_desc_any": "Ein beliebiges Zeichen",
            "builder_desc_custom": "Der Text: '{}'",
            "builder_desc_custom_generic": "Ihr eigener Suchtext",
            "builder_desc_special": "Sonderzeichen (Leerzeichen, Punkt, Komma, etc.)",
            "builder_desc_once": "erscheint genau einmal",
            "builder_desc_one_plus": "erscheint ein- oder mehrmals",
            "builder_desc_zero_one": "ist optional (0- oder 1-mal)",
            "builder_desc_zero_plus": "erscheint beliebig oft (0-mal oder mehr)",
            "builder_desc_n_times": "erscheint genau {}-mal",
            "builder_desc_m_n_times": "erscheint {} bis {}-mal",
            "builder_desc_start": "am Zeilenanfang",
            "builder_desc_end": "am Zeilenende",
            "builder_desc_word": "als ganzes Wort",
            "builder_desc_or": "mit Alternativen",
            "default_test_text": "Beispieltext mit error und warning 123 Zahlen und E-Mail: test@example.com",
            "default_result": "Hier erscheint das Testergebnis...",
            "no_matches": "Keine Treffer",
            "auto_desc": "Beschreibung wird automatisch generiert...",
            "select_char_first": "Wählen Sie zuerst einen Zeichentyp aus...",
            "enter_name": "Geben Sie einen Namen ein",
            "save_pattern": "Muster speichern",
            "name_for_pattern": "Name für das neue Muster:",
            "msg_save_success": "Muster '{}' wurde gespeichert",
            "overwrite_confirm": "Ein Muster mit dem Namen '{}' existiert bereits. Möchten Sie es überschreiben?",
            
            # Additional keys needed for gui_new.py
            "errors_and_warnings": "Fehler und Warnungen",
            "errors_only": "Nur Fehler",
            "warnings_only": "Nur Warnungen",
            "critical_errors": "Kritische Fehler",
            "numbers_100_199": "Zahlen 100-199",
            "email_addresses": "E-Mail-Adressen",
            "phone_numbers": "Telefonnummern (DE)",
            "date_yyyy_mm_dd": "Datum (YYYY-MM-DD)",
            
            "desc_errors_and_warnings": "Findet 'error', 'warning' oder 'critical'",
            "desc_errors_only": "Findet nur 'error'",
            "desc_warnings_only": "Findet nur 'warning'",
            "desc_critical_errors": "Findet nur 'critical'",
            "desc_numbers_100_199": "Findet Zahlen von 100 bis 199",
            "desc_email_addresses": "Findet übliche E-Mail-Adressen",
            "desc_phone_numbers": "Findet Telefonnummern (deutsches Format)",
            "desc_date_yyyy_mm_dd": "Findet Datum im ISO-Format",
        }

    def set_language(self, language):
        """
        Set the current language

        Args:
            language: Language code ('en' or 'de')
        """
        if language in self.translations:
            self.current_language = language
        else:
            raise ValueError(f"Unsupported language: {language}")

    def get(self, key, default=None):
        """
        Get a translation for a key

        Args:
            key: Translation key
            default: Default value if key not found

        Returns:
            Translated string or default value
        """
        return self.translations[self.current_language].get(key, default if default is not None else key)

    def __getitem__(self, key):
        """
        Get a translation using dictionary-style access
        """
        return self.get(key)

    def get_available_languages(self):
        """
        Get list of available language codes

        Returns:
            List of language codes
        """
        return list(self.translations.keys())

    def get_language_names(self):
        """
        Get dictionary mapping language codes to display names

        Returns:
            Dictionary with language codes as keys and display names as values
        """
        return {
            "en": self.get("english"),
            "de": self.get("german")
        }
