import os
import polib
import re

# Detect mnemonic in msgid or msgstr
def detect_mnemonic_style(text):
    if re.search(r'(?<!\\)_\w', text):  # Underscore before a letter
        return 'underscore'
    elif re.search(r'\(\s*._\w\s*\)', text):  # Bracketed like (_D)
        return 'bracket'
    return 'none'

def analyze_po_file(filepath):
    po = polib.pofile(filepath)

    missing_mnemonics = []
    mnemonic_styles = set()

    for entry in po:
        msgid = entry.msgid
        msgstr = entry.msgstr

        msgid_style = detect_mnemonic_style(msgid)
        msgstr_style = detect_mnemonic_style(msgstr)

        if msgid_style != 'none' and msgstr_style == 'none':
            line_number = entry.linenum if hasattr(entry, 'linenum') else '?'
            missing_mnemonics.append((filepath, line_number))

        if msgstr_style != 'none':
            mnemonic_styles.add(msgstr_style)

    return missing_mnemonics, mnemonic_styles

def main():
    base_path = os.path.abspath("../../../po")

    for root, dirs, files in os.walk(base_path):
        for file in files:
            if file.endswith(".po"):
                filepath = os.path.join(root, file)
                missing, styles = analyze_po_file(filepath)

                for fname, line in missing:
                    print(f"Missing mnemonic in msgstr: {fname} (line {line})")

                if len(styles) > 1:
                    print(f"Inconsistent mnemonic styles in file: {filepath} (styles used: {', '.join(styles)})")

if __name__ == "__main__":
    main()

