#!/usr/bin/env python3

# script to extract a lexicon from an igtall file
#   

import sys
import igtall
import getopt
import re


#step 0, setup
# parse opts and args
# see if there's an option for dealing with case values on nouns
# 
try:
  opts,args = getopt.getopt(sys.argv[1:], 'c:s:a:o:N:')
except getopt.GetoptError as err:
  print(str(err),file=sys.stderr)
  exit(1)

find_case_method=''
not_marked=''
sao_case_names={'s':'','a':'','o':''}
for opt,arg in opts:
  if opt == '-c':
    if not arg in ['grams', 'sao']:
      print('Error: incorrect case value extraction method: '+arg,file=sys.stderr)
      print('Choose a known case value extraction method.\n'+\
            '  current options are "grams" or "sao".',file=sys.stderr)
    else:
      find_case_method = arg
  elif opt in ['-s','-a','-o']:
    if arg[0] == "-":
      print('Error: provide an argument for the {} case name.'.format(opt[-1].upper()),file=sys.stderr)
      print('       to treat {} case as unmarked, use -s 0'.format(opt[-1].upper()),file=sys.stderr)
      sys.exit(1)
    elif arg == '0':
      sao_case_names[opt[-1]]=''
    else:
      sao_case_names[opt[-1]]=arg
  elif opt == '-N':
    not_marked=arg
    # what to do with nouns not marked, used on gram method



# an apriori collection of case grams, used in 'grams' method
all_case_grams = ['nom', 'acc', 'abs', 'erg', 'abl', 'all', 
                  'com', 'dat', 'gen', 'ins', 'loc', 'obl']

# if find_case_method is sao, then we only look for specific case
# grams input by the user, all other nouns go in 'othercase'
if find_case_method=='sao':
  all_case_grams = [] 
  for k,v in sao_case_names.items():
    all_case_grams.append(v) 

# mapping from ptb type tags to matrix style type names
lextype_mapping = { "NN":"noun", "VB":"verb", "DT":"det" }

# storage containers for data we find
nouns={}
verbs={}
dets={}

# these regexes and grams method below are used to find
# just the grammatical grams on tree leaf node
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()]


# step 1 process the igtall file into a class so that we can access it in 
igta = igtall.IgtAllFile(args[0])


# step 2 
# for each item in igtall file, look at the projected tree and get 
# category names from the leaf nodes

# make regexes for the PTB category names
regexes = {}
for lt in lextype_mapping.keys():
  # remember to strip trailing ")" from results
  regexes[lt] = re.compile("\("+lt+"\S* (\S+)\)")

for igt in igta.igts: 
  projt = igt.get('projt')
  if not projt == None:
    for k in regexes.keys():
      matches = regexes[k].findall(projt) 
      if len(matches) > 0:
        for m in matches:
          orth = m.strip("()")
          if not orth == "":
            # as long as we found an orthography

            this_case = ''

            if find_case_method!='' and k=='NN':
              # if we found a noun and 
              # we are supposed to find case values
              gloss = igt.get('gloss')
              text  = igt.get('text')
              g_idx = text.split().index(orth)
              if g_idx != -1:
                # gs are the grammatical grams from the gloss line
                gs = grams(gloss.split()[g_idx])
                for g in gs:
                  g=g.lower()
                  if g in all_case_grams:
                    this_case = g
              if this_case == '':
                this_case=not_marked
                       
            # get translation lemma
            lemma = igt.get_trans_from_text(orth).lower()

            # got all the info, store it 
            if k=='NN':
              if not this_case in nouns.keys():
                nouns[this_case]={orth:{lemma:1}}
              elif not orth in nouns[this_case].keys():
                nouns[this_case][orth]={lemma:1}
              elif not lemma in nouns[this_case][orth].keys(): 
                nouns[this_case][orth][lemma]=1
              else: nouns[this_case][orth][lemma]+=1

            elif k=='VB':
              if not orth in verbs.keys():
                verbs[orth]={lemma:1}
              elif not lemma in verbs[orth].keys():
                verbs[orth][lemma]=1
              else: verbs[orth][lemma]+=1

            else: 
              if not orth in dets.keys():
                dets[orth]={lemma:1}
              elif not lemma in dets[orth].keys():
                dets[orth][lemma]=1
              else: dets[orth][lemma]+=1


# finally:
# format and print the lexical choices
#

# nouns
n=0
for case in nouns.keys():
  n+=1
  if find_case_method != '': 
    print("noun{}_feat1_name=case".format(n))
    if case =='':
      print("noun{}_feat1_value=othercase".format(n))
    else:
      print("noun{}_feat1_value={}".format(n,case))
  m=0
  print("noun{}_det=opt".format(n))
  for orth in nouns[case].keys():
    for lemma in nouns[case][orth].keys():
      m+=1
      print("  noun{}_stem{}_orth={}".format(n,m,orth))
      print("  noun{}_stem{}_pred=_{}_n_{}_rel".format(n,m,orth,lemma))

# verbs
# currently outputting all verbs as transitive
n=0
print("verb1_valence=trans")
for orth in verbs.keys():
  for lemma in verbs[orth].keys():
    n+=1
    print("  verb1_stem{}_orth={}".format(n,orth))
    print("  verb1_stem{}_pred=_{}_v_{}_rel".format(n,orth,lemma))

# determiners
n=0
for orth in dets.keys():
  for lemma in dets[orth].keys():
    n+=1
    print("det1_stem{}_orth={}".format(n,orth))
    print("det1_stem{}_pred=_{}_q_{}_rel".format(n,orth,lemma))
  

