#!/usr/bin/env python3.2
#
# script to clean up some numbering and 
# clean up some formatting
# and put out xigt examples that
# might, maybe^k^k^k^k^k^ should be processable by our 
# inference system

import sys
import re
import argparse
from collections import defaultdict
from itertools import zip_longest
import xigt.core as xigt
from xigt.codecs import xigtxml
import logging

# N_RE = re.compile('\s\(?\d+\.?\)\.?')
LINE_RE = re.compile('line=\d+ tag=(\S+):(.*)$')

def blocks(file, separator=None):
    """return the 8 line blocks as lists of lines, however
       smash the first 4 lines together because they're all 
       meta data, this gives you:
       [ meta, l1, l2, l3, ... ]"""

    blocks = []
    block = []
    i = 0
    for line in file:
        if line.strip()=="":
            if block:
                blocks.append(block)
                block = []
                i=0
        else:
            if i<3:
                if len(block) == 0:
                    block.append("")
                block[0]+=line
            else:
                block.append(line)
            i+=1
    
    return blocks

def cleanblocks(blocks):
    cleaned = []
    for b in blocks:
        fields = defaultdict(list)
        # see how many lines
        n = len(b)-1
        if n>0:
            tag = None
            for l in b[1:]:
                m = LINE_RE.match(l)
                if m:
                    curtag = m.group(1).strip()
                    if curtag in ('B', 'M'): continue
                    if curtag == 'C':
                        fields[tag][-1] += m.group(2)
                        continue
                    tag = curtag
                    if tag.endswith('+CR'):
                        tag = tag[:-3]
                    fields[tag].append(m.group(2))
            for f in fields.keys():
                if len(fields[f]) > 1:
                    fields[f] = merge_lines(fields[f])
                else:
                    fields[f] = fields[f][0]
                if fields[f] is not None:
                    fields[f] = fields[f].strip()
            #print("----+++++-----".join(b),file=sys.stderr)
            #print("looks like "+str(n)+" line igt\n",file=sys.stderr)
            # get the line 'tag' and associated codes    
            cleaned.append(fields)
    return cleaned

def merge_lines(lines):
    """ Only return merged lines if they can be merged cleanly,
            otherwise return None. """
    a = str(lines[0])
    for b in lines[1:]:
        merged = []
        charpairs = zip_longest(a, b, fillvalue=' ')
        for charpair in charpairs:
            l, r = charpair
            if l == ' ':
                merged.append(r)
            elif r == ' ':
                merged.append(l)
            else:
                return None
        a = ''.join(merged)
    return a

def id_line(fields):
    return ('Igt_id={} Url_id=X flag=0 cleaned=4 src_leng={} trans_leng={}'
            .format(fields['id'],
                    len(fields['G']), len(fields['L']), len(fields['T'])))

paren_re = re.compile(r'\([^)]*\)')
paren_num_re = re.compile(
    r"^\(\s*(" # start (X; ( X; group for alternates
    r"[\d.]+\w?|\w|" # 1 1a 1.a 1.23.4b; a b (no multiple chars, except...)
    r"[ivxlc]+)"    # roman numerals: i iv xxiii; end alt group
    r"['.:]*\s*\)[.:]*") # optional punc (X) (X:) (X') (X.) (X. ) (X). (X):
num_re = re.compile(
    r"([\d.]+\w?|\w|[ivxlc]+)" # nums w/no parens; same as above
    r"['.):]+\s") # necessary punc; 1. 1' 1) 1: 10.1a. iv: etc.
precontent_re = re.compile(r'^\s*\w+(\s\w+)?:\s')

def normalize_line(line):
    logging.debug("line transforms:")
    if line is None: return None
    logging.debug("---begin:")
    # remove spaces, quotes, and punctuation to make later regexes simpler
    logging.debug(line)
    line = line.strip().strip('''"'`.?!''')
    # only strip initial parens if on both sides (so we don't turn 'abc (def)'
    # into 'abc (def'
    logging.debug(line)
    if line.startswith('(') and line.endswith(')'): line = line[1:-1]
    # one more space, quote, and punc strip, in case the parens grouped them
    logging.debug(line)
    line = line.strip().strip('''"'`.?!''')
    # re-add a period (to all lines)
    logging.debug(line)
    line += ' .'
    # remove inner parens (with encapsulated content)
    # this seems to to go too far in some cases, see ace.item11
    logging.debug(line)
    line = paren_re.sub('', line)
    # IGT-initial numbers (e.g. '1.' '(1)', '5a.', '(ii)')
    logging.debug(line)
    line = paren_num_re.sub('', line)
    logging.debug(line)
    line = num_re.sub('', line)
    logging.debug(line)
    # precontent tags can be 1 or 2 words ("intended:" or "speaker", "a:")
    # ignore those with 3 or more
    line = precontent_re.sub('', line)
    # ignore ungrammatical or questionably lines or those with alternates
    # now we want to include these, separate out the # or * and mark the
    # judgments  for /, it's no longer a bother 
    # do this later anyway
    # if line.startswith('*') or line.startswith('#'): or '/' in line:
    #    return None
    logging.debug("---end:")
    return line.split()

#def clean_lg_line(line):
#    return ' '.join(normalize_line(line))
#
#def clean_gram_line(line):
#    return ' '.join(normalize_line(line))
#
#def clean_trans_line(line):
#    return ' '.join(normalize_line(line))

def setup_argparse():
    ap = argparse.ArgumentParser()
    ap.add_argument('--start-num', '-n', type=int, default=0, metavar='N',
                    help='Start counting IGTs from this number.')
    ap.add_argument('odinfile')
    ap.add_argument('--verbose', '-v', action='count', dest='verbosity',
                    default=2, 
                    help='increase the verbosity (can be repeated: -vvv)')
    ap.add_argument('--quiet', '-q', action='store_const', const=0,
                     dest='verbosity', 
                     help='set verbosity to the quietest level')
    return ap

if __name__ == "__main__":

    ap = setup_argparse()
    args = ap.parse_args()
    logging.basicConfig(format='%(levelname)s:%(message)s',
                        level=50-(args.verbosity*10))

    blks = blocks(open(args.odinfile,'r'))

    # now we need to clean the igt lines as best as we can
    # clnblks should look something like the expected output
    clnblks = cleanblocks(blks)

    logging.debug("input igt blocks: "+str(len(blks)))
    logging.debug("cleaned blocks: "+str(len(clnblks)))

    unclean = 0
    didalign= 0

    ## use xigt for output
    xigt_items = []

    ## corpus metadata tier
    c_meta = xigt.Metadata(type="odin-meta")
    for i, fields in enumerate(clnblks):
        fields['id'] = str(i + args.start_num)
        logging.debug(fields['id'])
        fields['L'] = normalize_line(fields.get('L'))
        fields['G'] = normalize_line(fields.get('G'))
        fields['T'] = normalize_line(fields.get('T'))

        # output original odin lines as odin tier
        o = xigt.Tier(type="odin-txt", id="o",
                      items=[xigt.Item(id="o"+str(j),
                      content=o.strip()) for j,o in enumerate(blks[i])])

        if fields.get('L') is not None and\
            fields.get('G') is not None and\
            fields.get('T') is not None:
            ## seems like we can't really do alignment
            ## with any confidence unless the counts of
            ## L and G items are equal (and greater than 0!)
            align = False
            stok_spans = {}
            c = 0
            for j,stok in enumerate(fields['L']):
                stok_spans[j]="["+str(c)+":"+str(len(stok)+c)+"]"
                c=c+len(stok)+1

            if (len(fields['L']) == len(fields['G'])) \
                and len(fields['L']) > 0:
                align = True
                didalign+=1

            ## if there's a # or * at the beginning of a line, we
            ## should strip it out and mark this example as having a
            ## negative judgment

            s = xigt.Tier(type="phrases", id="p", 
                items=[xigt.Item(id="p0", content=" ".join(fields['L']))])
            w = xigt.Tier(type="words", id="w", ref="p",
                items=[xigt.Item(id="w"+str(j), ref="p0"+stok_spans[j],
                       content=w) for j,w in enumerate(fields['L'])])
            if not align:
                g = xigt.Tier(type="glosses", id="g",
                    items=[xigt.Item(id="g"+str(j), content=g) 
                           for j,g in enumerate(fields['G'])])
            else:
                g = xigt.Tier(type="glosses", id="g", ref="s",
                    items=[xigt.Item(id="g"+str(j), ref="w"+str(j),
                           content=g) for j,g in enumerate(fields['G'])])
            t = xigt.Tier(type="translations", id="t", ref="p",
                          items=[xigt.Item(id="t0", ref="p0",
                                 content=" ".join(fields['T']))])
            item = xigt.Igt(id="i"+str(i), tiers=[o,s,w,g,t])
        else:
            item = xigt.Igt(id="i"+str(i), tiers=[o])
            unclean+=1
            logging.debug('this item '+str(i)+' excluded for uncleanness')
            pass # not a good IGT
        xigt_items.append(item)

    logging.info("Created XigtCorpus with "+str(len(xigt_items))+" items.")
    logging.info(str(didalign)+" items with computed alignments.")
    logging.info(str(unclean)+" items from input file output without further"+
                              " processing because of uncleanness.")
    xc = xigt.XigtCorpus(metadata=c_meta, igts=xigt_items)
    print('<?xml-version="1.0" encoding="utf-8"?>')
    print(xigtxml.dumps(xc, pretty_print=True))

    # sys.stdout.buffer.write(outlines.encode('utf-8'))

#    for b in cleanblks:
#        print("\n".join(b)) 
