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')

# Set the filename for the list of pages to be edited
input_file = 'navdêrên_mê.txt'

# Read the titles from the file
with open(input_file, 'r', encoding='utf-8') as file:
    page_titles = [line.strip() for line in file]

# Iterate over all pages in the list
for title in page_titles:
    # Skip empty titles
    if not title:
        print(f"Skipping empty title.")
        continue

    page = pywikibot.Page(site, title)
    modify_wiktionary_page(page)