Bikarhêner:Balyozxane/katbike-rec.py

import pywikibot
import re
from pywikibot import pagegenerators
from pywikibot.bot import AutomaticTWSummaryBot, ConfigParserBot, SingleSiteBot

class AppendTextBot(
    SingleSiteBot,
    ConfigParserBot,
    AutomaticTWSummaryBot,
):
    summary_key = 'basic-changing'
    use_redirects = False
    update_options = {
        'summary': None,
        'text': '{{katbike}}',
        'top': False,
    }

    def fetch_interwiki_link_content(self, page_title):
        site = pywikibot.Site("ku", "wiktionary")  # Local wiki (ku.wiktionary.org)
        pywikibot.output(f"Fetching interwiki link content for page: {page_title}")

        # Remove "Kategorî:" from the page title
        cleaned_title = page_title.replace("Kategorî:", "").strip()

        pywikibot.output(f"cleaned_title: {cleaned_title}")

        # Fetch the result of Module:înterwîkî-çêke from the local wiki
        params = {
            "action": "expandtemplates",
            "format": "json",
            "text": f"{{{{#invoke:înterwîkî-çêke|biwesine|{cleaned_title}}}}}",
            "prop": "wikitext"
        }
        request = pywikibot.data.api.Request(site=site, **params)
        response = request.submit()
        data = response['expandtemplates']
        interwiki_link_content = data['wikitext']
        pywikibot.output(f"interwiki_link_content: {interwiki_link_content}")

        category_result = "Category:" + interwiki_link_content  # Add "Category:" to the result
        pywikibot.output(f"category_result: {category_result}")

        # Check if the page exists on en.wiktionary.org
        en_site = pywikibot.Site("en", "wiktionary")
        page = pywikibot.Page(en_site, category_result)
        page_exists = page.exists()
        pywikibot.output(f"page_exists: {page_exists}")

        return {
            "content": category_result,
            "pageExists": page_exists
        }
        
    def fetch_parent_categories(self, page_title):
        site = pywikibot.Site("ku", "wiktionary")
        
        # Remove "Kategorî:" from the page title
        cleaned_title = page_title.replace("Kategorî:", "").strip()
        
        pywikibot.output(f"Fetching parent categories for page: {cleaned_title}")

        # Fetch data from the Lua module
        params = {
            "action": "expandtemplates",
            "format": "json",
            "text": f"{{{{#invoke:getParents|biwesine|{cleaned_title}}}}}",
            "prop": "wikitext"
        }
        request = pywikibot.data.api.Request(site=site, **params)
        response = request.submit()
        data = response['expandtemplates']
        parent_categories_text = data['wikitext']

        # Parse the comma-separated list of parents
        parent_categories = parent_categories_text.split(',')
        pywikibot.output(f"parent_categories: {parent_categories}")

        return parent_categories
    def create_parent_category_recursive(self, parent_name):
        category_name = "Kategorî:" + parent_name

        site = self.site
        page = pywikibot.Page(site, category_name)
        if page.exists():
            pywikibot.output(f"Category '{category_name}' already exists. Skipping.")
            return

        # Add {{katbike}} to the category page's content
        category_content = "{{katbike}}"

        try:
            interwiki_content = self.fetch_interwiki_link_content(category_name)
            pywikibot.output(f"Interwiki content: {interwiki_content['content']}")

            if interwiki_content['pageExists']:
                category_content += "\n" + "[[en:" + interwiki_content['content'] + "]]"

            summary = None

            if interwiki_content['pageExists']:
                summary = (
                    f"Rûpel bi {{{{[[Şablon:katbike|katbike]]}}}} hat çêkirin "
                    f"û înterwîkî [[en:{interwiki_content['content']}]] lê hat zêdekirin"
                )
            else:
                summary = (
                    f"Rûpel bi {{{{[[Şablon:katbike|katbike]]}}}} hat çêkirin "
                    f"lê înterwîkî [[en:{interwiki_content['content']}]] li en.wiktê tine ye"
                )

            page.text = category_content

            # Save the category page
            page.save(summary=summary)

            # Fetch and create parent categories recursively
            parent_categories = self.fetch_parent_categories(parent_name)

            for parent_category in parent_categories:
                if "Xeletî çêbû" in parent_category:
                    pywikibot.output(f"Skipping creation of parent category '{parent_category}' due to message.")
                    break

                parent_category = parent_category.replace("Kategorî:", "")
                try:
                    self.create_parent_category_recursive(parent_category)
                except Exception as e:
                    pywikibot.error(f"Error creating parent category '{parent_category}': {e}")
                    pywikibot.output(f"Skipping creation of parent category '{parent_category}'.")
                    continue

        except Exception as e:
            pywikibot.error(f"Error creating category '{category_name}': {e}")
            pywikibot.output(f"Skipping creation of category '{category_name}'.")
            return
    def treat_page(self) -> None:
        page = self.current_page
        pywikibot.output(f"Processing page: {page.title()}")

        if page.exists():
            pywikibot.output(f"Page '{page.title()}' already exists. Skipping.")
            return

        try:
            interwiki_content = self.fetch_interwiki_link_content(page.title())
        except Exception as e:
            pywikibot.error(f"Error fetching interwiki content: {e}")
            pywikibot.output(f"Skipping page '{page.title()}'.")
            return

        pywikibot.output(f"Interwiki content: {interwiki_content['content']}")

        summary = None

        if interwiki_content['pageExists']:
            summary = (
                f"Rûpel bi {{{{[[Şablon:katbike|katbike]]}}}} hat çêkirin "
                f"û înterwîkî [[en:{interwiki_content['content']}]] lê hat zêdekirin"
            )
            text = "{{katbike}}\n" + "[[en:" + interwiki_content['content'] + "]]"
        else:
            summary = (
                f"Rûpel bi {{{{[[Şablon:katbike|katbike]]}}}} hat çêkirin "
                f"lê înterwîkî [[en:{interwiki_content['content']}]] li en.wiktê tine ye"
            )
            text = "{{katbike}}"

        pywikibot.output(f"Final text to put: {text}")

        self.put_current(text, summary=summary)

        try:
            parent_categories = self.fetch_parent_categories(page.title().replace("Kategorî:", ""))
        except Exception as e:
            pywikibot.error(f"Error fetching parent categories: {e}")
            pywikibot.output(f"Skipping creation of parent categories for page '{page.title()}'.")
            return

        if parent_categories:
            for parent_category in parent_categories:
                if "Parents not found for" in parent_category:
                    pywikibot.output(f"Skipping creation of parent category '{parent_category}' due to message.")
                    break

                parent_category = parent_category.replace("Kategorî:", "")
                self.create_parent_category_recursive(parent_category)

        else:
            pywikibot.output("No parent categories found. Skipping creation.")
  
def main(*args: str) -> None:
    local_args = pywikibot.handle_args(args)
    gen_factory = pagegenerators.GeneratorFactory()
    local_args = gen_factory.handle_args(local_args)

    options = {'text': '{{katbike}}'}

    for arg in local_args:
        option, _, value = arg.partition(':')
        if option in ('summary', 'text'):
            if not value:
                pywikibot.input(f'Please enter a value for {option}')
            options[option] = value
        else:
            options[option] = True

    gen = gen_factory.getCombinedGenerator(preload=True)

    if not pywikibot.bot.suggest_help(missing_generator=not gen):
        bot = AppendTextBot(generator=gen, **options)
        bot.run()

if __name__ == '__main__':
    main()