#!/usr/bin/python3
#coding=utf-8

"""
MIT License

Copyright (c) 2020 Vit Baisa, Vit Suchomel, Marek Blahus

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

"""
MediaWiki API help:
https://www.mediawiki.org/w/api.php?action=help&modules=query
"""

VERSION = '1.3'

import re
import os
import sys
import argparse
# use requests
import urllib.request
from urllib.parse import quote as url_quote
import http.client # httplib.HTTPException
import datetime
import json
import time
from justext import core as justext
from lxml.etree import XMLSyntaxError, ParserError
from unicodedata import category as unicode_char_category

remove_links_re = re.compile('</?a[^>]*>')

class PageNotFound(Exception):
    pass

class RequestTimeout(Exception):
    pass

class InvalidResponse(Exception):
    pass

class EmptyHTML(Exception):
    pass

class EmptyJusText(Exception):
    pass

LATEST = 'https://dumps.wikimedia.org/%swiki/latest/%swiki-latest-all-titles-in-ns0.gz'
WIKI_URL = 'https://%s.wikipedia.org/wiki/'
API_HTML = 'https://%s.wikipedia.org/w/api.php?action=parse&page=%s&format=json'
API_JSON = 'https://%s.wikipedia.org/w/api.php?action=query&prop=revisions&titles=%s&format=json'

# TODO: look at https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&titles=xxx

JUSTEXT_PARAMS_BY_LEVEL = {
    'verystrict': { #Justext default
        'length_low': 70,
        'length_high': 200,
        'stopwords_low': 0.3,
        'stopwords_high': 0.32,
        'max_link_density': 0.2,
        'max_good_distance': 5,
        'max_heading_distance': 150,
    },
    'strict': { #recommended
        'length_low': 70,
        'length_high': 200,
        'stopwords_low': 0.25,
        'stopwords_high': 0.32,
        'max_link_density': 0.3,
        'max_good_distance': 5,
        'max_heading_distance': 150,
    },
    'balanced': {
        'length_low': 55,
        'length_high': 140,
        'stopwords_low': 0.2,
        'stopwords_high': 0.3,
        'max_link_density': 0.4,
        'max_good_distance': 5,
        'max_heading_distance': 200,
    },
    'permissive': {
        'length_low': 40,
        'length_high': 90,
        'stopwords_low': 0.2,
        'stopwords_high': 0.3,
        'max_link_density': 0.45,
        'max_good_distance': 10,
        'max_heading_distance': 300,
    },
}

def html2prevert(s, justext_wordlist, justext_level='strict', allowshort=False):
    # TODO: preclean HTML (remove tables, infoboxes, References, TOC, ...)
    try:
        html_root = justext.preprocess(html_text=s, encoding='utf-8')
        paragraphs = justext.make_paragraphs(html_root)
    except (ParserError, XMLSyntaxError):
        return ('', 0, 0)
    #use Justext to classify paragraphs
    j_length_low = JUSTEXT_PARAMS_BY_LEVEL[justext_level]['length_low']
    j_length_high = JUSTEXT_PARAMS_BY_LEVEL[justext_level]['length_high']
    j_max_heading_distance = JUSTEXT_PARAMS_BY_LEVEL[justext_level]['max_heading_distance']
    if allowshort:
        j_length_low = j_length_low / 3
        j_length_high = j_length_high / 3
        j_max_heading_distance = j_max_heading_distance / 3
    justext.classify_paragraphs(
        paragraphs=paragraphs,
        stoplist=justext_wordlist,
        length_low=j_length_low, #character count < length_low => bad or short
        length_high=j_length_high, #character count > length_high => good
        stopwords_low=JUSTEXT_PARAMS_BY_LEVEL[justext_level]['stopwords_low'], #number of words frequent in the language >= stopwords_low => neargood
        stopwords_high=JUSTEXT_PARAMS_BY_LEVEL[justext_level]['stopwords_high'], #number of words frequent in the language >= stopwords_high => good or neargood
        max_link_density=JUSTEXT_PARAMS_BY_LEVEL[justext_level]['max_link_density'] #density of link words (words inside the <a> tag) > max_link_density => bad
    )
    justext.revise_paragraph_classification(
        paragraphs=paragraphs,
        max_heading_distance=j_max_heading_distance #Short/near-good heads in the distance [chars] before a good par => good
    )
    #extract good paragraphs
    prevert_paragraphs, paragraph_count, plaintext_len = [], 0, 0
    for p in paragraphs:
        #if p['class'] == 'good': # TODO find why this does not produce a good result
        if p['cfclass'] in ('good', 'neargood'): #'good', 'neargood', 'short', 'bad'
            p_text = justext.html_escape(p['text']).strip()
            if p_text:
                paragraph_count += 1
                plaintext_len += len(p_text)
                heading = ' heading="yes"' if p['heading'] else ''
                prevert_paragraphs.append('<p%s>\n%s\n</p>' % (heading, p_text))
    return ('\n'.join(prevert_paragraphs), paragraph_count, plaintext_len)

def api_wait(last, wait_interval):
    n = datetime.datetime.now()
    interval = (n-last).seconds + ((n-last).microseconds / 1.0e6)
    if interval < wait_interval:
        time.sleep(wait_interval - interval)

def process_page(langcode, title, linksf, raw_response_fp, justext_wordlist, logf,
        last_api_parse, wait_interval, justext_level, allowshort):
    api_wait(last_api_parse, wait_interval)
    api_url = API_HTML % (langcode, url_quote(title))

    try:
        response_data = urllib.request.urlopen(api_url, timeout=10).read()
    except HTTPError as e:
        raise PageNotFound()
    except URLError as e:
        if isinstance(e.reason, socket.timeout):
            raise RequestTimeout()
        else:
            raise PageNotFound()
    except socket.timeout as e:
        raise RequestTimeout()
    parse_time = datetime.datetime.now()
    try:
        response_data = response_data.decode('utf-8', errors='strict')
    except UnicodeDecodeError:
        logf.write('\tignoring a UnicodeDecodeError\n')
        response_data = response_data.decode('utf-8', errors='ignore')
    data = json.loads(response_data)
    if not data or 'error' in data:
        raise InvalidResponse()
    #store the API response to allow re-processing without downloading in the future
    raw_response_fp.write('%s\t%d\n' % (api_url, len(response_data) + 1))
    raw_response_fp.write(response_data)
    raw_response_fp.write('\n')
    #parse the API response
    p = data['parse']
    html = p['text']['*'].strip()
    if html:
        #remove <a/> tags (Justext makes extra spaces there) # TODO: correct Justext and remove
        html = remove_links_re.sub('', html)
        prevert, paragraph_count, plaintext_len = html2prevert(
            html.encode('utf-8'), justext_wordlist, justext_level, allowshort) # justext decodes!
    else:
        raise EmptyHTML()
    if not prevert:
        raise EmptyJusText()
    revid = p['revid']
    langlinks_len = len(p['langlinks'])
    categories = '|'.join([d['*'].replace('"', '') for d in p['categories']])
    if linksf and p['externallinks']:
        linksf.write('### %s\n' % title)
        linksf.write('%s\n' % '\n'.join(p['externallinks']))
    logf.write('\t%d chars\n' % plaintext_len)
    page_attrs = 'url="%s" title="%s" wiki_categories="%s" wiki_translations="%d" ' \
            'paragraphs="%d" chars="%d" crawl_date="%s"' % \
            ((WIKI_URL % langcode) + title, title, categories,
            langlinks_len, paragraph_count, plaintext_len,
            parse_time.strftime('%Y-%m-%d %H:%M'))
    page = '<doc %s>\n%s\n</doc>\n' % (page_attrs, prevert)
    return (page, paragraph_count, revid, parse_time)

def go_page(langcode, title, linksf, raw_response_fp, newest, justext_wordlist, logf, last_api_request,
        last_api_parse, wait_interval, justext_level, allowshort, cache, cf, hits_by_type):
    page, parlen, revid = '', 0, 0
    #check the cache first
    if title in cache:
        #download the newest revision if there is an old version in the cache
        if newest:
            previous_revid = cache[title]
            api_wait(last_api_request, wait_interval)
            last_api_request = datetime.datetime.now()
            api_url = API_JSON % (langcode, url_quote(title))
            resp = urllib.request.urlopen(api_url)
            data = json.load(resp)
            dqp = data['query']['pages']
            for key in dqp.keys():
                try:
                    current_revid = dqp[key]['revisions'][0]['revid']
                except (KeyError, IndexError):
                    logf.write('\tusing old revision %s instead of the newest '
                        'revision (invalid Wiki API response data)\n' % previous_revid)
                    current_revid = previous_revid
                #skip if cached is already newest
                if current_revid == previous_revid:
                    hits_by_type['skipped'] += 1
                    logf.write('\tskipping cached\n')
                    return (page, parlen, revid, last_api_parse)
                #continue to download the page otherwise
        #skip because in cache
        else:
            hits_by_type['skipped'] += 1
            logf.write('\tskipping already downloaded\n')
            return (page, parlen, revid, last_api_parse)
    #download the page since it is not in the cache or there is a new version
    try:
        page, parlen, revid, last_api_parse =\
                process_page(langcode, title, linksf,
                raw_response_fp, justext_wordlist, logf,
                last_api_parse, wait_interval,
                justext_level, allowshort)
        hits_by_type['processed'] += 1
        logf.write('\t%d paragraphs\n' % parlen)
    except Exception as e: #PageNotFound, RequestTimeout, InvalidResponse, EmptyHTML, EmptyJusText
        page = ''
        hits_by_type['empty'] += 1
        log_msg = {
            'PageNotFound': '\tskipped -- page not found',
            'RequestTimeout': '\tskipped -- request timeout',
            'InvalidResponse': '\tskipped -- invalid response',
            'EmptyHTML': '\tempty HTML parse returned by API',
            'EmptyJusText': '\tempty prevert returned by jusText'
        }.get(type(e).__name__, 'tskipped or empty -- %s' % type(e).__name__)
        logf.write('%s\n' % log_msg)
    #update the cache (previous records for the same tile are replaced when reloading the cache)
    if newest:
        cache[title] = revid #zero if page not found/empty/exception
    else:
        cache.add(title)
    cf.write('%s\t%s\n' % (title, revid))
    return (page, parlen, revid, last_api_parse)

def main(langcode, cachefn, raw_response_path, newest, links, justext_wordlist,
        logf, wait_interval, nicetitles, talkpages, justext_level, allowshort,
        title_file_path=''):
    last_api_request = datetime.datetime.now()
    last_api_parse   = datetime.datetime.now()

    if len(justext_wordlist) == 0:
        logf.write('Wordlist file is empty, switching off stopwords detection.\n')
        JUSTEXT_PARAMS_BY_LEVEL[justext_level]['stopwords_low'] = 0
        JUSTEXT_PARAMS_BY_LEVEL[justext_level]['stopwords_high'] = 0

    linksf = open(links, 'a') if links else None
    cache = {} if newest else set()
    if os.path.exists(cachefn):
        logf.write('Cache: %s\n' % cachefn)
        with open(cachefn) as cf:
            for line in cf:
                try:
                    title, revid = line.split('\t')
                    if newest:
                        cache[title.strip()] = revid.strip()
                    else:
                        cache.add(title.strip())
                except ValueError:
                    continue
        logf.write('Cache: %d titles loaded\n' % len(cache))

    langcode2 = langcode.replace('-', '_')
    wikidump_titles_url = LATEST % (langcode2, langcode2)
    if not title_file_path:
        title_file_path = wikidump_titles_url.rsplit('/', 1)[-1].replace('.gz', '')
    if not os.path.exists(title_file_path):
        logf.write('Getting all titles from latest Wikipedia dump %s to %s\n' %
            (wikidump_titles_url, title_file_path))
        wiki_title_data = urllib.request.urlopen(wikidump_titles_url).read()
        if wikidump_titles_url.endswith('.gz'):
            from io import BytesIO
            from gzip import GzipFile
            bio = BytesIO(wiki_title_data)
            bio.seek(0)
            wiki_title_data = GzipFile(fileobj=bio).read()
        with open(title_file_path, 'wb') as title_file:
            title_file.write(wiki_title_data)

    cf = open(cachefn, 'at') # cache file
    raw_response_fp = open(raw_response_path, 'at') #raw API responses
    hits_by_type = {'processed': 0, 'skipped': 0, 'empty': 0}
    for line in open(title_file_path, 'rt', encoding='utf-8', errors='ignore'):
        title = line.strip().replace('"', "'")
        # TODO: filter titles, use RE as parameter
        logf.write('%s\n' % title)
        if not title or nicetitles and not unicode_char_category(title[0])[0] in ('L', 'N'):
            logf.write('\tskipping (not a nice title)\n')
            continue
        page_titles = (title, 'Talk:' + title) if talkpages else (title,)
        for page_title in page_titles:
            page, parlen, revid, last_api_parse =\
                    go_page(langcode, page_title, linksf,
                    raw_response_fp, newest, justext_wordlist, logf,
                    last_api_request, last_api_parse, wait_interval,
                    justext_level, allowshort, cache, cf, hits_by_type)
            if page:
                sys.stdout.write(page)
    logf.write('Updated cache database stored in %s\n' % cachefn)
    if linksf:
        linksf.close()
    cf.close()
    for hit_type, hit_count in hits_by_type.items():
        logf.write('%s: %d\n' % (hit_type.title(), hit_count))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Wikipedia downloader')
    parser.add_argument('langcode', help='Wikipedia language prefix', type=str)
    parser.add_argument('wordlist', help='Path to a list of ~2000 most frequent words in the language (UTF-8, one per line)', type=str)
    parser.add_argument('--cache', help='File with previously downloaded pages and data', type=str, default='')
    parser.add_argument('--wait', help='Time interval between GET requests', type=float, default=1.0)
    parser.add_argument('--newest', help='Download the newest versions of articles', action='store_true')
    parser.add_argument('--links', help='Gather external links from Wikipedia', type=str, default='')
    parser.add_argument('--nicetitles', help='Download only titles starting with an alphabetical or numerical character', action='store_true')
    parser.add_argument('--talkpages', help='Download talk pages', action='store_true')
    parser.add_argument('--cleaning', help='Level of Justext boilerplate & short paragraph removal strictness (default = strict)',
        type=str, choices=('verystrict', 'strict', 'balanced', 'permissive'), default='strict')
    parser.add_argument('--allowshort', help='Allow three times shorter texts. Useful for ideographic scripts.', action='store_true')
    parser.add_argument('--title-file', help='Path to a custom list of titles to download, one per line.', type=str, default='')
    args = parser.parse_args()
    cachefile = args.cache or args.langcode + 'wiki.cache'
    raw_response_file = (args.cache or args.langcode) + '_raw_data'
    with open(args.wordlist) as fp:
        justext_wordlist = set([line.rstrip() for line in fp])
    logfn = args.langcode.replace('/','') + '_' + datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + '.log'
    with open(logfn, 'w', buffering=1) as logfile:
        main(args.langcode, cachefile, raw_response_file, args.newest, args.links,
            justext_wordlist, logfile, args.wait, args.nicetitles, args.talkpages,
            args.cleaning, args.allowshort, args.title_file)
