"""Add the family name property of a person if missing

For a person, check if the family name exists.
If not, create it and link it to the person
"""

from pywikibot.data import api
import pywikibot

#TODO: Iterate over several persons (or itemIDs)
#itemID = "Q2926869" # Jean-Marc Nollet
itemID = "Q1599"
instance_of_prop = "P31"
family_name_prop = "P734"
family_name_item = "Q101352"
human_item = "Q5"

def getItemsWithSameName(site, itemtitle):
    search_result = getItems(site, itemtitle)
    return [result for result in search_result['search'] if result['label'] == itemtitle]

def getItems(site, itemtitle):
    params = { 'action' :'wbsearchentities' , 'format' : 'json' , 'language' : 'en', 'type' : 'item', 'search': itemtitle}
    request = api.Request(site=site,parameters=params)
    return request.submit()

def getItem(site, wdItem, token):
   request = api.Request(site=site,
                         action='wbgetentities',
                         format='json',
                         ids=wdItem)    
   return request.submit()

site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()
person_item = pywikibot.ItemPage(repo, itemID)

#TODO: Check that person_item is an instance of human

person_dict = person_item.get()
person_label = person_dict['labels']['en']
clm_dict = person_dict["claims"]
if family_name_prop in clm_dict:
    # Family name exists, nothing to do
    clm_list = clm_dict[family_name_prop]

    for clm in clm_list:
        clm_trgt = clm.getTarget()
        fn_label = clm_trgt.text['labels']['en']
        print("'{}' is the family name indicated for '{}'".format(fn_label, person_label))
else:
    humanity_validated = False
    if instance_of_prop in clm_dict:
        for clm in clm_dict[instance_of_prop]:
            if human_item == clm.getTarget().getID():
                humanity_validated = True
    if humanity_validated:
        full_name = person_item.text['labels']['en']
        print("'{}' has no family name".format(full_name))
        proposed_family_name = full_name.split()[-1]
        print(proposed_family_name)
        # TODO: check (by a human) that family name is correct
        family_name_str = proposed_family_name

        # Create the item for his/her family name if it doesn't exist
        name_item_id = "" # Clear name_item_id
        potential_name_entries = getItemsWithSameName(site, family_name_str)
        for entry in potential_name_entries:
            potential_name_item = pywikibot.ItemPage(repo, entry['id'])
            item_dict = potential_name_item.get()
            clm_dict = item_dict["claims"]
            if instance_of_prop in clm_dict:
                for clm in clm_dict[instance_of_prop]:
                    if family_name_item == clm.getTarget().getID():
                        name_item_id = entry['id']
                        print("Name '{}' already exists!".format(family_name_str))

        if name_item_id == "":
            # name_item is not defined, create it!
            name_item = pywikibot.ItemPage(site)

            # create the labels
            mylabels = {}
            for language in ('en', 'fr', 'nl', 'de'):
                mylabels[language] = family_name_str
            name_item.editLabels(mylabels, summary='Set labels')

            # create the descriptions
            mydescriptions = {'en': 'family name', 'fr': 'nom de famille', 'nl': 'achternaam', 'de': 'Familienname'}
            name_item.editDescriptions(mydescriptions, summary='Setting descriptions.')

            # 'name_item' is an instance of 'family_name_item'
            claim = pywikibot.Claim(repo, instance_of_prop)
            target = pywikibot.ItemPage(repo, family_name_item)
            claim.setTarget(target)
            name_item.addClaim(claim, summary=u'Adding claim "instance of family name"')

            name_item_id = name_item.getID()

            print("'{}' created!".format(family_name_str))

        # family name of 'person_item' is 'name_item'
        claim = pywikibot.Claim(repo, family_name_prop) #'Has family name'
        target = pywikibot.ItemPage(repo, name_item_id)
        claim.setTarget(target)
        person_item.addClaim(claim, summary=u'Adding claim "has family name"')
        print("'{}' has been linked to '{}'".format(family_name_str, person_label))
    else:
        print("'{}' is not an instance of 'human'".format(person_label))
'Nagaland' is not an instance of 'human'