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

def norm(s):
    """Normalize string for caseless comparison (handles Unicode)."""
    return s.casefold()

def check_po_file(filepath, multi_translation_files):
    po = polib.pofile(filepath)

    # Look for msgid "Choose|Add"
    entry = po.find("Choose|Add")
    if not entry:
        return []  # no issue, nothing to check

    msgstr = entry.msgstr.strip()
    if not msgstr:
        return [(filepath, "Missing translation for 'Choose|Add'")]

    # Split translations
    parts = [p.strip() for p in msgstr.split("|") if p.strip()]

    choose_translations = []
    add_translations = []
    issues = []

    if len(parts) == 2:
        choose_translations = [parts[0]]
        add_translations = [parts[1]]
    elif len(parts) == 4:
        choose_translations = [parts[0], parts[1]]
        add_translations = [parts[2], parts[3]]
        print(f"Note: {filepath} has 4 translations for 'Choose|Add'")
        multi_translation_files.add(filepath)
    else:
        issues.append((filepath,
                       f"Number of translations for 'Choose|Add' is other than 2 or 4 (found {len(parts)}): {msgstr}"))
        multi_translation_files.add(filepath)
        return issues  # stop further checks for this file

    # --- CHECK "CHOOSE" ---
    choose_targets = [
        "Choose",
        "Choose an Action",
        "Choose an Action/Option",
        "Choose an Option"
    ]
    for target in choose_targets:
        e = po.find(target)
        if e and e.msgstr.strip():
            if not any(norm(c) in norm(e.msgstr) for c in choose_translations):
                issues.append((filepath,
                               f"Mismatch for '{target}': translation '{e.msgstr}' does not match any of {choose_translations}"))
        else:
            issues.append((filepath, f"Missing translation for '{target}'"))

    # --- CHECK "ADD" ---
    add_targets = ["Add"] + [e.msgid for e in po if e.msgid.startswith("Add Inside") or e.msgid.startswith("Add Next")]
    for target in add_targets:
        e = po.find(target)
        if e and e.msgstr.strip():
            if not any(norm(a) in norm(e.msgstr) for a in add_translations):
                issues.append((filepath,
                               f"Mismatch for '{target}': translation '{e.msgstr}' does not match any of {add_translations}"))
        else:
            issues.append((filepath, f"Missing translation for '{target}'"))

    return issues


def main():
    all_issues = []
    multi_translation_files = set()

    po_dir = os.path.join("..", "..", "po")

    for filename in os.listdir(po_dir):
        if filename.endswith(".po"):
            fpath = os.path.join(po_dir, filename)
            issues = check_po_file(fpath, multi_translation_files)
            all_issues.extend(issues)

    if all_issues:
        print("Issues found:")
        for filepath, issue in all_issues:
            print(f" - {filepath}: {issue}")
    else:
        print("All files passed consistency checks ✅")

    if multi_translation_files:
        print("\n⚠️  Some files have more than two translations for 'Choose|Add'.")
        print("Please check these files manually:")
        for f in sorted(multi_translation_files):
            print(f" - {f}")

if __name__ == "__main__":
    main()

