# This script replaces the English texts for the options inside the
# "Options" section of hints2 with the translations that are inside the 
# corresponding po file. 

import os
import polib # polib might need to be installed

def get_translation_dict(po_file_path):
    """Reads the .po file and returns a dictionary of English to translated text."""
    try:
        po = polib.pofile(po_file_path)
    except IOError:
        print(f"Error: The file {po_file_path} could not be found.")
        return {}
    except Exception as e:
        print(f"An error occurred: {e}")
        return {}

    translation_dict = {}
    for entry in po:
        translation_dict[entry.msgid] = entry.msgstr

    return translation_dict

def replace_in_file(file_path, replacements):
    """Replaces occurrences of keys in the dictionary with their corresponding values in the specified file."""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            content = file.read()

        for original, translated in replacements.items():
            content = content.replace(original, translated)

        with open(file_path, 'w', encoding='utf-8') as file:
            file.write(content)

    except IOError:
        print(f"Error: The file {file_path} could not be found.")
    except Exception as e:
        print(f"An error occurred while replacing text: {e}")

def main():
    # User input for language code
    lang_code = input("Enter the language code (e.g., 'de', 'fr', 'zh_CN'): ")

    # Define file paths
    po_file_path = os.path.join("..", "..", "..", "po", f"{lang_code}.po")
    hints_file_path = os.path.join("..", "..", "txts", "hints", lang_code, f"hints2_{lang_code}")

    # English sentences to translate and their corresponding replacements
    translation_requests = {
        "Always notify about Execute option conversions.": "Always Notify About Execute Option Conversions",
        "Create Backup Before Overwriting Menu File": "Create Backup Before Overwriting Menu File",
        "Use Tabs for Indentations in Saved Menu File": "Use Tabs for Indentations in Saved Menu File",
        "Keep Root Menu Separate in Saved Menu File": "Keep Root Menu Separate in Saved Menu File",
        "Sort Execute/Startupnotify Options": "Sort Execute/Startupnotify Options",
        "Show Menu Button Instead of Menubar": "Show Menu Button Instead of Menubar",
        "Use Client-Side Decorations": "Use Client-Side Decorations"
    }

    # Get translations from .po file
    translations = get_translation_dict(po_file_path)
    if not translations:
        print("No translations could be found, exiting.")
        return

    # Prepare replacements
    replacements = {lookup: translations.get(request, request) for request, lookup in translation_requests.items()}

    # Replace in hints file
    replace_in_file(hints_file_path, replacements)
    print("Replacement complete.")

if __name__ == "__main__":
    main()

