#!/usr/bin/env python3
import os
import sys
import polib

# Groups of msgids
GROUPS = {
    1: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "_Menu", "Pipe Men_u", "_Item", "Separato_r", "_Action"],
    2: ["_Cancel", "_Same Level", "_Inside Menu"],
    3: ["_File", "_View", "_Help", "_Done", "_Cancel"],
    4: ["_File", "_View", "_Help", "_Cancel", "_Reset", "_Done"],
    5: ["_Close", "_Replace"],
    6: ["_Cancel", "_OK"],
    7: ["_Cancel", "_Restart App"],
    8: ["_Cancel", "_Open"],   # special Cancel context
    9: ["_Cancel", "_Save"],   # special Cancel context
    10: ["_Choose File", "Check _Later", "_Ignore All Errors and Check Later"],
    11: ["_Visualize", "_Keep as is", "_Delete"],
    12: ["_Cancel", "C_ontinue"],
    13: ["_Restore Menu", "_Delete Autosave"],
    14: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "Pro_mpt"],
    15: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "_Command"],
    16: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "Startup_notify"],
    17: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "_Icon"],
    18: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "_Name"],
    19: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "E_nabled"],
    20: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "_WM__CLASS"],
    21: ["_File", "_Edit", "_Search", "_View", "_Preferences", "_Help", "_Option"],
    22: ["The Menu _File", "_Working With Kickshaw", "_Miscellaneous"],
}

def extract_mnemonic(text: str) -> str | None:
    """Extracts mnemonic character from a string with underscores."""
    i = 0
    while i < len(text):
        if text[i] == "_":
            if i + 1 < len(text) and text[i + 1] == "_":
                i += 2  # escaped underscore
                continue
            return text[i + 1] if i + 1 < len(text) else None
        i += 1
    return None

def get_cancel_context(group_num: int) -> str:
    """Return required msgctxt for '_Cancel' based on group."""
    if group_num in (8, 9):
        return "Cancel|File Dialogue"
    return "Cancel|No File Dialogue"

def check_po_file(filepath: str):
    po = polib.pofile(filepath)

    # Build lookup: (msgid, msgctxt or None) → msgstr
    lookup = {}
    for entry in po:
        key = (entry.msgid, entry.msgctxt or None)
        if entry.msgstr:
            lookup[key] = entry.msgstr

    for group_num, msgids in GROUPS.items():
        mnemonics = {}
        for msgid in msgids:
            # handle _Cancel with context
            if msgid == "_Cancel":
                ctxt = get_cancel_context(group_num)
                key = (msgid, ctxt)
            else:
                key = (msgid, None)

            if key not in lookup:
                print(f"ERROR: {filepath}: msgid '{msgid}' (context={key[1]}) not found in group {group_num}")
                sys.exit(1)

            msgstr = lookup[key]
            mnemonic = extract_mnemonic(msgstr)
            if mnemonic:
                normalized = mnemonic.casefold()   # normalize for duplicate check
                if normalized in mnemonics:
                    other = mnemonics[normalized]
                    print(
                        f"DUPLICATE in {filepath}, group {group_num}: "
                        f"mnemonic '{mnemonic}' (normalized='{normalized}') "
                        f"used by '{other}' and '{msgid}'"
                    )
                else:
                    mnemonics[normalized] = msgid

def main():
    po_dir = os.path.join("..", "..", "po")

    for fname in os.listdir(po_dir):
        if fname.endswith(".po"):
            fpath = os.path.join(po_dir, fname)
            check_po_file(fpath)

if __name__ == "__main__":
    main()

