#!/usr/bin/env python3

import sys
import re
from collections import Counter
import shlex, subprocess


## EMB Creating subroutines for determining overall case system and extracting case frames
## for particular verbs.

def get_verb_choices():
    #EMB Counters for null-marked instances, to see which case, if any, we want to assign to forms without case grams.
    null_s = 0
    any_s = 0
    null_o = 0
    any_o = 0
    null_a = 0
    any_a = 0

    # here we read 3 lines from stdin instead of singletons,
    # after we're done couning grams, we use the other lines to
    # create verbal choices: valence (case-frame), orth, pred
    lines = sys.stdin.readlines()
    # vso is the result of tgrepping the grammtree, may be a blank line
    for gloss,text,vso in zip(lines[::3],lines[1::3],lines[2::3]):
        # first go ahead and count any case grams
        get_case_grams_from_igt_item(gloss)
        gloss=gloss.strip(); text=text.strip(); vso=vso.strip()

        # now if have a tgrep result we may be able to find a caseframe 
        if not vso == "":
            try:
                pat,verb,subj,obj=vso.split('\t')
            except:
                continue
            o_grams='';s_grams=''
            if pat in ['3','4','5','6']:
                # trans
                ogmap = map(str.lower, gram_punc_re.sub(' ', obj).split())
                for g in ogmap:
                    if g in all_case_grams:
                        ogram=g
            sgmap = map(str.lower, gram_punc_re.sub(' ', subj).split())
            for g in sgmap:
                if g in all_case_grams:
                    s_grams=g

            # now get orth of verb by finding index of gloss 
            vgloss=verb.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)
            case_frame=''
            if gind==-1:
              print("!!Error finding gloss index",file=sys.stderr)
              print("vso",vso,"\nvgloss",vgloss,file=sys.stderr)
            else:
              if pat in ['1','2']:
                any_s +=1 
                # Intransitives
                if s_grams != '':
                  case_frame=s_grams
                else:
                  case_frame='default_s'
                  # EMB increment count of null marking on s
                  null_s += 1
              elif pat in ['3','4']:
                any_a += 1
                any_o += 1 
                if s_grams == '':
                   s_grams = 'default_a'
                   # EMB increment count of null marking on a
                   null_a += 1
                if o_grams == '':
                   o_grams = 'default_o'
                   # EMB increment count of null marking on o
                   null_o += 1
                case_frame=s_grams+"-"+o_grams
              elif pat in ['5','6']:
                #EMB NB: Not incrementing count of null marking here because whole argument is missing
                any_o += 1
                s_grams = 'default_a'
                if o_grams == '':
                   o_grams = 'default_o'
                   # EMB increment count of null marking on o
                   null_o += 1
                case_frame=s_grams+"-"+o_grams
              else:
                print("Error: couldn't make a case frame.",file=sys.stderr)

              if case_frame not in verb_types.keys():
                  verb_types[case_frame]=[]

              next_idx = len(verb_types[case_frame])+1
              verb_types[case_frame].append("  verb{}_stem"+str(next_idx)+"_orth="+text.split()[gind]+"\n" +\
                                            "  verb{}_stem"+str(next_idx)+"_pred=_"+text.split()[gind]+"_v_rel")


    #EMB: Next step is to get the overall case system and then rewrite the verb_types strings to replace
    #default_a, default_o, and default_s accordingly.  I think that goes in here.

    case_system = get_case_system()

    #EMB: Then after that next step is to add case constraints for any verb type that is not one of the basic
    #ones defined by the choice.
    # print("section=lexicon")

    for i,vt in enumerate(verb_types.keys()):
        print_valence(case_system,vt,i+1)
        for v in verb_types[vt]:
            print(v.format(i+1,i+1))    
               
    return null_a,any_a,null_o,any_o,null_s,any_s,case_system

def print_valence(case_system,verb_type,i):
    #Split verb_type on hyphen to get subj and obj (if any) case
    args = verb_type.split("-")

    if len(args) == 2:
        [subj,obj] = args
    elif len(args) == 1:
        [subj] = args
        obj = ''
    else:
        print("Error: more than two valence elements",file=sys.stderr)

    #If there's no case, just use trans and intrans for valence.
    if case_system == 'none':
         if obj:
             print('verb{}_valence={}'.format(i,'trans'))
         else:
             print('verb{}_valence={}'.format(i,'intrans'))

    #Otherwise, we need to figure out which cases to use as default, based on the system
    else:
        if case_system == 'nom-acc':
            default_a = 'nom' 
            default_o = 'acc'
            default_s = 'nom'

        if case_system == 'erg-abs':
            default_a = 'erg' 
            default_o = 'abs'
            default_s = 'abs'

        # JDC: what do we do about these if the system says split-erg?

        # Replace any place holders with the (now known) actual defaults)
        if subj == 'default_a':
              subj = default_a
        if subj == 'default_s':
              subj = default_s
        if obj == 'default_o':
              obj = default_o

        #transitives
        if obj:
             # We get one free built-in case frame, so use it if we can:
             if subj == default_a and obj == default_o:
                   print('verb{}_valence={}'.format(i,default_a+"-"+default_o))
             # Otherwise, we have to use the bland valence value and fill in case constraints
             else: 
                   print('verb{}_valence={}'.format(i,'trans'))
                   print('verb{}_feat1_name=case'.format(i))
                   print('verb{}_feat1_value={}'.format(i,subj))
                   print('verb{}_feat1_head=subj'.format(i))
                   print('verb{}_feat2_name=case'.format(i))
                   print('verb{}_feat2_value={}'.format(i,obj))
                   print('verb{}_feat2_head=obj'.format(i))
    
        #intransitives
        else:
    
             # We get one free built-in case frame, so use it if we can:
             if subj == default_s:
                   print('verb{}_valence={}'.format(i,default_s))
             # Otherwise, we have to use the bland valence value and fill in case constraints
             else: 
                   print('verb{}_valence={}'.format(i,'intrans'))
                   print('verb{}_feat1_name=case'.format(i))
                   print('verb{}_feat1_value={}'.format(i,subj))
                   print('verb{}_feat1_head=subj'.format(i))



def get_case_grams_from_igt_item(gloss):
    global item_count
    global case_grams
    gloss= gloss.strip()
    if gloss != '': 
        item_count+= 1
        grams = map(str.lower, gram_punc_re.sub(' ', gloss).split())
        for gram in grams:
            if gram in all_case_grams:
                case_grams[gram] += 1
               
def get_case_grams():
    for gloss in sys.stdin.readlines():
        get_case_grams_from_igt_item(gloss)

def get_case_system():
    # if a case gram appears in less than 2% of examples, discard it
    for gram, count in case_grams.items():
        if float(count)/float(item_count) < 0.02:
            case_grams[gram] = 0

    case='none'
    if case_grams['nom'] + case_grams['acc'] > 0 and \
       case_grams['erg'] + case_grams['abs'] == 0:
        case = 'nom-acc'
    elif case_grams['erg'] + case_grams['abs'] > 0 and \
       case_grams['nom'] + case_grams['acc'] == 0:
         case = 'erg-abs'
    elif case_grams['nom'] + case_grams['acc'] > 0 and \
       case_grams['erg'] + case_grams['abs'] > 0:
         case = 'split-erg'

    # print("section=case")
    print('case-marking={}'.format(case))
    
    # don't forget to define the case grams
    if case == 'nom-acc':
      print('  nom-acc-nom-case-name=nom')
      print('  nom-acc-acc-case-name=acc')
    elif case == 'erg-abs':
      print('  erg-abs-erg-case-name=erg')
      print('  erg-abs-abs-case-name=abs')

    # go ahead and define case names for all the other cases too
    for index,gram in enumerate(case_grams.items()):
      if gram not in ['erg','abs','nom','acc']:
        print('  case{}_name={}'.format(index+1,gram[0]))
    return(case)

def find_null_case(null_counts):
    [null_a,any_a,null_o,any_o,null_s,any_s,case_system] = null_counts
    if case_system == 'none':
        print('null-case=none')

    else:
        if case_system == 'erg-abs':
            null_erg_ratio = null_a / any_a
            null_abs_ratio = (null_o + null_s)/(any_o + any_s)
            if null_erg_ratio > null_abs_ratio and null_erg_ratio > .5:
                print('null-case=erg')
            elif null_abs_ratio > null_erg_ratio and null_abs_ratio > .5:
                print('null-case=abs')
            else:
                print('null-case=othercase')
    
        if case_system == 'nom-acc':
            null_acc_ratio = null_o / any_o
            null_nom_ratio = (null_a + null_s)/(any_a + any_s)
            if null_nom_ratio > null_acc_ratio and null_nom_ratio > .5:
                print('null-case=nom')
            elif null_acc_ratio > null_nom_ratio and null_acc_ratio > .5:
                print('null-case=acc')
            else:
                print('null-case=othercase')
    
                
        print('null-a : ' + str(null_a) + ' null-s : ' + str(null_s) + ' null-o : ' + str(null_o),file=sys.stderr)            
        print('any-a : ' + str(any_a) + ' any-s : ' + str(any_s) + ' any-o : ' + str(any_o),file=sys.stderr)            
        print('null-erg-ratio : ' + str(null_erg_ratio) + ' null-abs-ratio : ' + str(null_abs_ratio),file=sys.stderr)

## EMB action happens here

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

all_case_grams = {'nom', 'acc', 'abs', 'erg', 'abl', 'all', 
                  'com', 'dat', 'gen', 'ins', 'loc', 'obl' }

gram_punc_re = re.compile(r'\.|-|=|:')
verb_types={}


#Global variables
item_count = 0
case_grams = Counter()


if choices:
    null_counts = get_verb_choices()
    find_null_case(null_counts)
else:
    get_case_grams()
    get_case_system()
