from qgis.PyQt.QtCore import QSettings


LANGUAGE_TEXTS = {
    "zh": {
        "plugin_name": "AL 修改监测",
        "dock_title": "AL 修改监测",
        "language_zh": "中文",
        "language_en": "English",
        "start_tracking": "启动追踪",
        "stop_tracking": "停止追踪",
        "enable_builtin_hotkeys": "激活内置快捷键",
        "disable_builtin_hotkeys": "取消激活内置快捷键",
        "field_name": "状态字段名:",
        "field_placeholder": "留空则默认使用 al_checked",
        "layer_header": "选择要追踪的矢量图层:",
        "refresh_layers": "刷新图层",
        "hotkey_group": "快捷键配置 (仅对当前激活图层生效)",
        "key_label": "按键 {key}",
        "value_label": "写入值:",
        "prompt_title": "提示",
        "select_layer_warning": "请至少勾选一个图层进行追踪。",
        "tracking_started_title": "追踪启动",
        "tracking_started_message": "成功挂载 {count} 个图层的动态追踪与全局热键。",
        "tracking_stopped_title": "追踪停止",
        "tracking_stopped_message": "已安全解绑所有监控信号。",
        "builtin_hotkeys_on_title": "快捷键已激活",
        "builtin_hotkeys_on_message": "插件内置快捷键已应用到当前 QGIS。",
        "builtin_hotkeys_off_title": "快捷键已还原",
        "builtin_hotkeys_off_message": "插件内置快捷键已移除，并恢复原有 QGIS 快捷键。",
        "field_type_conflict_title": "字段异构冲突",
        "field_type_conflict_message": "图层 '{layer}' 中的 '{field}' 类型不兼容，将自动使用 'al_checked' 替代。",
        "untracked_layer_title": "AL 修改监测",
        "untracked_layer_message": "当前激活的图层未加入追踪列表，操作已忽略。",
        "layer_not_editable_title": "AL 修改监测",
        "layer_not_editable_message": "当前图层未开启编辑模式，无法修改属性。",
        "init_field_command": "初始化 {field}",
        "hotkey_edit_command": "快捷键状态校准 ({value})",
        "other_unmarked": "其他/未标记",
    },
    "en": {
        "plugin_name": "AL Modify Monitor",
        "dock_title": "AL Modify Monitor",
        "language_zh": "中文",
        "language_en": "English",
        "start_tracking": "Start Tracking",
        "stop_tracking": "Stop Tracking",
        "enable_builtin_hotkeys": "Enable Built-in Hotkeys",
        "disable_builtin_hotkeys": "Disable Built-in Hotkeys",
        "field_name": "Status field:",
        "field_placeholder": "Leave empty to use al_checked",
        "layer_header": "Select vector layers to track:",
        "refresh_layers": "Refresh Layers",
        "hotkey_group": "Hotkey Configuration (active layer only)",
        "key_label": "Key {key}",
        "value_label": "Write value:",
        "prompt_title": "Notice",
        "select_layer_warning": "Please select at least one layer to track.",
        "tracking_started_title": "Tracking Started",
        "tracking_started_message": "Tracking and global hotkeys were attached to {count} layer(s).",
        "tracking_stopped_title": "Tracking Stopped",
        "tracking_stopped_message": "All tracking signals were safely disconnected.",
        "builtin_hotkeys_on_title": "Hotkeys Enabled",
        "builtin_hotkeys_on_message": "The plugin's built-in hotkeys are now active in QGIS.",
        "builtin_hotkeys_off_title": "Hotkeys Restored",
        "builtin_hotkeys_off_message": "The plugin's built-in hotkeys were removed and the original QGIS shortcuts were restored.",
        "field_type_conflict_title": "Field Type Conflict",
        "field_type_conflict_message": "Field '{field}' in layer '{layer}' is incompatible. Falling back to 'al_checked'.",
        "untracked_layer_title": "AL Modify Monitor",
        "untracked_layer_message": "The active layer is not being tracked, so the action was ignored.",
        "layer_not_editable_title": "AL Modify Monitor",
        "layer_not_editable_message": "The active layer is not editable, so attributes cannot be changed.",
        "init_field_command": "Initialize {field}",
        "hotkey_edit_command": "Hotkey status update ({value})",
        "other_unmarked": "Other / Unmarked",
    },
    "ru": {
        "plugin_name": "AL Modify Monitor",
        "dock_title": "AL Modify Monitor",
        "start_tracking": "Начать отслеживание",
        "stop_tracking": "Остановить отслеживание",
        "enable_builtin_hotkeys": "Включить встроенные горячие клавиши",
        "disable_builtin_hotkeys": "Отключить встроенные горячие клавиши",
        "field_name": "Поле статуса:",
        "field_placeholder": "Оставьте пустым для al_checked",
        "layer_header": "Выберите слои для отслеживания:",
        "refresh_layers": "Обновить слои",
        "hotkey_group": "Горячие клавиши (только активный слой)",
        "key_label": "Клавиша {key}",
        "value_label": "Записать значение:",
        "prompt_title": "Сообщение",
        "select_layer_warning": "Пожалуйста, выберите хотя бы один слой для отслеживания.",
        "tracking_started_title": "Отслеживание запущено",
        "tracking_started_message": "Отслеживание и горячие клавиши подключены к {count} слою(ям).",
        "tracking_stopped_title": "Отслеживание остановлено",
        "tracking_stopped_message": "Все сигналы отслеживания безопасно отключены.",
        "builtin_hotkeys_on_title": "Горячие клавиши включены",
        "builtin_hotkeys_on_message": "Встроенные горячие клавиши плагина активированы в QGIS.",
        "builtin_hotkeys_off_title": "Горячие клавиши восстановлены",
        "builtin_hotkeys_off_message": "Встроенные горячие клавиши удалены, исходные сочетания QGIS восстановлены.",
        "field_type_conflict_title": "Конфликт типа поля",
        "field_type_conflict_message": "Поле '{field}' в слое '{layer}' несовместимо. Используется 'al_checked'.",
        "untracked_layer_title": "AL Modify Monitor",
        "untracked_layer_message": "Активный слой не отслеживается, действие проигнорировано.",
        "layer_not_editable_title": "AL Modify Monitor",
        "layer_not_editable_message": "Активный слой не в режиме редактирования, изменить атрибуты нельзя.",
        "init_field_command": "Инициализация {field}",
        "hotkey_edit_command": "Обновление статуса ({value})",
        "other_unmarked": "Другое / Не отмечено",
    },
    "ja": {
        "plugin_name": "AL Modify Monitor",
        "dock_title": "AL Modify Monitor",
        "start_tracking": "追跡開始",
        "stop_tracking": "追跡停止",
        "enable_builtin_hotkeys": "内蔵ショートカットを有効化",
        "disable_builtin_hotkeys": "内蔵ショートカットを無効化",
        "field_name": "ステータス字段:",
        "field_placeholder": "空欄の場合は al_checked を使用",
        "layer_header": "追跡するベクターレイヤを選択:",
        "refresh_layers": "レイヤ更新",
        "hotkey_group": "ショートカット設定（アクティブレイヤのみ）",
        "key_label": "キー {key}",
        "value_label": "書き込む値:",
        "prompt_title": "通知",
        "select_layer_warning": "追跡するレイヤを少なくとも1つ選択してください。",
        "tracking_started_title": "追跡開始",
        "tracking_started_message": "{count} レイヤに追跡とショートカットを適用しました。",
        "tracking_stopped_title": "追跡停止",
        "tracking_stopped_message": "追跡シグナルを安全に解除しました。",
        "builtin_hotkeys_on_title": "ショートカット有効",
        "builtin_hotkeys_on_message": "プラグイン内蔵ショートカットが QGIS に適用されました。",
        "builtin_hotkeys_off_title": "ショートカット復元",
        "builtin_hotkeys_off_message": "内蔵ショートカットを解除し、元の QGIS ショートカットを復元しました。",
        "field_type_conflict_title": "字段タイプの衝突",
        "field_type_conflict_message": "レイヤ '{layer}' の字段 '{field}' は非対応です。'al_checked' に切替えます。",
        "untracked_layer_title": "AL Modify Monitor",
        "untracked_layer_message": "アクティブレイヤは追跡対象外のため、操作を無視しました。",
        "layer_not_editable_title": "AL Modify Monitor",
        "layer_not_editable_message": "レイヤが編集モードではありません。属性を変更できません。",
        "init_field_command": "{field} 初期化",
        "hotkey_edit_command": "ショートカット更新（{value}）",
        "other_unmarked": "その他 / 未マーク",
    },
    "fr": {
        "plugin_name": "AL Modify Monitor",
        "dock_title": "AL Modify Monitor",
        "start_tracking": "Démarrer le suivi",
        "stop_tracking": "Arrêter le suivi",
        "enable_builtin_hotkeys": "Activer les raccourcis intégrés",
        "disable_builtin_hotkeys": "Désactiver les raccourcis intégrés",
        "field_name": "Champ d’état :",
        "field_placeholder": "Laisser vide pour utiliser al_checked",
        "layer_header": "Sélectionnez les couches à suivre :",
        "refresh_layers": "Rafraîchir",
        "hotkey_group": "Raccourcis (couche active uniquement)",
        "key_label": "Touche {key}",
        "value_label": "Écrire la valeur :",
        "prompt_title": "Info",
        "select_layer_warning": "Veuillez sélectionner au moins une couche à suivre.",
        "tracking_started_title": "Suivi démarré",
        "tracking_started_message": "Suivi et raccourcis appliqués à {count} couche(s).",
        "tracking_stopped_title": "Suivi arrêté",
        "tracking_stopped_message": "Tous les signaux de suivi ont été déconnectés en toute sécurité.",
        "builtin_hotkeys_on_title": "Raccourcis activés",
        "builtin_hotkeys_on_message": "Les raccourcis intégrés du plugin sont actifs dans QGIS.",
        "builtin_hotkeys_off_title": "Raccourcis restaurés",
        "builtin_hotkeys_off_message": "Les raccourcis intégrés ont été retirés et les raccourcis QGIS ont été restaurés.",
        "field_type_conflict_title": "Conflit de type de champ",
        "field_type_conflict_message": "Le champ '{field}' de la couche '{layer}' est incompatible. Utilisation de 'al_checked'.",
        "untracked_layer_title": "AL Modify Monitor",
        "untracked_layer_message": "La couche active n’est pas suivie, l’action a été ignorée.",
        "layer_not_editable_title": "AL Modify Monitor",
        "layer_not_editable_message": "La couche active n’est pas en mode édition, impossible de modifier les attributs.",
        "init_field_command": "Initialiser {field}",
        "hotkey_edit_command": "Mise à jour ({value})",
        "other_unmarked": "Autre / Non marqué",
    },
    "de": {
        "plugin_name": "AL Modify Monitor",
        "dock_title": "AL Modify Monitor",
        "start_tracking": "Tracking starten",
        "stop_tracking": "Tracking stoppen",
        "enable_builtin_hotkeys": "Integrierte Hotkeys aktivieren",
        "disable_builtin_hotkeys": "Integrierte Hotkeys deaktivieren",
        "field_name": "Statusfeld:",
        "field_placeholder": "Leer lassen für al_checked",
        "layer_header": "Zu verfolgende Layer auswählen:",
        "refresh_layers": "Layer aktualisieren",
        "hotkey_group": "Hotkeys (nur aktiver Layer)",
        "key_label": "Taste {key}",
        "value_label": "Wert schreiben:",
        "prompt_title": "Hinweis",
        "select_layer_warning": "Bitte mindestens einen Layer zum Tracking auswählen.",
        "tracking_started_title": "Tracking gestartet",
        "tracking_started_message": "Tracking und Hotkeys wurden an {count} Layer(n) angehängt.",
        "tracking_stopped_title": "Tracking gestoppt",
        "tracking_stopped_message": "Alle Tracking-Signale wurden sicher getrennt.",
        "builtin_hotkeys_on_title": "Hotkeys aktiv",
        "builtin_hotkeys_on_message": "Die integrierten Hotkeys des Plugins sind in QGIS aktiv.",
        "builtin_hotkeys_off_title": "Hotkeys wiederhergestellt",
        "builtin_hotkeys_off_message": "Die integrierten Hotkeys wurden entfernt und die ursprünglichen QGIS-Shortcuts wiederhergestellt.",
        "field_type_conflict_title": "Feldtyp-Konflikt",
        "field_type_conflict_message": "Feld '{field}' in Layer '{layer}' ist inkompatibel. Fallback auf 'al_checked'.",
        "untracked_layer_title": "AL Modify Monitor",
        "untracked_layer_message": "Der aktive Layer wird nicht getrackt, Aktion ignoriert.",
        "layer_not_editable_title": "AL Modify Monitor",
        "layer_not_editable_message": "Der aktive Layer ist nicht editierbar, Attribute können nicht geändert werden.",
        "init_field_command": "{field} initialisieren",
        "hotkey_edit_command": "Hotkey-Update ({value})",
        "other_unmarked": "Andere / Unmarkiert",
    },
    "hi": {
        "plugin_name": "AL Modify Monitor",
        "dock_title": "AL Modify Monitor",
        "start_tracking": "ट्रैकिंग शुरू करें",
        "stop_tracking": "ट्रैकिंग रोकें",
        "enable_builtin_hotkeys": "बिल्ट-इन हॉटकी सक्षम करें",
        "disable_builtin_hotkeys": "बिल्ट-इन हॉटकी अक्षम करें",
        "field_name": "स्थिति फ़ील्ड:",
        "field_placeholder": "खाली छोड़ें तो al_checked उपयोग होगा",
        "layer_header": "ट्रैक करने के लिए लेयर चुनें:",
        "refresh_layers": "लेयर रिफ्रेश करें",
        "hotkey_group": "हॉटकी कॉन्फ़िग (केवल सक्रिय लेयर)",
        "key_label": "कुंजी {key}",
        "value_label": "मान लिखें:",
        "prompt_title": "सूचना",
        "select_layer_warning": "कृपया ट्रैकिंग के लिए कम से कम एक लेयर चुनें।",
        "tracking_started_title": "ट्रैकिंग शुरू",
        "tracking_started_message": "{count} लेयर पर ट्रैकिंग और हॉटकी लागू की गई।",
        "tracking_stopped_title": "ट्रैकिंग रुकी",
        "tracking_stopped_message": "सभी ट्रैकिंग सिग्नल सुरक्षित रूप से हटाए गए।",
        "builtin_hotkeys_on_title": "हॉटकी सक्षम",
        "builtin_hotkeys_on_message": "प्लगइन की बिल्ट-इन हॉटकी अब QGIS में सक्रिय हैं।",
        "builtin_hotkeys_off_title": "हॉटकी बहाल",
        "builtin_hotkeys_off_message": "बिल्ट-इन हॉटकी हटाई गईं और मूल QGIS शॉर्टकट बहाल किए गए।",
        "field_type_conflict_title": "फ़ील्ड प्रकार संघर्ष",
        "field_type_conflict_message": "लेयर '{layer}' में फ़ील्ड '{field}' असंगत है। 'al_checked' उपयोग होगा।",
        "untracked_layer_title": "AL Modify Monitor",
        "untracked_layer_message": "सक्रिय लेयर ट्रैक नहीं हो रही है, इसलिए क्रिया अनदेखी की गई।",
        "layer_not_editable_title": "AL Modify Monitor",
        "layer_not_editable_message": "सक्रिय लेयर एडिट मोड में नहीं है, एट्रिब्यूट बदले नहीं जा सकते।",
        "init_field_command": "{field} आरंभ करें",
        "hotkey_edit_command": "हॉटकी अपडेट ({value})",
        "other_unmarked": "अन्य / बिना चिह्न",
    },
}

LANGUAGE_NAMES = [
    ("zh", "中文"),
    ("en", "English"),
    ("ru", "Русский"),
    ("ja", "日本語"),
    ("fr", "Français"),
    ("de", "Deutsch"),
    ("hi", "हिन्दी"),
]


def detect_language():
    locale = QSettings().value("locale/userLocale", "", type=str) or ""
    locale = locale.lower()
    if locale.startswith("zh"):
        return "zh"
    if locale.startswith("en"):
        return "en"
    if locale.startswith("ru"):
        return "ru"
    if locale.startswith("ja"):
        return "ja"
    if locale.startswith("fr"):
        return "fr"
    if locale.startswith("de"):
        return "de"
    if locale.startswith("hi"):
        return "hi"
    return "en"


def get_text(language, text_key, **kwargs):
    texts = LANGUAGE_TEXTS.get(language, LANGUAGE_TEXTS["en"])
    value = texts.get(text_key, text_key)
    if kwargs:
        return value.format(**kwargs)
    return value
