#!/usr/bin/env python3
"""Build ../index.html from template.html + the reconstructed code-book.

Run from the folder friedman-special-code-problem/:
    python3 work/build_report.py
Writes index.html and results.json.
"""
import bisect, json, os, re, statistics, sys
from collections import Counter

sys.path.insert(0, 'work')
from load import load
from steps import STEPS, DOUBTS

msgs = load('work/messages.txt')
book = []
for line in open('work/codebook.txt'):
    g, w = line.split(None, 1)
    book.append({'g': g, 'w': w.strip()})
B = {e['g']: e['w'] for e in book}

# ---- consistency checks -------------------------------------------------
cnt = Counter(g for m in msgs for g in m['g'])
assert set(cnt) == set(B), 'code-book does not cover the groups exactly'
ws = [e['w'] for e in book]
assert ws == sorted(ws), 'code-book is not in alphabetical order'
for m in msgs:
    n = int(re.search(r'(\d+) words', m['hdr']).group(1))
    assert n == len(m['g']), m['hdr']

step_of = {}
for i, s in enumerate(STEPS, 1):
    for g in s['groups'].split():
        step_of[g] = i
assert set(step_of) == set(B)

# ---- dictionary-rank evidence ------------------------------------------
def wordlist(path):
    return sorted(set(l.split()[0].lower() for l in open(path)
                      if l.strip() and l.split()[0].isalpha()))

lists = {
    'top60k': '../skydrop-scroll-puzzle/data/words60k.txt',
    'web2': '/usr/share/dict/web2',
}
ranks, stats = {}, {}
for name, path in lists.items():
    if not os.path.exists(path):
        continue
    wl = wordlist(path)
    r = [bisect.bisect_left(wl, e['w'].lower()) for e in book]
    ranks[name] = r
    y = [int(e['g']) for e in book]
    stats[name] = {'n_words': len(wl), 'pearson_r': round(statistics.correlation(r, y), 5)}
    # leave-one-out interpolation error
    errs = []
    for i in range(1, len(book) - 1):
        g0, g1, g2 = y[i - 1], y[i], y[i + 1]
        if g2 - g0 < 100 or r[i + 1] == r[i - 1]:
            continue
        errs.append(abs((g1 - g0) / (g2 - g0) - (r[i] - r[i - 1]) / (r[i + 1] - r[i - 1])))
    errs.sort()
    stats[name]['loo_median_err'] = round(statistics.median(errs), 3)
    stats[name]['loo_p90_err'] = round(errs[int(.9 * len(errs))], 3)

slot = json.load(open('work/slot_test.json'))

LETTERS = {e['w'] for e in book if len(e['w']) == 1}
NUMWORDS = {'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'EIGHT', 'NINE', 'ZERO', 'TWELVE', 'FIFTEEN',
            'SIXTEEN', 'TWENTY', 'NINETY', 'HUNDRED', 'SIXTH', 'EIGHTH'}
for i, e in enumerate(book):
    e['n'] = cnt[e['g']]
    e['step'] = step_of[e['g']]
    e['kind'] = ('stop' if e['w'] == 'STOP' else 'letter' if e['w'] in LETTERS
                 else 'num' if e['w'] in NUMWORDS else 'word')
    if e['g'] in DOUBTS:
        e['doubt'] = DOUBTS[e['g']]
    if 'top60k' in ranks:
        e['rank'] = ranks['top60k'][i]

# ---- clean plaintext (hand-smoothed: suffix groups joined, STOP -> full stop) ----
CLEAN = [
    "MESSAGE ONE FIVE. TO GENERAL SMITH. RECENT INFORMATION FROM CAPTURED PRISONER OF WAR INDICATES THAT ENEMY IS "
    "PLANNING TO ATTACK AT DAWN ON THURSDAY. KEEP YOUR FORCES ON ALERT. WE WILL PROVIDE AIR SUPPORT FOR YOUR FORCES. "
    "KEEP IN RADIO CONTACT WITH OUR HEADQUARTERS. ENEMY CAN BE EXPECTED TO ATTEMPT TO OVERRUN YOUR POSITIONS USING "
    "TANKS AND INFANTRY. CASUALTY REPORT FOR TODAY FOLLOWS: TWO KILLED, SIXTEEN WOUNDED AND SIX MISSING. "
    "SIGNED GENERAL DAVIDSON.",
    "MESSAGE THREE. FOR GENERAL DAVIDSON. ACKNOWLEDGE YOUR MESSAGE FIFTEEN. OUR TROOPS HAVE BEEN PUT ON ALERT AND WE "
    "ARE PREPARED FOR ENEMY ATTACK. WE WILL STAY IN RADIO CONTACT WITH YOUR HEADQUARTERS. ANTI-TANK WEAPONS HAVE BEEN "
    "PUT IN POSITION AND WE ARE CONFIDENT OF OUR ABILITY TO REPULSE THE ENEMY. OUR MORALE IS HIGH. WE DO NEED MORE "
    "AMMUNITION AND GASOLINE. IS IT POSSIBLE TO AIR-DROP THESE SUPPLIES? SIGNED SMITH.",
    "MESSAGE NUMBER SIXTEEN. FOR GENERAL SMITH. FURTHER AMPLIFICATION OF OUR MESSAGE FIFTEEN FOLLOWS: PRISONER OF WAR "
    "IS FROM ENEMY'S EIGHTH DIVISION. HIS UNIT HAS MOVED INTO THE VICINITY OF HILL 9800 (NINE EIGHT ZERO ZERO) AND ALL "
    "DIVISIONAL TROOPS HAVE BEEN SPECIALLY BRIEFED FOR OPERATIONS TO COMMENCE AT TWELVE HUNDRED HOURS ON THURSDAY. "
    "TO COUNTER THIS ENEMY ATTACK WE ARE BRINGING IN A BRIGADE OF HEAVY ARTILLERY FROM ARMY RESERVE FORCES. IN ADDITION "
    "WE ARE ALERTING ONE DIVISION OF PARATROOPS TO JUMP BEHIND ENEMY FORCES NOW CONCENTRATED AROUND HILL NINETY-EIGHT "
    "HUNDRED. WE WILL KEEP YOU ADVISED. SIGNED GENERAL DAVIDSON.",
    "MESSAGE FOUR TO GENERAL DAVIDSON. WE URGENTLY NEED TO AIR-EVACUATE TWENTY-SIX WOUNDED. OUR MEDICAL FACILITY IS "
    "NOT ABLE TO HANDLE THESE WOUNDED CASES AS IT IS NOW ALMOST COMPLETELY FILLED. WE ALSO HAVE ONLY TWO DOCTORS "
    "AVAILABLE. IS IT POSSIBLE TO HAVE ADDITIONAL DOCTORS AND NURSES ASSIGNED TO THIS COMMAND? PLEASE REPLY SOONEST. "
    "SIGNED GENERAL SMITH",
    "MESSAGE NUMBER FIVE FOR GENERAL DAVIDSON. WE HAVE LOST CONTACT WITH SIXTH BRIGADE EAST OF US. CAN YOU REACH THEM "
    "BY TELEPHONE? SIGNED GENERAL SMITH",
    "MESSAGE SIX TO GENERAL DAVIDSON. CANCEL OUR MESSAGE FIFTEEN [read: FIVE]. WE HAVE JUST ESTABLISHED RADIO CONTACT "
    "WITH SIXTH BRIGADE. THEY ADVISE THAT THEY ARE RUNNING LOW ON AMMUNITION AND ENEMY HAS MADE FOUR PROBING ATTACKS "
    "IN LAST TWENTY-FOUR HOURS. SIGNED GENERAL SMITH.",
]

mout = []
for i, m in enumerate(msgs):
    no, route, time, words = [s.strip() for s in m['hdr'].split('|')]
    mout.append({'no': no, 'route': route, 'time': time.replace('Time ', ''), 'words': words,
                 'g': m['g'], 'clean': CLEAN[i]})

data = {
    'messages': mout,
    'book': book,
    'steps': [{'title': s['title'], 'why': s['why'], 'groups': s['groups'].split()} for s in STEPS],
    'stats': stats,
    'slot': slot,
}
json.dump({'codebook': {e['g']: e['w'] for e in book},
           'counts': {e['g']: e['n'] for e in book},
           'uncertain': DOUBTS, 'dictionary_rank_stats': stats, 'slot_tests': slot,
           'plaintext': {m['no']: m['clean'] for m in mout}},
          open('results.json', 'w'), indent=1)

html = open('work/template.html').read()
html = html.replace('/*__DATA__*/', 'const DATA = ' + json.dumps(data, separators=(',', ':')) + ';')
for k, v in {'__NGROUPS__': str(sum(len(m['g']) for m in msgs)), '__NDISTINCT__': str(len(book)),
             '__R60__': str(stats.get('top60k', {}).get('pearson_r', '')),
             '__RWEB2__': str(stats.get('web2', {}).get('pearson_r', '')),
             '__LOO__': str(stats.get('top60k', {}).get('loo_median_err', ''))}.items():
    html = html.replace(k, v)
open('index.html', 'w').write(html)
print('wrote index.html', len(html), 'bytes;', stats)
