#!/usr/bin/python
# -*- coding: utf-8  -*-

import codecs, wikipedia, catlib
import pagegenerators

# PotatoBot Task 1: Code for creating redirects to asteroid stubs (e. g. Agnesraab → 49109 Agnesraab)

def treat(page):
	"""Get an article, and either create a redirect or add the article name to a list."""
	# Show name of page in console window
	wikipedia.output(u'\n* ' + page.title())
	
	# Name of redirect to create
	s = page.title().find(' ')
	redir = page.title()[s+1:]
	redirpage = wikipedia.Page(wikipedia.getSite(), redir)
	
	# Only if the page is in article namespace, and it starts with a number (with optional parentheses) plus a space,
	# and it doesn't end with a digit (excludes 1994 XL1), and the name doesn't consist of two upper-case letters (excludes 2002 MN)
	if (page.namespace() == 0) and ((page.title()[:s].isdigit() and (not redir[-1].isdigit()) and ((len(redir) > 2) or not redir[1].isupper()))\
	or ((page.title()[0] == u'(') and (page.title()[1:s-1].isdigit()))):
	
		# Write names of existing pages to a list
		if redirpage.exists():
			wikipedia.output(u'  \03{yellow}page %s already exists\03{default}' % redir)
			comment = ''
			if redirpage.isDisambig():
				comment = u' (disambig)'
			if redirpage.isRedirectPage():
				try:
					if redirpage.getRedirectTarget().isDisambig():
						comment = u' (redir to disambig)'
					else:
						comment = u' (redir)'
				except:
					comment = u' (broken redir)'
			return u'# [[' + redir + u']] → ' + page.aslink() + comment + u'\n'
		
		# Else create redirect, or write page name to list if an error occurs
		else:
			try:
				redirpage.put(u'#REDIRECT ' + page.aslink() + u'{{R from short name}}', minorEdit=False)
				wikipedia.output(u'  \03{green}creating redirect %s\03{default}' % redir)
				return ''
			except wikipedia.LockedPage:
				wikipedia.output(u'  \03{red}cannot save %s because it is locked\03{default}' % redir)
				return u'# [[' + redir + u']] → ' + page.aslink() + u': page was locked\n'
			except wikipedia.EditConflict:
				wikipedia.output(u'  \03{red}cannot save %s because of edit conflict\03{default}' % redir)
				return u'# [[' + redir + u']] → ' + page.aslink() + u': edit conflict occurred\n'
			except wikipedia.SpamfilterError, error:
				wikipedia.output(u'  \03{red}cannot save %s because of spam blacklist entry %s\03{default}' % (redir, error.url))
				return u'# [[' + redir + u']] → ' + page.aslink() + u': spam blacklist entry\n'
			except:
				wikipedia.output(u'  \03{red}unknown error on saving %s\03{default}' % redir)
				return u'# [[' + redir + u']] → ' + page.aslink() + u': unknown error occurred\n'
	else:
		wikipedia.output(u'  \03{yellow}not a numbered asteroid\03{default}')
		return ''


def main():
	# Prepare list of redirects the bot could not create
	listout = u'Asteroid redirects PotatoBot could not create because there was already a page of that name. (Articles unless otherwise noted.)\n'
	
	# Fetch article list and run
	articlelist = pagegenerators.CategorizedPageGenerator(catlib.Category(wikipedia.getSite(), u'Category:Asteroid stubs'), True)
	wikipedia.setAction(u'Bot: Redirect from short name') # text for the REDIR edit summary
	for page in articlelist: 
		listout = listout + treat(page)
	
	# Create list of redirects the bot could not create
	wikipedia.setAction(u'Bot: Creating list of asteroids without redirects') # text for the LIST edit summary
	wikipedia.Page(wikipedia.getSite(), u'User:PotatoBot/Lists/Asteroids without redirects').put(listout, minorEdit=False)

if __name__ == "__main__":
	try:
		main()
	finally:
		wikipedia.stopme()