#!/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 field into a dummy C++ file for lupdate scanning.
    """
    display_names = set()
    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", {})

                        # Check if modifiable is true
                        modifiable = contents.get("modifiable", {}).get("value", False)
                        if not modifiable:
                            continue

                        # Extract displayName only if modifiable is true
                        display_name = contents.get("displayName", {}).get("value")
                        if display_name:
                            display_names.add(display_name)
                    except Exception as e:
                        print(f"Error parsing {file}: {e}", file=sys.stderr)

    if not display_names:
        print(f"Warning: No shortcut definitions 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(display_names):
            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])
