#!/usr/bin/env python3

import re
import sys
import argparse
from collections import OrderedDict

# a list of encodings to try when reading input files
encodings = ('utf-8', 'latin1', 'windows-1251', 'macgreek')

meta_re = re.compile(r'\s*(Language|Language code|Tiers|Lines|Author|Date|' +\
                     r'Source [^:]+)\s*:', flags=re.IGNORECASE|re.UNICODE)
igt_meta_re = re.compile(r'\s*(Source|Judge?ment|Vetted|Phenomen(a|on))\s*:',
                         flags=re.IGNORECASE|re.UNICODE)
bracket_re = re.compile(r'(\(|\)|\[|\])')

def norm(s): return s.strip().lower()
def despace(s): return ' '.join(s.split())
def format_translation(s): return despace(bracket_re.sub(' ', s)) + ' .'

def decode_testsuite(testsuite, transonly=False, startnum=0):
    all_lines = []
    meta, lines = pop_block(testsuite)
    tiers = meta.get('tiers', 'orth orth-seg gloss translat').split()
    igt_cnt = startnum
    while len(testsuite) > 0:
        meta, lines = pop_block(testsuite)
        try:
            if len(lines) != len(tiers):
                print('IGT has invalid number of tiers:\n', lines,
                      file=sys.stderr)
                continue
            tierdata = dict(zip(tiers, lines))
            if meta['judgment'] != 'u' and len(lines) >= 3:
                if transonly:
                    all_lines += [format_translation(tierdata['translat'])]
                else:
                    # assuming we want the last 3 lines of IGT (for the
                    # morph, gloss, and trans lines
                    morph = (tierdata.get('orth-seg') or \
                             tierdata.get('translit-seg') or\
                             tierdata.get('orth') or\
                             tierdata.get('translit')).strip() + ' .'
                    gloss = tierdata['gloss'].strip() + ' .'
                    gloss = gloss.replace(':','.').replace('=','-')
                    trans = format_translation(tierdata['translat'])
                    metaline = 'Igt_id={} '.format(igt_cnt) +\
                        'Url_id=X flag=0 cleaned=4 ' +\
                        'src_leng={} trans_leng={}'.format(len(morph.split()),
                                                           len(trans.split()))
                    all_lines += ['\n'.join([metaline,morph,gloss,trans])]
                    #all_lines += ['\n'.join([morph,gloss,trans])]
            igt_cnt += 1
        except: # Bare exception handling---bad!
            continue
    if transonly:
        all_lines = '\n'.join(all_lines)
    else:
        # add an extra newline for igts, so we can append more later
        all_lines = '\n\n'.join(all_lines) + '\n\n' 
    sys.stdout.buffer.write(all_lines.encode('utf-8'))

def pop_block(igt_lines):
    # side-effects: removes lines from igt_lines
    remove_blank_lines(igt_lines)
    in_igt_header = len(igt_lines) > 0 and igt_meta_re.match(igt_lines[0])
    meta = {}
    lines = []
    while len(igt_lines) > 0:
        line = igt_lines[0].strip()
        if line == '' or line.startswith('#'):
            igt_lines.pop(0)
            continue
        elif igt_meta_re.match(line):
            if in_igt_header == False:
                break
            else:
                key, val = line.split(':',1)
                # fix a common misspelling
                if norm(key) == 'judgement': key = 'judgment'
                meta[norm(key)] = norm(val)
        else:
            in_igt_header = False
            if meta_re.match(line):
                key, val = line.split(':',1)
                if norm(key) == 'lines': key = 'tiers'
                meta[norm(key)] = norm(val)
            else:
                lines += [line.strip('\'`".?!')] # remove quotes and punc
        igt_lines.pop(0)
    # remove following whitespace
    remove_blank_lines(igt_lines)
    return (meta, lines)

def remove_blank_lines(igt_lines):
    while len(igt_lines) > 0 and igt_lines[0].strip() == '':
        igt_lines.pop(0)

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('testsuite')
    args = ap.parse_args()

    testsuite = []
    for enc in encodings:
        try:
            testsuite = open(args.testsuite, 'rU', encoding=enc).readlines()
            break
        except UnicodeDecodeError as ex:
            if enc == encodings[-1]:
                print("Unable to find suitable encoding for file " + filename,
                      file=sys.stderr)
                sys.exit(-1)
    decode_testsuite(testsuite, args.trans_only, args.start_num)
