#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2015 Alexandre Detiste <alexandre@detiste.be>
# SPDX-License-Identifier: GPL-2.0-or-later

# a simple spider to locate Wikipedia url
# in per-engine-wiki pages
# we don't rescan games we already have

import sys
import time
import urllib.request

from bs4 import BeautifulSoup

from game_data_packager.game import load_games
from game_data_packager.util import AGENT

CSV = 'data/wikipedia.csv'

try:
    todo = sys.argv[1]
except IndexError:
    todo = '*'

urls = dict()
with open(CSV, 'r', encoding='utf8') as f:
    for line in f.readlines():
        line = line.strip()
        if not line:
            continue
        shortname, url = line.split(';', 1)
        urls[shortname] = url


def is_wikipedia(href: str) -> bool:
    return bool(href) and "wikipedia" in href


for shortname, game in load_games(game=todo).items():
    if not game.wiki:
        continue
    if shortname in urls:
        continue

    print('processing %s ...' % shortname)
    url = game.wikibase + game.wiki
    html = urllib.request.urlopen(urllib.request.Request(url,
                                  headers={'User-Agent': AGENT}))
    soup = BeautifulSoup(html, 'lxml')
    for tag in soup.find_all(href=is_wikipedia):
        print('  ' + tag['href'])
        urls[shortname] = tag['href']

    # break
    time.sleep(1)

# write it back
with open(CSV, 'w', encoding='utf8') as f:
    for shortname in sorted(urls.keys()):
        f.write(shortname + ';' + urls[shortname] + '\n')
