#!/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 20 juin 2011

@author: Loïc Grobol <loic.grobol@gmail.com>
"""


import sys, subprocess, os, tempfile, shutil
import argparse

COMMAND = "label"
ADDITIONAL_OPTIONS = ["--post"]
TOOL_INPUT, TOOL_OUTPUT = "in", "out"
TOOL_PATH = os.path.join(sys.path[0], "bin", "wapiti")

MODELS_PATH = os.path.join(sys.path[0], "models")
MODELS = os.listdir(MODELS_PATH)

def main(argv=sys.argv[1:]):
    """Main function."""
    parser = argparse.ArgumentParser(description="Wrapper for easy wapiti train.")
    parser.add_argument("--in-stream", "-i",
                        type=argparse.FileType('r'),
                        default=sys.stdin,
                        help="Text stream to be processed. (default: stdin)")
    parser.add_argument("--out-stream", "-o",
                        default=sys.stdout,
                        help="Output stream. Wapiti result (default: stdout).")
    parser.add_argument("--model", "-m",
                        help='Model file. See defaults in the "models" directory.')

    args = parser.parse_args(argv)

    if args.in_stream.isatty():
        parser.print_help()
    else:

        with tempfile.TemporaryDirectory(prefix=".wapiti_wrap_") as tempdir:
            tool_input = os.path.join(tempdir, TOOL_INPUT)
            # handles open stream inputs
            with open(tool_input, "w") as ti:
                ti.write(args.in_stream.read())

            # fallback to default models if args.model doesn't exists
            if not os.path.exists(args.model):
                args.model = os.path.join(MODELS_PATH, args.model)

            tool_args = [TOOL_PATH, COMMAND, "-m", args.model]
            tool_args.extend(ADDITIONAL_OPTIONS)
            tool_output = os.path.join(tempdir, TOOL_OUTPUT)
            tool_args.append(tool_input)
            tool_args.append(tool_output)
            #print('Invoking "wapiti {0}" :'.format(" ".join(tool_args[1:-2])))
            subprocess.call(tool_args)

            shutil.copy2(tool_output, args.out_stream)

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