#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#==============================================================================
# Copyright (C) 2011 by Loïc Grobol
#
# This file is part of CTESLO.
# 
#    CTESLO is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
# 
#    CTESLO is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
# 
#    You should have received a copy of the GNU General Public License
#    along with CTESLO.  If not, see <http://www.gnu.org/licenses/>.
#==============================================================================

"""
Created on 21 juin 2011

@author: Loïc Grobol <loic.grobol@gmail.com>
"""
import sys, subprocess, os, tempfile
import argparse

# Ugly hack to allow absolute import from the root folder
# whatever its name is. Please forgive the heresy.
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir
    path.append(dir(dir(path[0])))

import libcteslo.dflib.columns_handling as dfch

DEFAULT_MODEL = "ressources/models/uncut_wleff_2011-01-06-3"
DEFAULT_LEFFF = "ressources/lefff_pickled"
DEFAULT_TOOL_INPUT = "in"
DEFAULT_TOOL_OUTPUT = "out"
TOOL_PATH = sys.path[0]
WAPITI_PATH = os.path.join(TOOL_PATH, "tagger")

def main(argv=sys.argv[1:]):
    """Main function."""
    parser = argparse.ArgumentParser(description="Execute cem tagger as a cteslo external tool.")
    parser.add_argument("--in-stream", "-i",
                        default=sys.stdin,
                        help="Text file to be processed. (default: stdin)")
    parser.add_argument("--out-file", "-o",
                        default=sys.stdout,
                        help="Output directory. (default: %(default)s).")
    parser.add_argument("--lefff", '-l',
                        default=os.path.join(sys.path[0], DEFAULT_LEFFF),
                        help="path/name of the lefff pickle dumped file. (default: %(default)s)")
    parser.add_argument("--model", '-m',
                        default=os.path.join(sys.path[0], DEFAULT_MODEL),
                        help="path/name of the model file (default: %(default)s)")

    args = parser.parse_args(argv)

    try:
        if args.in_stream.isatty():
            parser.print_help()
            return
    except AttributeError:
        args.in_stream= open(args.in_stream)
    
    # cem only handles file inputs, this allows to pass a stream input
    # to this helper.
    with tempfile.TemporaryDirectory(prefix=".cteslo_") as temp:
        tool_input = os.path.join(temp, DEFAULT_TOOL_INPUT)
        with open(tool_input, "w") as ti:
            ti.write(args.in_stream.read())


        # execute cem via python interpreter, in out_dir, with args.lefff lefff,
        # args.model model, on tool_input, which is a raw text file to be tokenized,
        # cleaning auxiliary files.
        cem = os.path.join(TOOL_PATH, "sem_tagger.py")
        cem_args = ["python", cem, "-l", args.lefff,
                 "-m", args.model, "-s", "-q", "-t", "POS+CHUNK",
                 "--no-tag", "-o", temp, tool_input]

        # Fancy info about exec"        
        #print('Invoking "cem_tagger {0}" :'.format(" ".join(cem_args[2:-3])))

        env = os.environ.copy()
        env["PATH"] += ":" + WAPITI_PATH
        subprocess.call(cem_args, cwd=TOOL_PATH, env=env)

        tool_output = os.path.join(temp, DEFAULT_TOOL_INPUT + "_out")
        dfch.stream_select(tool_output, args.out_file, (0, 1), "\t")

if __name__ == "__main__":
    sys.exit(main())
