import pywikibot
from pywikibot import pagegenerators
from pywikibot.data.api import APIError

wikidata_site = pywikibot.Site('wikidata', 'wikidata')
repo = wikidata_site.data_repository()

propToPurge = 'P814'
snaktypesToRemove = [ 'novalue', 'somevalue' ] # list of snaktypes; https://doc.wikimedia.org/pywikibot/master/api_ref/pywikibot.html?highlight=snaktype#pywikibot.Claim.getSnakType
editSummary = "remove [[Property:{}]]: ''{}''; per request at [[Special:Diff/862746716]]"

whitelist = [ 'Q1971408', 'Q15856098', 'Q52092068', 'Q52092070', 'Q22348284', 'Q1265878', 'Q15059746', 'Q15835591', 'Q22569645', 'Q22054793', 'Q56369925', 'Q798148', 'Q1970824', 'Q1971182', 'Q15842801', 'Q13968510', 'Q15812385', 'Q1813410', 'Q15853333', 'Q2176674', 'Q15058120', 'Q15836452', 'Q52144571', 'Q1646403', 'Q15809591', 'Q1156775', 'Q15853332', 'Q15854804', 'Q13744957', 'Q13747595', 'Q15853330', 'Q15853331', 'Q53294041', '' ]
dataset_query = """SELECT DISTINCT ?item WITH {
  SELECT DISTINCT ?item WHERE {
    ?item wdt:P31/wdt:P279* wd:Q759421 .
  }
} AS %subquery WHERE {
  INCLUDE %subquery .
  ?item wdt:P131* wd:Q1200 .
  {
    ?item rdf:type wdno:P814 .
    BIND('novalue' AS ?type) .
  } UNION {
    ?item wdt:P814 ?value .
    FILTER(ISBLANK(?value)) .
    BIND('somevalue' AS ?type) .
  }
}"""

for Qitem in pagegenerators.WikidataSPARQLPageGenerator(dataset_query, site=wikidata_site):
    Qitem.get()
    
    if not Qitem.claims or propToPurge not in Qitem.claims:
        continue
        
    if Qitem.title() not in whitelist:
        continue
    
    for claim in Qitem.claims[propToPurge]:
        snaktype = claim.getSnakType()
        
        if snaktype not in snaktypesToRemove:
            continue
        if claim.getTarget() != None: # just to make sure
            continue
        if len(claim.getSources()) != 0: # do not work on sourced statements
            continue

        try:
            Qitem.removeClaims([claim], summary=editSummary.format(propToPurge, snaktype))
            print('* {}: removed {}: {}'.format(Qitem.title(), propToPurge, snaktype))
        except APIError as e:
            print('{}\tcannot remove novalue due to APIerror: {}'.format(Qitem.title(), e))
        
print('All done, job finished')