import pywikibot
from pywikibot import pagegenerators as pg

def list_template_usage(site_obj, tmpl_name):
    name = "{}:{}".format(site.namespace(10), tmpl_name)
    tmpl_page = pywikibot.Page(site, name)
    ref_gen = pg.ReferringPageGenerator(tmpl_page, onlyTemplateInclusion=True)
    filter_gen = pg.NamespaceFilterPageGenerator(ref_gen, namespaces=[0])
    generator = site.preloadpages(filter_gen, pageprops=True)
    return generator

def check_for_statement(item, country):
    item_dict = item.get()
    claims = item_dict["claims"]
    try:
        country_claim = claims["P17"][0]
        if country_claim.target.id == country:
            return True
        else:
            return False
    except:
        return False

def add_country_claim(item, country, repo):
    claim = pywikibot.Claim(repo, "P17")
    target_item = pywikibot.ItemPage(repo, country)
    claim.setTarget(target_item)
    item.addClaim(claim, summary="Importing P17 from ar-wiki")

    source_target = pywikibot.ItemPage(repo, "Q199700") #Q199700 Arabic Wikipedia
    source_claim = pywikibot.Claim(repo, "P143", isReference=True)
    source_claim.setTarget(source_target)
    claim.addSources([source_claim])

template_name = "منطقة يمنية"
country = "Q805"
site = pywikibot.Site("ar", "wikipedia")
tmpl_gen = list_template_usage(site, template_name)

data_site = pywikibot.Site("wikidata", "wikidata")
repo = data_site.data_repository()
count = 0

for page in tmpl_gen:
    count += 1
    print("------({})------".format(count))
    try:
        item = pywikibot.ItemPage.fromPage(page)
    except:
        print("Not connected to Wikidata")
        continue
    try:
        print(item.get()["labels"]["ar"])
    except:
        pass
    country_set = check_for_statement(item, country)
    print("Country set:", country_set)
    if country_set == False:
        add_country_claim(item, country, repo)