import os

def clean_po_file(filepath):
    with open(filepath, "r", encoding="utf-8") as f:
        lines = f.readlines()

    # Traverse from bottom to top
    new_end = len(lines)
    for i in range(len(lines) - 1, -1, -1):
        line = lines[i].rstrip("\n")
        if line.strip() == "" or line.strip().startswith("#"):
            new_end = i
        else:
            break

    # Keep only up to the last non-comment, non-empty line
    cleaned_lines = lines[:new_end]

    with open(filepath, "w", encoding="utf-8") as f:
        f.writelines(cleaned_lines)


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)
            print(f"Cleaning {fname}...")
            clean_po_file(fpath)

if __name__ == "__main__":
    main()
