import os
import pywikibot

from pywikibot.bot import QuitKeyboardInterrupt
from pywikibot import pagegenerators

def main(*args):
    genFactory = pagegenerators.GeneratorFactory()
    #allowed_suffixes = ('jpg', 'jpeg', 'png', 'gif', 'svg')
    allowed_suffixes = []
    images_checked = 0
    capped_suffixes = 0
    site = pywikibot.Site()

    try:
        allowed_suffixes = site.siteinfo.get('fileextensions', get_default=False)
    except KeyError:
        pywikibot.stdout('Failed to get the wiki\'s allowed image suffixes!')
        return
    else:
        allowed_suffixes = [item['ext'].lower() for item in allowed_suffixes]
        pywikibot.stdout('Wiki accepts image suffixes {0}.'.format(allowed_suffixes))

    generator = site.allimages()
    pywikibot.stdout('Looking for images with capitalized suffixes...')
    for page in pagegenerators.PreloadingGenerator(generator, 100):
        images_checked = images_checked + 1
        suffix = page.title().split('.')[-1]
        if suffix.lower() in allowed_suffixes:
            if suffix != suffix.lower():
                # We found a page which has an allowed suffix but which is capitalized
                pywikibot.stdout('{0}'.format(page.title()))
                capped_suffixes = capped_suffixes + 1

                # Rename page to have lowercase suffix
                new_page_title = os.path.splitext(page.title())[0] + '.' + suffix.lower()
                pywikibot.stdout('Moving page to {0}...'.format(new_page_title))
                page.move(new_page_title, reason='use lowercase file suffix', movetalk=True, noredirect=True)

                # Warn the user if the page we moved had references to it
                wiki_links = []
                wiki_links = list(page.backlinks())
                file_links = []
                file_links = list(page.usingPages())
                if len(wiki_links) or len(file_links):
                    pywikibot.stdout('However this page is referenced by:')
                    for ref in wiki_links:
                        pywikibot.stdout('    {0}'.format(ref.title()))
                    for ref in file_links:
                        pywikibot.stdout('    {0}'.format(ref.title()))
        else:
            pywikibot.stdout('Found disallowed suffix {0}!'.format(suffix)) # should never happen

    pywikibot.stdout('Checked {0} images and found {1} with capitalized suffixes.'.format(images_checked, capped_suffixes))

if __name__ == '__main__':
    main()
