#!/usr/bin/env python3

import sys
import re
from collections import defaultdict, Counter

choices=0
if len(sys.argv) > 1 and sys.argv[1] == 'choices':
  choices=1

token_re = re.compile(r'([^\s)]+)\)')
gram_punc_re = re.compile(r'\.|-|=|:')
def grams(node):
    #return [gram.lower() for tok in token_re.findall(node)
    return [gram for tok in token_re.findall(node)
            for gram in gram_punc_re.sub(' ', tok).split()
            if len(gram) > 1 and gram.isupper()]

# this isn't efficient for huge IGT samples
instances = {'trans':[], 'intrans':[]}
arggrams = Counter()
vgrams = Counter()

# EMB: I think we want this to be separate for transitives and intransitives
s_inst = 0
a_inst = 0
o_inst = 0

if choices:
    lines = sys.stdin.readlines()
    for gloss,text,gramtree in zip(lines[::3],lines[1::3],lines[2::3]): 
        gloss=gloss.strip();text=text.strip();gramtree=gramtree.strip()
        if gramtree=='': continue  
        try: pat,vrb,sbj,obj = gramtree.split('\t')
        except: continue
        # need to get verbal orth and gloss here and add to the inst
        # used below to output choices
        vgloss = vrb.split()[-1].strip(")") 
        # EMB surely there's a better way to do this.  In fact, when we have the whole tree
        # we should be able to figure out if nodes are empty, but for now just checking that 
        # vgloss doesn't have VB as an initial substring.
        if re.match(r'VB',vgloss):
          print("error finding tree leaf material in gloss line",file=sys.stderr)
          gind=-1
        else: 
          gind = gloss.split().index(vgloss)
        vorth= text.split()[gind]
        inst = (grams(vrb), grams(sbj), grams(obj), vorth, vgloss)
        vgrams.update(inst[0])
        arggrams.update(inst[1])
        if pat in ('1', '2'):
            instances['intrans'] += [inst]
            s_inst += 1
        elif pat in ('3','4'):
            instances['trans'] += [inst]
            arggrams.update(inst[2])
            a_inst += 1
            o_inst += 1
        # EMB Count these separately since I don't want to increment a_inst counter when A is dropped.
        elif pat in ('5','6'):
            instances['trans'] += [inst]
            arggrams.update(inst[2])
            o_inst += 1
          
else:
    gramtreefile = sys.stdin
    
    for line in gramtreefile:
        line = line.strip()
        if line == '': continue
        pattern, vrb, sbj, obj = line.split('\t')
        inst = (grams(vrb), grams(sbj), grams(obj),line)
        vgrams.update(inst[0])
        arggrams.update(inst[1])
        if pattern in ('1', '2'):
            instances['intrans'] += [inst]
            s_inst += 1
        elif pattern in ('3','4'):
            instances['trans'] += [inst]
            arggrams.update(inst[2])
            a_inst += 1
            o_inst += 1
        elif pattern in ('5','6'):
            instances['trans'] += [inst]
            arggrams.update(inst[2])
            o_inst += 1




# Only keep vgrams that occur in 2% or more of the instances
thresh = (len(instances['trans']) + len(instances['intrans']))/50
# EMB I think we want separate threshholds for each of S, A, O, not just one overall number.
sthresh = s_inst / 50
if sthresh < 2: sthresh = 2
othresh = o_inst / 50
if othresh < 2: othresh = 2
athresh = a_inst / 50
if athresh < 2: athresh = 2


## vgrams aren't used below anywhere
## commenting out for now
if thresh < 2: thresh = 2
for k in list(vgrams.keys()):
    if vgrams[k] < thresh:
        del vgrams[k]

s_counts = Counter()
a_counts = Counter()
o_counts = Counter()
#all_pairs = []
for inst in instances['intrans']:
    s_counts.update(inst[1])
#all_pairs.extend(s_counts.keys())
for inst in instances['trans']:
    a_counts.update(inst[1])
    o_counts.update(inst[2])

#print('s_counts : ' + str(s_counts),file=sys.stderr)
#print('a_counts : ' + str(a_counts),file=sys.stderr)
#print('o_counts : ' + str(o_counts),file=sys.stderr)

# first filter out grams occuring less than the threshold (or less than 2)
for g in arggrams.keys():
    if s_counts[g] < sthresh: del s_counts[g]
    if a_counts[g] < athresh: del a_counts[g]
    if o_counts[g] < othresh: del o_counts[g]
# 

#print('s_counts : ' + str(s_counts),file=sys.stderr)
#print('a_counts : ' + str(a_counts),file=sys.stderr)
#print('o_counts : ' + str(o_counts),file=sys.stderr)


# # then filter out grams occuring in each category more than the threshold
for g in arggrams.keys():
    if s_counts[g] >= sthresh and \
       a_counts[g] >= athresh and \
       o_counts[g] >= othresh:
 #       print('deleting : ' + g,file=sys.stderr)
 #       print('sthresh : ' + str(sthresh),file=sys.stderr)
 #       print('athresh : ' + str(athresh),file=sys.stderr)
 #       print('othresh : ' + str(othresh),file=sys.stderr)
        del s_counts[g]
        del a_counts[g]
        del o_counts[g]
# 
s = s_counts.most_common()[:1] or None
a = a_counts.most_common()[:1] or None
o = o_counts.most_common()[:1] or None

#print('s most common: ' + s,file=sys.stderr)

case = 'none'

# EMB Fix it to deal with zeros.
# Check first whether any of s, a, o are actually empty.  If so, record that as a value with a threshhold high enough
# to pass the check below.

#print('s is : ' + str(s),file=sys.stderr)
#print('a is : ' + str(a),file=sys.stderr)
#print('o is : ' + str(o),file=sys.stderr)

if not s:
  s = [('no-case',sthresh+10)]

if not a:
  a = [('no-case',athresh+10)]

if not o:
  o = [('no-case',othresh+10)]




if s and a and o:
    s = s[0][0]
    a = a[0][0]
    o = o[0][0]
    if s == a and s != o: case = 'nom-acc'
    elif s == o and s != a: case = 'erg-abs'
    elif a_counts[s] < athresh and o_counts[s] < othresh and\
         s_counts[a] < sthresh and o_counts[a] < othresh and\
         s_counts[o] < sthresh and a_counts[o] < athresh:
        case = 'tripartite'
    elif s != a and s != o and a != o and \
         s_counts[a] > sthresh and s_counts[o] > sthresh:
        case = 'split-s'
    # split-n?
    # split-v?
print('case-marking={}'.format(case))


n = 0
if case=='none':
    print('verb1_valence=intrans')
    n=0
    for inst in instances['intrans']:
        n+=1
        print('  verb1_stem{}_orth={}'.format(n,inst[3]))
        print('  verb1_stem{}_pred=_{}_v_{}_rel'.format(n,inst[3],inst[4]))
    n=0
    print('verb2_valence=trans')
    for inst in instances['trans']:
        n+=1
        print('  verb2_stem{}_orth={}'.format(n,inst[3]))
        print('  verb2_stem{}_pred=_{}_v_{}_rel'.format(n,inst[3],inst[4]))
else:
    # TODO: need to address split-erg answer
    n=0
    print('verb1_valence={}'.format(s.lower()))
    for inst in instances['intrans']:
        n+=1
        print('  verb1_stem{}_orth={}'.format(n,inst[3]))
        print('  verb1_stem{}_pred=_{}_v_{}_rel'.format(n,inst[3],inst[4]))
    n=0
    print('verb2_valence={}-{}'.format(a.lower(),o.lower()))
    for inst in instances['trans']:
        n+=1
        print('  verb2_stem{}_orth={}'.format(n,inst[3]))
        print('  verb2_stem{}_pred=_{}_v_{}_rel'.format(n,inst[3],inst[4]))
