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

"""
MIT License

Copyright (c) 2016 Vit Baisa, Vit Suchomel

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.
"""

VERSION = '1.0.1'

import re
import os
import sys
import argparse
import urllib2
import urllib
import socket #socket.error
import datetime
import json
import time
import codecs
import datetime
import gzip
from justext import core as justext
from lxml.etree import XMLSyntaxError, ParserError
remove_links_re = re.compile(u'</?a[^>]*>')

from unicodedata import category as unicode_char_category

class MissingPage(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

def html2prevert(s, justext_wordlist):
    # 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
    justext.classify_paragraphs(
        paragraphs=paragraphs,
        stoplist=justext_wordlist,
        length_low=70, #character count < length_low => bad or short
        length_high=200, #character count > length_high => good
        stopwords_low=0.2, #number of words frequent in the language >= stopwords_low => neargood
        stopwords_high=0.3, #number of words frequent in the language >= stopwords_high => good or neargood
        max_link_density=0.4 #density of link words (words inside the <a> tag) > max_link_density => bad
    )
    justext.revise_paragraph_classification(
        paragraphs=paragraphs,
        max_heading_distance=200, #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 = u' heading="1"' if p['heading'] else u''
                prevert_paragraphs.append(u'<p%s>\n%s\n</p>' % (heading, p_text))
    return (u'\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_article(langcode, title, linksf, raw_response_fp, justext_wordlist, logf, last_api_parse, wait_interval):
    api_wait(last_api_parse, wait_interval)
    api_url = API_HTML % (langcode, title)
    try:
        response_data = urllib2.urlopen(api_url).read()
        parse_time = datetime.datetime.now()
    except urllib2.HTTPError:
        raise MissingPage()
    try:
        data = json.loads(response_data)
    except socket.error:
        raise MissingPage()
    if not data or 'error' in data:
        raise MissingPage()
    #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 decodes!
    else:
        print >>logf, '\tempty HTML parse returned by API'
        raise EmptyHTML()
    if not prevert:
        print >>logf, '\tempty prevert returned by jusText'
        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)
        for line in p['externallinks']:
            linksf.write(line.encode('utf-8') + '\n')
        linksf.write('\n')
    print >>logf, '\t%d chars' % plaintext_len
    article_attrs = 'url="%s" title="%s" categories="%s" translations="%d" paragraphs="%d" chars="%d" downloaded="%s"' % \
            ((WIKI_URL % langcode) + title, title, categories.encode('utf-8'),
            langlinks_len, paragraph_count, plaintext_len,
            parse_time.strftime('%Y-%m-%d %H:%M'))
    article = '<doc %s>\n%s\n</doc>\n' % (article_attrs, prevert.encode('utf-8'))
    return (article, paragraph_count, revid, parse_time)

def main(langcode, cachefn, raw_response_path, logfn, newest, links, justext_wordlist, logf, wait_interval, nicetitles):
    last_api_request = datetime.datetime.now()
    last_api_parse   = datetime.datetime.now()

    linksf = open(links, 'a') if links else None
    cache = {}
    if os.path.exists(cachefn):
        print >>logf, 'Cache: %s' % cachefn
        with open(cachefn) as cf:
            for line in cf:
                try:
                    title, revid = line.split('\t')
                    cache[title.strip()] = revid.strip()
                except ValueError:
                    continue
    cf = open(cachefn, 'a') # cache file
    raw_response_fp = open(raw_response_path, 'a') #raw API responses
    print >>logf, 'Getting all titles from latest Wikipedia dump'
    processed_articles = 0
    skipped_articles = 0
    empty_articles = 0
    filename, _ = urllib.urlretrieve(LATEST % (langcode, langcode))
    with gzip.open(filename) as df:
        for line in df:
            # TODO: download also talk pages
            title = line.strip().replace('"', "'")
            # TODO: filter titles, use RE as parameter
            print >>logf, '%s' % title
            if nicetitles and not unicode_char_category(unicode(title, 'utf-8')[0])[0] == 'L':
                print >>logf, '\tskipping (not a nice title)'
                continue
            if title in cache:
                if newest: # download the newest revision
                    previous_revid = cache[title]
                    api_wait(last_api_request, wait_interval)
                    last_api_request = datetime.datetime.now()
                    resp = urllib2.urlopen(API_JSON % (langcode, title))
                    data = json.load(response)
                    try:
                        dqp = data['query']['pages']
                        for key in dqp.keys():
                            current_revid = dqp[key]['revisions']['revid']
                            if previous_revid != current_revid:
                                article, parlen, revid, last_api_parse =\
                                        process_article(langcode, title, linksf,
                                        raw_response_fp, justext_wordlist, logf,
                                        last_api_parse, wait_interval)
                                cache[title] = revid
                                cf.write(title + '\t' + revid + '\n')
                            else:
                                print >>logf, '\tskipping cached'
                    except (MissingPage, EmptyHTML, EmptyJusText):
                        article = ''
                        empty_articles += 1
                else:
                    # do not download
                    print >>logf, '\tskip already downloaded'
                    skipped_articles += 1
                    article = ''
            else:
                try:
                    article, parlen, revid, last_api_parse =\
                            process_article(langcode, title, linksf,
                            raw_response_fp, justext_wordlist, logf,
                            last_api_parse, wait_interval)
                    cache[title] = revid
                    cf.write('%s\t%d\n' % (title, revid))
                    print >>logf, '\t%d paragraphs' % parlen
                    processed_articles += 1
                except (MissingPage, EmptyHTML, EmptyJusText):
                    article = ''
                    empty_articles += 1
            if article:
                sys.stdout.write(article)
    print >>logf, 'Updated cache database stored in %s' % cachefn
    linksf.close()
    cf.close()
    print >>logf, 'Processed: %d' % processed_articles
    print >>logf, 'Empty: %d' % empty_articles
    print >>logf, 'Skipped: %d' % skipped_articles
    logf.close()

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='Directory 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 alphabetical character', action='store_true')
    args = parser.parse_args()
    logfn = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S') + '.log'
    logfile = open(logfn, 'w')
    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.decode('utf-8').rstrip() for line in fp])
    main(args.langcode, cachefile, raw_response_file, logfile, args.newest, args.links, justext_wordlist, logfile, args.wait, args.nicetitles)
