import pywikibot
from pywikibot import pagegenerators as pg

query='select ?item where {?item wdt:P597 ?wta . ?item wdt:P1352 ?rang}'

def wd_sparql_query(spq):
   generator=pg.WikidataSPARQLPageGenerator(spq,site=pywikibot.Site('wikidata','wikidata'))
   for wd in generator:
     try:
       wd.get(get_redirect=True)
       yield wd
     except:
       pass

def fix(wd):
  rangclaim_enkel = wd.claims['P1352'][0]
  #qe = rangclaim_enkel.qualifiers
  rangclaim_dubbel = wd.claims['P1352'][1]
  qd=rangclaim_dubbel.qualifiers['P641']
  rangclaim_dubbel.removeQualifiers(qd)

  newclaim=pywikibot.Claim(repo,'P641');           #sport
  newtarget=pywikibot.ItemPage(repo,'Q18123885')   #tennis dubbel
  newclaim.setTarget(newtarget)
  rangclaim_dubbel.addQualifier(newclaim)

    
def actonone(wd):
  if (len(wd.claims['P1352'])==2):
    q1 = wd.claims['P1352'][0]
    if (q1.has_qualifier):
      x1 = q1.qualifiers
      q2 = wd.claims['P1352'][1]
      if (q2.has_qualifier):
        x2=q2.qualifiers
    
      if ('P641' in x1) and ('P641' in x2):
        if (x1['P641']==x2['P641']):  
          print(f'fix {wd.title()}')
          fix(wd)
          return(1)  
        
    
    else:
       print(wd.title())    
       print('skip')
       return(0)
  return(0)
    
site = pywikibot.Site('wikidata','wikidata')           #Geef aan naar welke site je wilt schrijven
repo = site.data_repository()                     #voor ophalen wikidata-items adhv Qxxxx
print('Start')
if (False):
  print('Say')  
  player=pywikibot.ItemPage(repo,'Q445472')
  player=pywikibot.ItemPage(repo,'Q47087780')
  player=pywikibot.ItemPage(repo,'Q270967')
  player=pywikibot.ItemPage(repo,'Q461059')
  
  
  player.get(get_redirect=True)  
  actonone(player)
else: 
  print('False')  
  counter=0
  for player in wd_sparql_query(query):
    counter+=actonone(player)
    #if (10/(counter-4)>10):
    #    print('x')
Start
False