"""Neutrality audit of the page text: words, sentences, readability, sentiment and citations per side.
Usage: python3 -I audit.py <index.html> <nltk_data dir>"""
import re, sys, html, json, statistics as st
import nltk
nltk.data.path.insert(0, sys.argv[2])
from nltk.sentiment import SentimentIntensityAnalyzer
src = open(sys.argv[1], encoding='utf-8').read()
sia = SentimentIntensityAnalyzer()

def clean(fragment):
    fragment = re.sub(r'<sup[\s\S]*?</sup>', '', fragment)
    return html.unescape(re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', ' ', fragment))).strip()

def blocks(pattern):
    return [clean(m.group(1)) for m in re.finditer(pattern, src)]

def syllables(word):
    w = re.sub(r'[^a-z]', '', word.lower())
    if not w: return 0
    groups = re.findall(r'[aeiouy]+', w)
    n = len(groups) - (1 if w.endswith('e') and not w.endswith(('le', 'ee')) and len(groups) > 1 else 0)
    return max(1, n)

def measure(texts):
    text = ' '.join(texts)
    sents = [s for s in re.split(r'(?<=[.!?])\s+', text) if re.search(r'[A-Za-z]', s)]
    words = re.findall(r"[A-Za-z][A-Za-z'’-]*", text)
    syl = sum(syllables(w) for w in words)
    wps, spw = len(words) / len(sents), syl / len(words)
    comp = [sia.polarity_scores(s)['compound'] for s in sents]
    return {'words': len(words), 'sentences': len(sents), 'words_per_sentence': round(wps, 1),
            'flesch_reading_ease': round(206.835 - 1.015 * wps - 84.6 * spw, 1),
            'fk_grade': round(0.39 * wps + 11.8 * spw - 15.59, 1),
            'sentiment_mean': round(st.mean(comp), 3), 'positive_sentences': sum(c > .05 for c in comp), 'negative_sentences': sum(c < -.05 for c in comp)}

out = {}
for side in ('cap', 'soc'):
    args = blocks(r'<article class="arg %s"[^>]*>([\s\S]*?)</article>' % side)
    thinkers = blocks(r'<figure class="thinker %s"[^>]*>([\s\S]*?)</figure>' % side)
    m = measure(args)
    m['blocks'] = len(args)
    m['thinker_words'] = len(re.findall(r"[A-Za-z][A-Za-z'’-]*", ' '.join(thinkers)))
    sec = re.findall(r'<article class="arg %s"[\s\S]*?</article>' % side, src)
    m['citations'] = len(set(re.findall(r'href="#ref-(\d+)"', ' '.join(sec))))
    out[side] = m
print(json.dumps(out, indent=1))
