#!/usr/bin/env python3
#
# goal of this script is to merge the case choices
# generated by case extraction into a mom lexicon
#
# the trick is that the case choices lexicon is 
# full-form, while the mom one has a morphotactic treatment
#
# first try:
# # 1. read in all the mom verb forms
# # 2. read the through the case'd lexicon
# #    -- if you find a mom verb as a subpart of a case'd verb
# #
# #    eg: mom verb:    "ca", "_eat_v_rel"
# #        case'd verb: u-ca-u-hatt-e, _u-ca-u-hatt-e_v_rel
# #        ^^^ that would be a match
# #    -- add that mom verb to this case type
# #      ---- to do that, need to create subtypes for mom verb types
# #           that have the relevant case constraint
# #
# #    --- note, mom verb types are all specified valence=trans, we need to remove this
# #        and output them underspecified (specificied instead on subtypes to be created
# #
# arg1 is the mom file
# arg2 is the case'd file

import sys
import re
V_NUM = re.compile('verb(\d+)')
V_VAL = re.compile('verb\d+_valence=(.*)$')
V_STEM_NUM = re.compile('verb\d+_stem(\d+)')
V_STEM_ORTH = re.compile('verb\d+_stem\d+_orth=(.*)$')
V_STEM_PRED = re.compile('verb\d+_stem\d+_pred=(.*)$')
V_FEAT_NUM = re.compile('verb\d+_feat(\d+)')
V_FEAT_NAME = re.compile('verb\d+_feat\d+_name=(.*)$')
V_FEAT_VALUE = re.compile('verb\d+_feat\d+_value=(.*)$')
V_FEAT_HEAD = re.compile('verb\d+_feat\d+_head=(.*)$')

def create_verb_dict(choicesfile):
  verbs = {}
  for l in choicesfile:
    if V_NUM.findall(l) != [] and \
       V_NUM.findall(l)[0] not in verbs.keys():
      # found a new verb entry, make a dictionary key
      verbs[V_NUM.findall(l)[0]] = { 'stems':{}, 'feats':{} }
  
    if V_STEM_NUM.findall(l) != [] and \
       V_STEM_NUM.findall(l)[0] not in verbs[V_NUM.findall(l)[0]]['stems']:
      # found a new stem, make a dictionary key
      verbs[V_NUM.findall(l)[0]]['stems'][V_STEM_NUM.findall(l)[0]] = {}
    
    if V_VAL.findall(l) != []:
      verbs[V_NUM.findall(l)[0]]['valence'] = V_VAL.findall(l)[0]

    elif V_FEAT_NAME.findall(l) != []:
      verbs[V_NUM.findall(l)[0]]['feats'][V_FEAT_NUM.findall(l)[0]]\
                                        = {'name':V_FEAT_NAME.findall(l)[0]}
    elif V_FEAT_VALUE.findall(l) != []:
      verbs[V_NUM.findall(l)[0]]['feats'][V_FEAT_NUM.findall(l)[0]]['value']= \
                                        V_FEAT_VALUE.findall(l)[0]
    elif V_FEAT_HEAD.findall(l) != []:
      verbs[V_NUM.findall(l)[0]]['feats'][V_FEAT_NUM.findall(l)[0]]['head']=\
                                        V_FEAT_HEAD.findall(l)[0]
    elif V_STEM_ORTH.findall(l) != []:
      verbs[V_NUM.findall(l)[0]]['stems'][V_STEM_NUM.findall(l)[0]]['orth'] = V_STEM_ORTH.findall(l)[0]

    elif V_STEM_PRED.findall(l) != []:
      verbs[V_NUM.findall(l)[0]]['stems'][V_STEM_NUM.findall(l)[0]]['pred'] = V_STEM_PRED.findall(l)[0]
  return verbs



momchoicesfile = open(sys.argv[1]).readlines()
casechoicesfile= open(sys.argv[2]).readlines()

## so first read the files into objects that we can read data from easily
caseverbs =  create_verb_dict(casechoicesfile)
momverbs =  create_verb_dict(momchoicesfile)

case_table = {}
# now loop through mom verbs and find potential matches
# notate them in a 'case_table' where for each mom-type is hashed
# to a list of case-types 
for i,v in momverbs.items():
  case_table[i] = {}
  for j,s in v['stems'].items():
    for k,w in caseverbs.items(): 
      for l,t in w['stems'].items():
        # dumb hack here because I can't get these python re's 
        # to match on end of string symbol
        if re.findall('[\-=]('+s['orth']+')[=\-]', "-"+t['orth']+"-") != []:
          if not k in case_table[i]:
            case_table[i][k]=[s]
          elif not s in case_table[i][k]:
            case_table[i][k].append(s)

## finally, loop through the types in momverbs and define subtypes for each
# corresponding types in the case_table
## for stems not found in the case table, make a valence=trans subtype and throw
# them in there

last_verb_type = len(momverbs.keys())+1
outverbs = {}
for i,v in momverbs.items():
  ## copy the current momverb type into the output types,
  ## this will be a supertype for all stems found in this type
  outverbs[i] = { 'stems':{}, 'feats':{}, 'name':'momtype'+str(i) }
  ## create a default subtype for any stem not found in the case table
  ## default subtype just takes the val that its super had
  default_subtype = ''
  
  for j,s in v['stems'].items():
    # see if this stem is in the case table
    for case_type_idx,stem_list in case_table[i].items():
      case_type_idx_subtype = ''
      if s in stem_list: 
        if case_type_idx_subtype == '':
          case_type_idx_subtype = last_verb_type+1
          last_verb_type+=1
          outverbs[str(case_type_idx_subtype)] = { 'stems':{}, 'feats':caseverbs[case_type_idx]['feats'],
                                                   'supertypes':[ 'verb'+i ],
                                                   'valence':caseverbs[case_type_idx]['valence']}

        nxt_stem = len(outverbs[str(case_type_idx_subtype)]['stems'].keys())+1
        outverbs[str(case_type_idx_subtype)]['stems'][str(nxt_stem)] = s
      else:
        if default_subtype == '':
          default_subtype = last_verb_type+1
          last_verb_type+=1
          outverbs[str(default_subtype)] = { 'stems':{}, 'feats':v['feats'],
                                             'supertypes':[ 'verb'+i ],
                                             'valence':v['valence']}
        ## assign to default type
        nxt_stem = len(outverbs[str(default_subtype)]['stems'].keys())+1
        outverbs[str(default_subtype)]['stems'][str(nxt_stem)] = s


## get nouns and dets from the cased choices
## and case section
NOUN_RE = re.compile('\s*noun\d')
DET_RE = re.compile('\s*det\d')

case_section=0
case_section_lines = []
lex_lines = []
for l in casechoicesfile:
  if l.find('section=case') != -1:
  # beginning of case section
    case_section=1
  elif case_section and l.find('section') != -1:
  # end of case section
    case_section=0
  if case_section:
    case_section_lines.append(l.rstrip())

  if NOUN_RE.match(l) or DET_RE.match(l):
    lex_lines.append(l.rstrip())

## print out the result, we'll use the mom choices file for everything up to
## lexicon (except case!)

case_section=0
for l in momchoicesfile:
  if l.find('section=lexicon') != -1:
    print (l.rstrip())
    print('\n'.join(lex_lines))
    break
  ## skip the case section
  elif l.find('section=case') != -1:
    case_section=1
  elif case_section and l.find('section') != -1:
    case_section=0
    print('\n'.join(case_section_lines))
  if not case_section:
    print(l.rstrip())


## print out the merged verbs 
for k in outverbs.keys():
  if 'valence' in outverbs[k]:
    print('verb'+k+'_valence='+outverbs[k]['valence'])
  else:
    print('verb'+k+'_name='+outverbs[k]['name'])
  if 'supertypes' in outverbs[k]:
    print('verb'+k+'_supertypes='+' '.join(outverbs[k]['supertypes']))
  for f in outverbs[k]['feats']:
    print('  verb'+k+'_feat'+f+'_name='+outverbs[k]['feats'][f]['name'])
    print('  verb'+k+'_feat'+f+'_head='+outverbs[k]['feats'][f]['head'])
    print('  verb'+k+'_feat'+f+'_value='+outverbs[k]['feats'][f]['value'])
  for s in outverbs[k]['stems']:
    print('  verb'+k+'_stem'+s+'_orth='+outverbs[k]['stems'][s]['orth'])
    print('  verb'+k+'_stem'+s+'_pred='+outverbs[k]['stems'][s]['pred'])

## finally print out the verb-pcs from the momlexicon
VERB_PC_RE = re.compile('\s*verb_pc')
for l in momchoicesfile:
  if VERB_PC_RE.match(l):
    print(l.rstrip())

print("section=test-sentences\n")
print("section=gen-options\n")
