#!/usr/bin/env python3
# order_steps.py: the article order of cmix-neif-1.0, built step by step from
# the article order of fx2-cmix.
#
# Usage: python3 order_steps.py <enwik9> <fx2-cmix new_article_order> <outdir>
#
# Input: enwik9 and src/readalike_prepr/data/new_article_order of fx2-cmix
# (https://github.com/kaitz/fx2-cmix). All lists are unit numbers, one per line,
# in the format of that file: a unit number counts the non-redirect pages of
# enwik9 (0-based), a page being a redirect if one of its lines starts with
# '      <text xml:space="preserve">' followed by #REDIRECT, #redirect,
# #Redirect, #REdirect or {{softredirect (rule of fx2-cmix article_remap.cpp).
# The lists hold 172,277 of the 172,315 units, like the fx2-cmix file.
#
# Output in <outdir>, one list per step, with its sha256 against the expected
# value:
#   step1_wikipedia_last.txt   step 1: pages titled "Wikipedia:..." at the end
#                              (the file shipped with cmix-lex)
#   step2_classes_by_id.txt    step 2: class blocks by descending unit number
#   step3_project_pages.txt    step 3: Wikipedia:/Help:/MediaWiki: pages behind
#                              the image block; input of encode_order
#   step4_calendar_block.txt   step 4: calendar block; the order that
#                              cmix-neif-1.0 decodes from its residual
#                              (= new_article_order_fx2format.txt)
#
# Needs Python 3, about 1 GB of RAM and 15 s.
# License: GNU GPL version 3, like cmix-neif-1.0.

import hashlib
import os
import re
import sys

EXPECTED = {
    'step1_wikipedia_last.txt':
        'eecd462c29319bab185b48229c4d09ab52f16ca9c582e8e32eff9a7c2a7de39e',
    'step2_classes_by_id.txt':
        'ea1e64b0afd72fea3604f3eb5f21265b4c27fb80b5d41c0ad61def66f65a6ce4',
    'step3_project_pages.txt':
        '57a05c998d9a868e59129df5be72a1302a3f65571f266872e0a7abce03a17b57',
    'step4_calendar_block.txt':
        'c5170101aae4e99702af64c84c51c2801aa2fb0b65fe94028d6bf67d9ed98318',
}

REDIRECT_LINES = [b'\n      <text xml:space="preserve">' + p for p in
                  (b'#REDIRECT', b'#redirect', b'#Redirect', b'#REdirect',
                   b'{{softredirect')]

# Detection strings of the manual sort step of the fx2-cmix order
# (fx2-cmix src/article_order/manual-sort.ipynb, Byron Knoll).
CENSUS = [
    b'According to the [[United States Census Bureau]],',
    b'According to the [[U.S. Census Bureau]],',
    b'As of the [[2000]] census,',
    b'According to the [[2000]] census, ',
    b'According to the [[United States Census Bureau|U.S. Census Bureau]],',
    b'According to the [[US Census Bureau]], ',
    b'According to the U.S. Census,',
    b'As of the 2000 ',
    b'As of the census of 2000,',
]
DISAM_TEMPLATE = re.compile(rb'\{\{[Dd]isam.*\}\}')

NORMAL, CENSUS_C, IMAGE, DISAM, GEO, HNDIS = range(6)


def page_class(title, content):
    """Class of a page as in the manual sort step: the later test wins."""
    k = NORMAL
    if any(c in content for c in CENSUS):
        k = CENSUS_C
    if title.startswith(b'Image:'):
        k = IMAGE
    if b'(disambiguation)' in title or DISAM_TEMPLATE.search(content):
        k = DISAM
    if b'{{geodis}}' in content:
        k = GEO
    if b'{{hndis' in content:
        k = HNDIS
    return k


MONTHS = [b'January', b'February', b'March', b'April', b'May', b'June',
          b'July', b'August', b'September', b'October', b'November',
          b'December']


def kal_num(s):
    if len(s) == 0 or len(s) > 6 or not s.isdigit():
        return None
    return int(s)


def kal_mk(group, v):
    return (group << 32) | ((v + (1 << 30)) & 0xFFFFFFFF)


def kal_key(s):
    """Calendar key of a title, -1 for no calendar title (port of
    ord::KalKey in src/readalike_prepr/order_codec.h of cmix-neif-1.0).
    Groups: 0 year, 1 decade, 2 century, 3 millennium, 4 day, 5 month,
    6 month of a year, 7 deaths or births in a year."""
    n = len(s)
    for mo, w in enumerate(MONTHS):
        l = len(w)
        if s[:l] == w:
            if n == l:
                return kal_mk(5, mo)
            v = kal_num(s[l + 1:]) if s[l:l + 1] == b' ' else None
            if v is None:
                return -1
            if n - l - 1 <= 2:
                return kal_mk(4, (mo + 1) * 32 + v)
            if n - l - 1 == 4:
                return kal_mk(6, v * 16 + mo)
            return -1
    if n > 10 and s[:10] in (b'Deaths in ', b'Births in '):
        v = kal_num(s[10:]) if n <= 14 else None
        return kal_mk(7, 2 * v + (s[:1] == b'B')) if v is not None else -1
    bc = n > 3 and s[n - 3:] == b' BC'
    m = n - 3 if bc else n
    i = 0
    while i < m and 0x30 <= s[i] <= 0x39:
        i += 1
    v = kal_num(s[:i])
    if v is None:
        return -1
    sv = -2 * v - 1 if bc else 2 * v
    if i == m:
        return kal_mk(0, sv) if i <= 4 else -1
    if i + 1 == m and s[i:i + 1] == b's' and s[i - 1:i] == b'0':
        return kal_mk(1, sv)
    if m - i > 2 and s[i:i + 2] in (b'st', b'nd', b'rd', b'th'):
        rest = s[i + 2:m]
        if rest == b' century':
            return kal_mk(2, sv)
        if rest == b' millennium':
            return kal_mk(3, sv)
    return -1


def scan_units(path):
    """Title and class of every unit (non-redirect page) of enwik9."""
    data = open(path, 'rb').read()
    titles, classes = [], []
    pos = 0
    while True:
        s = data.find(b'  <page>\n', pos)
        if s < 0:
            break
        e = data.find(b'  </page>\n', s)
        if e < 0:
            break                          # the last page of enwik9 is cut off
        e += 10
        page = data[s:e]
        pos = e
        if any(r in page for r in REDIRECT_LINES):
            continue
        a = page.find(b'<title>')
        b = page.find(b'</title>')
        title = page[a + 7:b]
        ts = page.find(b'<text xml:space="preserve">')
        te = page.find(b'</text>')
        content = page[ts + 27:te] if 0 <= ts < te else b''
        titles.append(title)
        classes.append(page_class(title, content))
    return titles, classes


def write_list(outdir, name, units):
    text = ''.join('%d\n' % u for u in units).encode()
    with open(os.path.join(outdir, name), 'wb') as f:
        f.write(text)
    sha = hashlib.sha256(text).hexdigest()
    ok = 'OK' if sha == EXPECTED[name] else 'DIFFERS'
    print('%-26s %d units  sha256 %s  %s' % (name, len(units), sha, ok))
    return ok == 'OK'


def main():
    if len(sys.argv) != 4:
        sys.exit('usage: order_steps.py <enwik9> <fx2-cmix new_article_order> <outdir>')
    enwik9, fx2_path, outdir = sys.argv[1:]
    os.makedirs(outdir, exist_ok=True)
    titles, klass = scan_units(enwik9)
    fx2 = [int(x) for x in open(fx2_path).read().split()]
    all_ok = True

    # Step 1 (Kaido Orav, fxcm_v26; the file of cmix-lex): the pages titled
    # "Wikipedia:..." move to the end, in their fx2-cmix order. Of the 907
    # pages, 904 come from the normal part, 3 from the disambiguation block.
    wp = [u for u in fx2 if titles[u].startswith(b'Wikipedia:')]
    wp_set = set(wp)
    step1 = [u for u in fx2 if u not in wp_set] + wp
    all_ok &= write_list(outdir, 'step1_wikipedia_last.txt', step1)

    # Step 2: the normal part keeps its order; behind it the five class blocks
    # census, image, disambiguation, geographic disambiguation, personal-name
    # disambiguation, each by descending unit number (= descending page id).
    # The 904 Wikipedia: pages of the normal part now end the normal part.
    step2 = [u for u in step1 if klass[u] == NORMAL]
    for k in (CENSUS_C, IMAGE, DISAM, GEO, HNDIS):
        step2 += sorted((u for u in step1 if klass[u] == k), reverse=True)
    all_ok &= write_list(outdir, 'step2_classes_by_id.txt', step2)

    # Step 3: the normal pages of the project namespaces (titles starting with
    # Wikipedia:, Help: or MediaWiki:, 907 pages) move as one group, in their
    # order, between the image block and the disambiguation block.
    proj = [u for u in step2 if klass[u] == NORMAL and
            titles[u].startswith((b'Wikipedia:', b'Help:', b'MediaWiki:'))]
    proj_set = set(proj)
    step3 = [u for u in step2 if klass[u] == NORMAL and u not in proj_set]
    step3 += [u for u in step2 if klass[u] in (CENSUS_C, IMAGE)]
    step3 += proj
    step3 += [u for u in step2 if klass[u] in (DISAM, GEO, HNDIS)]
    all_ok &= write_list(outdir, 'step3_project_pages.txt', step3)

    # Step 4: calendar block. Normal pages titled as a year, decade, century,
    # millennium, day, month, month of a year or deaths or births in a year
    # leave the normal part and form one block sorted by the calendar key of
    # the title (then by unit number). The block takes the place of the first
    # day page that is directly followed by another day page: it goes in
    # front of the first remaining normal page behind that day page.
    key = {u: kal_key(titles[u]) for u in step3 if klass[u] == NORMAL}
    cal = sorted((k, u) for u, k in key.items() if k >= 0)
    normal3 = [u for u in step3 if klass[u] == NORMAL]
    is_day = lambda u: key[u] >= 0 and key[u] >> 32 == 4
    anchor = next(i for i in range(len(normal3) - 1)
                  if is_day(normal3[i]) and is_day(normal3[i + 1]))
    n_kal = sum(1 for u in normal3[:anchor] if key[u] < 0)
    step4 = []
    seen = 0
    for u in step3:
        if klass[u] == NORMAL:
            if key[u] >= 0:
                continue
            if seen == n_kal:
                step4 += [v for _, v in cal]
            seen += 1
        step4.append(u)
    all_ok &= write_list(outdir, 'step4_calendar_block.txt', step4)
    print('calendar block %d pages in front of normal page %d' % (len(cal), n_kal))
    sys.exit(0 if all_ok else 1)


if __name__ == '__main__':
    main()
