import pywikibot
import re

def modify_wiktionary_page(page):
    # Load the current text of the page
    text = page.text

    # Check if {{ku-tewîn-rd is already present
    if '{{ku-tewîn-rd' not in text:
        # Check if the page contains "=== Navdêr 2 ===" or "=== Navdêr 3 ===" or "=== Serenav ==="
        # or if it contains "[Wêne:"
        if re.search(r'===\s*(Navdêr\s*2|Navdêr\s*3|Serenav)\s*===|\[Wêne:', text):
            print(f"Ignoring page '{page.title()}' as it contains Navdêr 2, Navdêr 3, Serenav sections, or [Wêne: in the text.")
        else:
            # Set the new text to be added
            new_text_to_add = f'{{{{ku-tewîn-rd|{page.title()}}}}}\n{{{{rengdêr|ku}}}}'

            # Add the new text before "{{rengdêr|ku}}"
            new_text = re.sub(r'{{rengdêr\|ku}}', new_text_to_add, text)
            
            # Check if the text has changed
            if text != new_text:
                # Save the changes
                page.text = new_text
                page.save(summary="Tabloya berhevdana rengdêrê hat lêzêdekirin", botflag=True)
                print(f"Content added successfully on page '{page.title()}'.")
            else:
                print(f"No changes required on page '{page.title()}'.")
    else:
        print(f"{{ku-tewîn-rd}} already present on page '{page.title()}'.")

# Create a Site connection
site = pywikibot.Site('ku', 'wiktionary')

# Specify the category you want to retrieve pages from
category_title = 'Rengdêr bi kurmancî'

# Get the Category object
category = pywikibot.Category(site, title=category_title)

# Get the category members (pages within the category)
category_members = list(category.members())

# Iterate over all pages in the category
for page in category_members:
    # Skip empty titles
    if not page.title():
        print("Skipping empty title.")
        continue

    modify_wiktionary_page(page)