#!/usr/bin/python

"""
MIT License

Copyright (c) 2016 Vit Baisa

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

import os
import sys
import argparse
import urllib2
import urllib
import datetime
import json
import time
import datetime
import gzip
from justext import core as justext
from lxml.etree import XMLSyntaxError, ParserError

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'
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'

last_api_request = datetime.datetime.now()
last_api_parse   = datetime.datetime.now()
logf = None

def html2prevert(s):
    try:
        html_root = justext.preprocess(html_text=s, encoding='utf-8')
        return justext.make_paragraphs(html_root)
    except (ParserError, XMLSyntaxError):
        return []

def api_wait(last):
    global wait_interval
    global logf
    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):
    global last_api_parse
    global logf
    api_wait(last_api_parse)
    last_api_parse = datetime.datetime.now()
    resp = urllib2.urlopen(API_HTML % (langcode, title))
    data = json.load(resp)
    if 'error' in data:
        raise MissingPage()
    p = data['parse']
    html = p['text']['*']
    if html.strip():
        pars = html2prevert(html.encode('utf-8')) # justext decodes!
    else:
        print >>logf, '\tempty HTML parse returned by API'
        raise EmptyHTML()
    if not pars:
        print >>logf, '\tempty prevert returned by jusText'
        raise EmptyJusText()
    outp = []
    for par in pars:
        parx = justext.html_escape(par['text'])
        outp.append(parx)
    revid = p['revid']
    langlinks_len = len(p['langlinks'])
    #links = '\v'.join([d['*'].replace('"', '') for d in p['links']])
    categories = '\v'.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 + '\n')
        linksf.write('\n')
    s = ''
    chars = 0
    for p in outp:
        s += '<p>\n'
        s += p
        s += '\n</p>\n'
        chars += len(p)
    print >>logf, '\t%d chars' % chars
    header = '<doc title="%s" categories="%s" translations="%d" paragraphs="%d" chars="%d">\n' %\
            (title, categories.encode('utf-8'), langlinks_len, 
                    #links.encode('utf-8'),
                    len(outp), chars)
    return header + s.encode('utf-8') + '</doc>\n', len(outp), revid

def main(langcode, cachefn, logfn, newest, links):
    global logf
    logf = open(logfn, 'w')
    print >>sys.stderr, "Log will be stored in %s" % logfn
    linksf = open(links, 'w') 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, 'w') # empty cache file
    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:
            title = line.strip().replace('"', "'")
            print >>logf, '%s' % title
            if title in cache:
                if newest: # download the newest revision
                    previous_revid = cache[title]
                    api_wait(last_api_request)
                    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 = process_article(langcode, title, linksf)
                                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 = process_article(langcode, title, linksf)
                    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', type=str, help='Wikipedia language prefix')
    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='')
    args = parser.parse_args()
    wait_interval = args.wait

    current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    logfile = current_time + '.log'
    cachefile = args.cache or args.langcode + 'wiki.cache'
    main(args.langcode, cachefile, logfile, args.newest, args.links)
