#!/usr/bin/env python3
#
# SPDX-FileCopyrightText: 2026 UnionTech Software Technology Co., Ltd.
#
# SPDX-License-Identifier: LGPL-3.0-or-later

import json
import os
import sys

def extract_translations(config_dir, output_file, app_id):
    """
    Scans the config_dir for org.deepin.shortcut.json / org.deepin.gesture.json
    files and extracts the displayName and category fields into a dummy C++ file
    for lupdate scanning. Both fields use the same translation model: the app
    that provides the config provides the translation via its per-appId QM.
    """
    # Fixed display text used when a shortcut has no assigned key sequence.
    translatable = {"None"}
    target_files = {"org.deepin.shortcut.json", "org.deepin.gesture.json"}

    for root, dirs, files in os.walk(config_dir):
        for file in files:
            if file in target_files:
                with open(os.path.join(root, file), 'r') as f:
                    try:
                        data = json.load(f)
                        contents = data.get("contents", {})

                        # Only extract from modifiable (user-visible) configs
                        modifiable = contents.get("modifiable", {}).get("value", False)
                        if not modifiable:
                            continue

                        display_name = contents.get("displayName", {}).get("value")
                        if display_name:
                            translatable.add(display_name)

                        category = contents.get("category", {}).get("value")
                        if category and isinstance(category, str):
                            translatable.add(category)
                    except Exception as e:
                        print(f"Error parsing {file}: {e}", file=sys.stderr)

    if not translatable:
        print(f"Warning: No translatable strings found in {config_dir}", file=sys.stderr)

    with open(output_file, 'w') as f:
        f.write('// This is an automatically generated file for shortcut translation extraction.\n')
        f.write('// DO NOT EDIT THIS FILE MANUALLY.\n\n')
        f.write('#include <QtGlobal>\n\n')
        f.write('// Mark strings for translation using QT_TRANSLATE_NOOP\n')
        f.write('// The array is marked as unused to suppress compiler warnings\n')
        f.write('[[maybe_unused]] static const char* shortcut_names[] = {\n')
        for name in sorted(translatable):
            f.write(f'    QT_TRANSLATE_NOOP("{app_id}", "{name}"),\n')
        f.write('};\n')

if __name__ == "__main__":
    if len(sys.argv) < 4:
        print("Usage: extract_shortcuts_i18n.py <configs_dir> <output_cpp> <app_id>")
        sys.exit(1)
        
    extract_translations(sys.argv[1], sys.argv[2], sys.argv[3])
