#!/usr/bin/env python3
#
# script to clean up some numbering and 
# clean up some formatting
# and put out plain text examples that
# might, maybe be processable by our 
# inference system

import sys
import re
import argparse
from collections import defaultdict
from itertools import zip_longest

# 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, ... ]"""

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

def cleanblocks(blocks):
    cleaned = []
    for b in blocks:
        fields = defaultdict(list)
        # see how many lines
        #n = len(b)-1
        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))
        # print("looks like "+str(n)+" line igt\n")
        # 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):
    if line is None: return None
    # remove spaces, quotes, and punctuation to make later regexes simpler
    line = line.strip().strip('''"'`.?!''')
    # only strip initial parens if on both sides (so we don't turn 'abc (def)'
    # into 'abc (def'
    if line.startswith('(') and line.endswith(')'): line = line[1:-1]
    # one more space, quote, and punc strip, in case the parens grouped them
    line = line.strip().strip('''"'`.?!''')
    # re-add a period (to all lines)
    line += ' .'
    # remove inner parens (with encapsulated content)
    line = paren_re.sub('', line)
    # IGT-initial numbers (e.g. '1.' '(1)', '5a.', '(ii)')
    line = paren_num_re.sub('', line)
    line = num_re.sub('', 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
    if line.startswith('*') or line.startswith('#') or '/' in line:
        return None
    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))

if __name__ == "__main__":

    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('--trans-only', '-t', action='store_true',
                    help='Only print the translation line.')
    ap.add_argument('odinfile')
    args = ap.parse_args()

    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)

    outlines = []
    for i, fields in enumerate(clnblks):
        fields['id'] = str(i + args.start_num)
        fields['L'] = normalize_line(fields.get('L'))
        fields['G'] = normalize_line(fields.get('G'))
        fields['T'] = normalize_line(fields.get('T'))
        if fields.get('L') is not None and\
             fields.get('G') is not None and\
             fields.get('T') is not None:
            #print(fields['L'])
            #print(fields['G'])
            #print(fields['T'])
            if args.trans_only:
                outlines.append(' '.join(fields['T']))
            else:
                outlines.append('\n'.join([id_line(fields),
                                           ' '.join(fields['L']),
                                           ' '.join(fields['G']),
                                           ' '.join(fields['T'])]))
        else:
            pass # not a good IGT
    if args.trans_only:
        outlines = '\n'.join(outlines)
    else:
        outlines = '\n\n'.join(outlines) + '\n\n'
    sys.stdout.buffer.write(outlines.encode('utf-8'))

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